Blurring and expanding images using OpenCV in Python

Morphological operations — it is a set of operations that process shape-based images. They apply a structuring element to an input image and generate an output image. 
The main morphological operations are two: erosion and dilatation
Basics of erosion:

  • Blurs the boundaries of the foreground object
  • Used to reduce image capabilities.

Erosion work:

  1. Kernel (matrix of odd size (3 , 5,7) collapsed with the image.
  2. A pixel in the original image (either 1 or 0) will be counted as 1 only if all pixels under the kernel are equal to 1, otherwise it is blurred (zeroed out).
  3. Thus, all pixels near the border will be discarded depending on the size of the kernel.
  4. Thus, the thickness or size of the foreground object is reduced or just the white area is reduced in the image.

Basics of dilatation:

  • Increases the area of ​​the object
  • Used to accentuate functions

Dilation work:

  1. Core (matrix of odd size (3 , 5,7) collapsed with the image
  2. The pixel element in the original image is “1” if at least one pixel under the kernel is “1”.
  3. Increases the white area in the image or increases the size of the foreground object

# Python program to demonstrate erosion and
# image extension.

import cv2

import numpy as np

 
# Read input image

img = cv2.imread ( `input.png` , 0 )

  
# Taking a size 5 matrix as the core

kernel = np.ones (( 5 , 5 ), np.uint8)

 
# The first parameter is the original image
# kernel - this is the matrix with which the image
# collapsed and the third parameter is a number
The number of iterations that will determine how much
# you want to destroy / expand the given image.

img_erosion = cv2.erode (img, kernel, iterations = 1 )

img_dilation = cv2.dilate (img, kernel, iterations = 1 )

  

cv2.imshow ( `Input` , img)

cv2.imshow ( `Erosion` , img_erosion)

cv2. imshow ( `Dilation` , img_dilation)

  

cv2.waitKey ( 0 )

The second image is a blurred shape of the original image, and the third image is an extended form. < br />
Using erosion and dilatation:

  1. Erosion:
    • This is useful for removing small white noise.
    • Used for detaching two related objects, etc.
  2. Stretching :
    • In cases such as noise removal, erosion is followed by expansion. Because erosion removes white noise, but it also reduces our subject. So we are expanding it. Since the noise has disappeared, they will not come back, but our object area increases.
    • This is also useful when connecting broken parts of an object.

article courtesy of Pratima Upadhyay . If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting an article contribute @ python.engineering. See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.