Home > Mobile >  Kernel for Gaussian Blur
Kernel for Gaussian Blur

Time:11-02

I am trying to make a kernel for GaussianBlur, but I have no idea how to do it. I have tried this, but it throws an error.

    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)

Is it possible to change kernels? I have been looking for a solution, but without result.

CodePudding user response:

You have mixed the Opencv's inbuilt method of Gaussian blurring and custom kernel filtering method. Let us see the two methods below:

First load the original image

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

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

enter image description here

If you want to use the inbuilt method, then you do not need to make the kernel yourself. Just define its size (size=11x11 below):

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

enter image description here

If you want to use your own kernel. Use filter2D method:

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

enter image description here

  • Related