Search code examples
pythonimage-processingblurgaussianblur

How to use different kernel shapes while blurring an image?


I want to use a fast blurring function like cv2.GaussianBlur() but it only allows for rectangular kernel shapes. Is there a way to use elliptic kernel shape? If any other blur function allows it, can you please suggest that function?


Solution

  • Instead of relying on built-in kernels or the built-in functions of opencv, use cv2.filter2D() function to apply a custom kernel of your choice with the values that you have chosen! With this you can apply not just "elliptic" kernel that you mentioned, but any kernel you want.

    Here is the usage:

    import cv2
    import numpy as np
    
    img = cv2.imread('image.png')
    
    kernel = np.ones((5,5),np.float32)/25
    dst = cv2.filter2D(img,-1,kernel)
    

    So in the above code, a kernel that looks like this:

    enter image description here

    is used.

    Now if you want an "elliptical" kernel, you can either manually build an np array (i.e kernel) with custom values in every row and column or you can use cv2.getStructuringElement function of cv2 to build the elliptical kernel for you and then you can use this kernel in filter2D() function.

    cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
    

    The above function will print:

    [[0, 0, 1, 0, 0],
     [1, 1, 1, 1, 1],
     [1, 1, 1, 1, 1],
     [1, 1, 1, 1, 1],
     [0, 0, 1, 0, 0]]
    

    which is your elliptical kernel!