OpenCV实现二维高斯核GaussianKernel

本文详细对比了Matlab与OpenCV中高斯滤波器的实现方式,介绍了Matlab中fspecial函数与OpenCV中getGaussianKernel函数的参数设置与返回值,展示了如何在OpenCV中通过一维高斯核生成二维高斯核,并提供了代码示例,验证了两种方法的一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 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运行结果一致
高斯核

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值