使用带有高斯核的cv2.GaussianBlur和cv2.filter2D的不同结果?

2024-05-13 03:51:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在Python中移植一些lua/torch代码,有一个序列在图像上运行高斯模糊,如下所示:

local gauK = image.gaussian(math.ceil(3*sigma)*2+1, sigma)
inp = image.convolve(inp, gauK, 'same')

为了在我的方法中复制这一点,我一直在研究cv2.GaussianBlur()和cv2.filter2D,并传入一个高斯核。在

方法1(cv2.GaussianBlur):

^{pr2}$

方法2(cv2.filter2D)

kernel_size = int(math.ceil(3 * sigma) * 2 + 1)  # same size as the lua code
gaussian_kernel = cv2.getGaussianKernel(kernel_size, sigma)
blurred_image_2 = cv2.filter2D(img, -1, gaussian_kernel)

在方法1和方法2之间,我得到了不同的图像。似乎方法1的图像比方法2的图像更模糊。有什么原因让我在这里得到不同的结果?我想找出哪一个符合lua代码。谢谢。在


Tags: 方法代码图像imagesizemathgaussiancv2
2条回答

getGaussianKernel函数返回1D向量,使其成为2D高斯矩阵,可以用它的转置相乘(@用于矩阵乘法)。你能试试这个代码吗:

gaussian_kernel = cv2.getGaussianKernel(kernel_size, sigma)
kernel_2D = gaussian_kernel @ gaussian_kernel.transpose()
blurred_image_2 = cv2.filter2D(img, -1, kernel_2D)

这是一个奇怪的问题;为了实用起见,我建议你选一个你满意的并使用它。除此之外,我猜多个参数如何处理的语义导致了这种不匹配。另外,opencv从kernelsize推断sigma的公式(反之亦然)似乎与您的公式不符。在

来自GaussianBlur docs

  • ksize: Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. Or, they can be zero's and then they are computed from sigma.
  • sigmaX: Gaussian kernel standard deviation in X direction.
  • sigmaY: Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, respectively (see cv::getGaussianKernel for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY.

以及getGaussianKernel docs

  • If it is non-positive, it is computed from ksize as sigma = 0.3\*((ksize-1)\*0.5 - 1) + 0.8

所有的重点都是我的。你的西格玛有没有可能是负的?这可能会导致不匹配。在

编辑:刚刚注意到你想让这个和lua代码匹配。我的建议是保存结果,然后在photoshop或你最喜欢的图像编辑器中进行比较。如果你从参考中减去测试,你应该能够看到差异,而且随着你的尝试越来越近,整体上的差异应该会更小。除此之外,您可以尝试阅读源代码以找出定义上的差异,或者编写您自己的!在

祝你好运!在

相关问题 更多 >