NumCpp  2.12.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
gaussianFilter1d.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <cmath>
31#include <string>
32
34#include "NumCpp/Core/Types.hpp"
37#include "NumCpp/NdArray.hpp"
39
40namespace nc::filter
41{
42 //============================================================================
43 // Method Description:
55 template<typename dtype>
57 double inSigma,
58 Boundary inBoundaryType = Boundary::REFLECT,
59 dtype inConstantValue = 0)
60 {
61 if (inSigma <= 0)
62 {
63 THROW_INVALID_ARGUMENT_ERROR("input sigma value must be greater than zero.");
64 }
65
66 // calculate the kernel size based off of the input sigma value
67 constexpr uint32 MIN_KERNEL_SIZE = 5;
68 uint32 kernelSize =
69 std::max(static_cast<uint32>(std::ceil(inSigma * 2. * 4.)), MIN_KERNEL_SIZE); // 4 standard deviations
70 if (kernelSize % 2 == 0)
71 {
72 ++kernelSize; // make sure the kernel is an odd size
73 }
74
75 const auto kernalHalfSize = static_cast<double>(kernelSize / 2); // integer division
76
77 // calculate the gaussian kernel
78 NdArray<double> kernel(1, kernelSize);
79 for (double i = 0; i < kernelSize; ++i)
80 {
81 kernel[static_cast<uint32>(i)] = utils::gaussian1d(i - kernalHalfSize, 0., inSigma);
82 }
83
84 // normalize the kernel
85 kernel /= kernel.sum().item();
86
87 // perform the convolution
88 NdArray<dtype> output =
89 convolve1d(inImageArray.template astype<double>(), kernel, inBoundaryType, inConstantValue)
90 .template astype<dtype>();
91
92 return output;
93 }
94} // namespace nc::filter
#define THROW_INVALID_ARGUMENT_ERROR(msg)
Definition: Error.hpp:37
Holds 1D and 2D arrays, the main work horse of the NumCpp library.
Definition: NdArrayCore.hpp:139
value_type item() const
Definition: NdArrayCore.hpp:3022
self_type sum(Axis inAxis=Axis::NONE) const
Definition: NdArrayCore.hpp:4618
Definition: addBoundary1d.hpp:44
NdArray< dtype > convolve1d(const NdArray< dtype > &inImageArray, const NdArray< dtype > &inWeights, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition: convolve1d.hpp:54
NdArray< dtype > gaussianFilter1d(const NdArray< dtype > &inImageArray, double inSigma, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition: gaussianFilter1d.hpp:56
Boundary
Boundary condition to apply to the image filter.
Definition: Boundary.hpp:36
double gaussian1d(double inX, double inMu, double inSigma) noexcept
Definition: gaussian1d.hpp:46
dtype ceil(dtype inValue) noexcept
Definition: ceil.hpp:48
std::uint32_t uint32
Definition: Types.hpp:40
NdArray< dtype > max(const NdArray< dtype > &inArray, Axis inAxis=Axis::NONE)
Definition: max.hpp:44