In the previous articles, the Opening operation and the Closing operations were specified. In this article, another morphological operation is elaborated that is Gradient. It is used for generating the outline of the image. There are two types of gradients, internal and external gradient. The internal gradient enhances the internal boundaries of objects brighter than their background and external boundaries of objects darker than their background. For binary images, the internal gradient generates a mask of the internal boundaries of the foreground image objects.
Syntax: cv2.morphologyEx(image, cv2.MORPH_GRADIENT, kernel)
Parameters:
-> image: Input Image array.
-> cv2.MORPH_GRADIENT: Applying the Morphological Gradient operation.
-> kernel: Structuring element.
Below is the Python code explaining Gradient Morphological Operation –
Python3
import cv2
import numpy as np
screenRead = cv2.VideoCapture( 0 )
while ( 1 ):
_, image = screenRead.read()
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
blue1 = np.array([ 110 , 50 , 50 ])
blue2 = np.array([ 130 , 255 , 255 ])
mask = cv2.inRange(hsv, blue1, blue2)
res = cv2.bitwise_and(image, image, mask = mask)
kernel = np.ones(( 5 , 5 ), np.uint8)
gradient = cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, kernel)
cv2.imshow( 'Gradient' , gradient)
if cv2.waitKey( 1 ) & 0xFF = = ord ( 'a' ):
break
cv2.destroyAllWindows()
screenRead.release()
|
Result:

The output image frame shows the outline generated over the blue book and the blue object in top left.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
04 Jan, 2023
Like Article
Save Article