OpenCV | Blur in Python



Motion blur filter
Applying motion blur to an image is reduced to a convolution of the filter on the image. Examples of 5 * 5 filters are shown below.

vertical :

horizontal :

The larger the filter size, the greater the motion blur effect. In addition, direction 1 on the filter screen is the direction of the desired movement. To set motion blur in a specific direction of a vector, such as diagonally, simply place 1 along the vector to create a filter.

Code
Consider the following image of a car.


Code: Python code to apply motion blur to an image.

# library loading

import cv2

import numpy as np

 

img = cv2.imread ( `car.jpg` )

 
# Specify the kernel size.
# The larger the size, the more movement.

kernel_size = 30

 
# Create a vertical core.

kernel_v = np.zeros ((kernel_size, kernel_size))

 
# Make the same copy to create a horizontal kernel.

kernel_h = np.copy (kernel_v)

 
# Fill in middle row with them.

kernel_v [:, int ((kernel_size - 1 ) / 2 )] = np.ones (kernel_size)

kernel_h [ int ((kernel_size - 1 ) / 2 ),:] = np.ones (kernel_size)

 
Normalize

kernel_v / = kernel_size

kernel_h / = kernel_size

 
# Apply a vertical core.

vertical_mb = cv2.filter2D (img, - 1 , kernel_v)

  
# Use a horizontal core.

horizonal_mb = cv2.filter2D (img, - 1 , kernel_h)

 
Save the results.

cv2.imwrite ( `car_vertical.jpg` , vertical_mb)

cv2.imwrite ( ` car_horizontal.jpg` , horizonal_mb)

Exit

Vertical blur:

Horizontal blur: