NumCpp  2.12.1
A Templatized Header Only C++ Implementation of the Python NumPy Library
gaussianFilter.hpp
Go to the documentation of this file.
1
28#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
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(kernelSize);
79 for (double row = 0; row < kernelSize; ++row)
80 {
81 for (double col = 0; col < kernelSize; ++col)
82 {
83 kernel(static_cast<uint32>(row), static_cast<uint32>(col)) =
84 utils::gaussian(row - kernalHalfSize, col - kernalHalfSize, inSigma);
85 }
86 }
87
88 // normalize the kernel
89 kernel /= kernel.sum().item();
90
91 // perform the convolution
92 NdArray<dtype> output =
93 convolve(inImageArray.template astype<double>(), kernelSize, kernel, inBoundaryType, inConstantValue)
94 .template astype<dtype>();
95
96 return output;
97 }
98} // 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 > convolve(const NdArray< dtype > &inImageArray, uint32 inSize, const NdArray< dtype > &inWeights, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition: convolve.hpp:60
NdArray< dtype > gaussianFilter(const NdArray< dtype > &inImageArray, double inSigma, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition: gaussianFilter.hpp:56
Boundary
Boundary condition to apply to the image filter.
Definition: Boundary.hpp:36
double gaussian(double inX, double inY, double inSigma) noexcept
Definition: gaussian.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