How to do it...

  1. Import the Computer Vision package – cv2:
import cv2 
  1. Import the numerical Python package – numpy as np:
import numpy as np 
  1. Read the image using the built-in imread function:
image = cv2.imread('image_4.jpg')
  1. Display the original image using the built-in imshow function:
cv2.imshow("Original", image) 
  1. Wait until any key is pressed:
cv2.waitKey(0) 
  1. Given shape and type, fill it with ones:
# np.ones(shape, dtype) 
# 5 x 5 is the dimension of the kernel, uint8: is an unsigned integer (0 to 255) 
kernel = np.ones((5,5), dtype = "uint8") 
  1. cv2.erode is the built-in function used for erosion:
# cv2.erode(image, kernel, iterations) 
erosion = cv2.erode(image, kernel, iterations = 1) 
  1. Display the image after erosion using the built-in imshow function:
cv2.imshow("Erosion", erosion) 
  1. Wait until any key is pressed:
cv2.waitKey(0) 
  1. cv2.dilate is the built-in function used for dilation:
# cv2.dilate(image, kernel, iterations) 
dilation = cv2.dilate(image, kernel, iterations = 1) 
  1. Display the image after dilation using the built-in imshow function:
cv2.imshow("Dilation", dilation) 
  1. Wait until any key is pressed:
cv2.waitKey(0) 
  1. Close all windows:
cv2.destroyAllWindows()
  1. The command used to execute the Erosion_Dilation.py file is shown here:
  1. The input image used to execute the Erosion_Dilation.py file is shown here:
  1. The eroded image obtained after executing the Erosion_Dilation.py file is shown here:
  1. The dilated image obtained after executing the Erosion_Dilation.py file is shown here: