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