NumCpp  2.9.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
gaussianFilter.hpp
Go to the documentation of this file.
1 #pragma once
29 
30 #include <cmath>
31 #include <string>
32 #include <utility>
33 
35 #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(kernelSize);
81  for (double row = 0; row < kernelSize; ++row)
82  {
83  for (double col = 0; col < kernelSize; ++col)
84  {
85  kernel(static_cast<uint32>(row), static_cast<uint32>(col)) =
86  utils::gaussian(row - kernalHalfSize, col - kernalHalfSize, inSigma);
87  }
88  }
89 
90  // normalize the kernel
91  kernel /= kernel.sum().item();
92 
93  // perform the convolution
94  NdArray<dtype> output =
95  convolve(inImageArray.template astype<double>(), kernelSize, kernel, inBoundaryType, inConstantValue)
96  .template astype<dtype>();
97 
98  return output;
99  }
100  } // namespace filter
101 } // 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 > gaussianFilter(const NdArray< dtype > &inImageArray, double inSigma, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition: gaussianFilter.hpp:58
NdArray< dtype > convolve(const NdArray< dtype > &inImageArray, uint32 inSize, const NdArray< dtype > &inWeights, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition: convolve.hpp:62
Boundary
Boundary condition to apply to the image filter.
Definition: Boundary.hpp:38
double gaussian(double inX, double inY, double inSigma) noexcept
Definition: gaussian.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