Advertisement

通过OpenCV生成二维高斯核及其Python实现

阅读量:

官方文档提供getGaussianKernel函数的具体实现细节

Python:
cv2.getGaussianKernel(ksize, sigma[, ktype]) → retval
Parameters:

  • ksize – Aperture size, which must be an odd integer ( \texttt{ksize} \% 2 == 1 ) and a positive value.
  • sigma – Gaussian standard deviation, which determines the extent of Gaussian blur applied to the image. When it’s not positive, OpenCV calculates its value based on the formula: sigma = 0.3*((ksize-1)*0.5 - 1) + 0.8.
  • ktype – Determines the precision of the filter coefficients used in edge detection algorithms. The supported options are either CV_32F for single-precision floating-point coefficients or CV_64F for double-precision floating-point coefficients.

This function calculates a \texttt{ksize} \times 1 matrix of Gaussian filter coefficients, defined by G_i = \alpha e^{-\left(i - (\texttt{ksize} - 1)/2\right)^2 / (2\,\texttt{sigma})^2}, where each index i ranges from 0 to \texttt{ksize}-1, and \alpha is selected such that the sum of all coefficients equals one.

Two such-generated kernels can be passed to the sepFilter2D function. The functions automatically recognize smoothing kernels, which are symmetrical with a sum of weights equal to 1, and handle them appropriately. Additionally, a higher-level GaussianBlur function is available.

复制代码
    >>> import cv2 as cv
    >>> cv.getGaussianKernel(3, 1)
    array([[0.27406862],
       [0.45186276],
       [0.27406862]])
    
    
    python
    
    运行

此时返回的是一维的高斯核。要获取二维的高斯核也很简单:

复制代码
    >>> def gaussian_kernel_2d(ksize, sigma):
    		return cv.getGaussianKernel(ksize, sigma) * cv.getGaussianKernel(ksize,sigma).T
    		
    >>> gaussian_kernel_2d(3,1)
    array([[0.07511361, 0.1238414 , 0.07511361],
       [0.1238414 , 0.20417996, 0.1238414 ],
       [0.07511361, 0.1238414 , 0.07511361]])
    
    
    python
    
    运行

全部评论 (0)

还没有任何评论哟~