OpenCV实现二维高斯核GaussianKernel

  • matlab:
    matlab示例

h = fspecial(‘gaussian’, hsize, sigma) returns a rotationally symmetric Gaussian lowpass filter of size hsize with standard deviation sigma (positive). hsize can be a vector specifying the number of rows and columns in h, or it can be a scalar, in which case h is a square matrix. The default value for hsize is [3 3]; the default value for sigma is 0.5. Not recommended. Use imgaussfilt or imguassfilt3 instead.


示例:

G=fspecial('gaussian', 3, 1)

result:

G =
    0.0751    0.1238    0.0751
    0.1238    0.2042    0.1238
    0.0751    0.1238    0.0751
  • OpenCV:

在openCV中也有函数getGaussianKernel(int ksize, double sigma, int ktype=CV_64F)实现计算高斯核


getGaussianKernel
Returns Gaussian filter coefficients.

C++: Mat getGaussianKernel(int ksize, double sigma, int ktype=CV_64F )
Python: cv2.getGaussianKernel(ksize, sigma[, ktype]) → retval
Parameters:
ksize – Aperture size. It should be odd ( \texttt{ksize} \mod 2 = 1 ) and positive.
sigma – Gaussian standard deviation. If it is non-positive, it is computed from ksize as sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8 .
ktype – Type of filter coefficients. It can be CV_32F or CV_64F .
The function computes and returns the \texttt{ksize} \times 1 matrix of Gaussian filter coefficients:

G_i= \alpha e^{-(i-( \texttt{ksize} -1)/2)^2/(2 \texttt{sigma} )^2},

where i=0..\texttt{ksize}-1 and \alpha is the scale factor chosen so that \sum_i G_i=1.

Two of such generated kernels can be passed to sepFilter2D(). Those functions automatically recognize smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. You may also use the higher-level GaussianBlur().


然而使用getGaussianKernel(int ksize, double sigma, int ktype=CV_64F)获得的高斯核是一维的,那又怎么获得2维的高斯核呢?
非常简单,使用以下语句就可以办到

    Mat kernelX = getGaussianKernel(3, 1);  
    cout << kernelX << endl << endl << endl;

    Mat kernelY = getGaussianKernel(3, 1);
    cout << kernelY<< endl << endl << endl; 

    Mat G = kernelX * kernelY.t();
    cout << G << endl << endl << endl;

运行结果如下:
跟matlab运行结果一致
OpenCV实现二维高斯核GaussianKernel_第1张图片

你可能感兴趣的:(opencv)