Performing an opening operation on an image using OpenCV

OpenCVPythonServer Side ProgrammingProgramming

In this program, we will perform the opening operation on image. Opening removes small objects from the foreground of an image, placing them in the background. This technique can also be used to find specific shapes in an image. Opening can be called erosion followed by dilation. The function we will use for this task is cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel).

Original Image


Step 1: Import cv2 and numpy.
Step 2: Read the image.
Step 3: Define the kernel.
Step 4: Pass the image and kernel to the cv2.morphologyex() function.
Step 4: Display the output.

Example Code

import cv2
import numpy as np

image = cv2.imread('testimage.jpg')
kernel = np.ones((5,5), np.uint8)

image = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)
cv2.imshow('Opening', image)


Published on 17-Mar-2021 12:38:11