高斯模糊的内核

Kernel for Gaussian Blur

我正在尝试为 GaussianBlur 制作内核,但我不知道该怎么做。 我已经试过了,但它会引发错误。

    import cv2 as cv
    import numpy as np
    
    img = cv.imread('lena_gray.bmp')
    
    x = np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]])
#x2 = np.array([[0, -1, 0], [-1, 4, -1], [0, -1, 0]]) I also need the ability to use other types of kernels like this one
    img_rst = cv.GaussianBlur(img, kernel=x)
    cv.imwrite('result.jpg', img_rst)

是否可以更换内核?我一直在寻找解决方案,但没有结果。

您混合了 Opencv 的内置高斯模糊方法和自定义内核过滤方法。让我们看看下面的两种方法:

先加载原图

import cv2
from matplotlib import pyplot as plt
import numpy as np

img_path = 'Lena.png'
image = plt.imread(img_path)
plt.imshow(image)

如果你想使用内置的方法,那么你不需要自己制作内核。只需定义它的尺寸(下图尺寸=11x11):

img_blur = cv2.blur(src=image, ksize=(11,11))
plt.imshow(img_blur)

如果你想使用自己的内核。使用filter2D方法:

blur_kernel = np.ones((11, 11), np.float32) / 121
kernel_blurred = cv2.filter2D(src=image, ddepth=-1, kernel=blur_kernel)
plt.imshow(kernel_blurred)