Search code examples
pythonopencvimage-processinggaussianblur

How to demonstrate the Gaussian Kernal used in opencv GausssianBlurr, using the instruction `GaussianBlur()` from OpenCV?


  • I want to demonstrate the Gaussian Kernel used in openCV. cv2.GaussianBlurr(img, kernel_size, sigma) for explanation purposes.
  • I know how to demonstrate the image which results after applying the blur, and that is not my objective here.
  • My objective is to demonstrate the kernel automatically for any used sigma, and any used kernel size!
  • I have seen a code(mentioned down) but I prefer to use something more related to instruction used in OpenCV, rather than just a general mathematical dependent approach.
  • The expected output kernel is something like this:

image

import cv2
import numpy as np

# Read Image
img_path = 'image.jpg'
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Gaussian Blurr
Kernel = np.ones((15,15))
sigma = 2

Blurred_Image = cv2.GaussianBlur(img, (Kernel.shape[0], Kernel.shape[1]), sigma)

Gaussian Kernel Manual Code:

def dnorm(x, mu, sd):
    return 1 / (np.sqrt(2 * np.pi) * sd) * np.e ** (-np.power((x - mu) / sd, 2) / 2)

def gaussian_kernel(size, sigma=1, verbose=False):
 
    kernel_1D = np.linspace(-(size // 2), size // 2, size)
    for i in range(size):
        kernel_1D[i] = dnorm(kernel_1D[i], 0, sigma)
    kernel_2D = np.outer(kernel_1D.T, kernel_1D.T)
 
    kernel_2D *= 1.0 / kernel_2D.max()
 
    if verbose:
        plt.imshow(kernel_2D, interpolation='none',cmap='gray')
        plt.title("Image")
        plt.show()
 
    return kernel_2D

Solution

  • Here is one way in Python/OpenCV.

     - Read the input
     - Create a delta image (one white pixel in the center of a black background)
     - Blur the image
     - List item
     - Resize the image to enlarge it
     - Stretch the image to full dynamic range
     - Save the result
    

    import cv2
    import numpy as np
    import skimage.exposure as exposure
    
    # create delta image
    dims = 30
    dims2 = 30 // 2
    delta = np.zeros((dims,dims,3), dtype=np.float32)
    delta[dims2:dims2+1, dims2:dims2+1] = (255,255,255)
    
    # blur image
    blur = cv2.GaussianBlur(delta, (0,0), sigmaX=5, sigmaY=5)
    
    # resize 16x
    dims4x = dims * 16
    resized = cv2.resize(blur, (dims4x,dims4x), interpolation = cv2.INTER_AREA)
    
    # stretch to full dynamic range
    result = exposure.rescale_intensity(resized, in_range='image', out_range=(0,255)).astype(np.uint8)
    
    # save image
    cv2.imwrite('delta.png',delta)
    cv2.imwrite('gaussian_blur_view.png',result)
    
    # show the images
    cv2.imshow("delta", delta)
    cv2.imshow("result", result)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    Delta image:

    enter image description here

    Result:

    enter image description here