NumCpp  2.18.0
A Templatized Header Only C++ Implementation of the Python NumPy Library
Loading...
Searching...
No Matches
gaussianFilter.hpp
Go to the documentation of this file.
1
28#pragma once
29
30#include <cmath>
31
33#include "NumCpp/Core/Types.hpp"
35#include "NumCpp/NdArray.hpp"
37
38namespace nc::filter
39{
40 //============================================================================
41 // Method Description:
53 template<typename dtype>
55 double inSigma,
56 Boundary inBoundaryType = Boundary::REFLECT,
57 dtype inConstantValue = 0)
58 {
59 if (inSigma <= 0)
60 {
61 THROW_INVALID_ARGUMENT_ERROR("input sigma value must be greater than zero.");
62 }
63
64 // calculate the kernel size based off of the input sigma value
65 constexpr uint32 MIN_KERNEL_SIZE = 5;
66 uint32 kernelSize =
67 std::max(static_cast<uint32>(std::ceil(inSigma * 2. * 4.)), MIN_KERNEL_SIZE); // 4 standard deviations
68 if (kernelSize % 2 == 0)
69 {
70 ++kernelSize; // make sure the kernel is an odd size
71 }
72
73 const auto kernalHalfSize = static_cast<double>(kernelSize / 2); // integer division
74
75 // calculate the gaussian kernel
76 NdArray<double> kernel(kernelSize);
77 for (double row = 0; row < kernelSize; ++row)
78 {
79 for (double col = 0; col < kernelSize; ++col)
80 {
81 kernel(static_cast<uint32>(row), static_cast<uint32>(col)) =
82 utils::gaussian(row - kernalHalfSize, col - kernalHalfSize, inSigma);
83 }
84 }
85
86 // normalize the kernel
87 kernel /= kernel.sum().item();
88
89 // perform the convolution
90 NdArray<dtype> output =
91 convolve(inImageArray.template astype<double>(), kernelSize, kernel, inBoundaryType, inConstantValue)
92 .template astype<dtype>();
93
94 return output;
95 }
96} // 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:135
value_type item() const
Definition NdArrayCore.hpp:3098
self_type sum(Axis inAxis=Axis::NONE) const
Definition NdArrayCore.hpp:4694
Definition addBoundary1d.hpp:42
NdArray< dtype > convolve(const NdArray< dtype > &inImageArray, uint32 inSize, const NdArray< dtype > &inWeights, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition convolve.hpp:58
NdArray< dtype > gaussianFilter(const NdArray< dtype > &inImageArray, double inSigma, Boundary inBoundaryType=Boundary::REFLECT, dtype inConstantValue=0)
Definition gaussianFilter.hpp:54
Boundary
Boundary condition to apply to the image filter.
Definition Boundary.hpp:36
@ REFLECT
Definition Boundary.hpp:37
double gaussian(double inX, double inY, double inSigma) noexcept
Definition gaussian.hpp:46
NdArray< dtypeOut > astype(const NdArray< dtype > inArray)
Definition astype.hpp:43
std::uint32_t uint32
Definition Types.hpp:40