Python | Morphological operations in image processing (gradient) | Set-3

In the previous articles, the opening and closing operations were specified. In this article, another morphological operation has been developed —  gradient . It is used to generate the outline of an image. There are two types of gradients, inner and outer gradient. Inner gradient makes the inner edges of objects brighter than their background, and the outer edges of objects are darker than their background. For binary images, the inner gradient creates a mask of the inner borders of foreground image objects.

Syntax: cv2.morphologyEx (image, cv2.MORPH_GRADIENT, kernel)

Parameters:
– & gt;  image : Input Image array.
– & gt;  cv2.MORPH_GRADIENT : Applying the Morphological Gradient operation.
– & gt;  kernel : Structuring element.

Below is the Python code explaining the gradient of the morphological operation —

# Python program for illustration
# Gradient of morphological operation
# on input frames

 
# organization of import

import cv2 

import numpy as np 

  
# return video from the first webcam on your computer.

screenRead = cv2 .VideoCapture ( 0 )

 
# the loop starts if there was a capture initialized.

while ( 1 ):

# reads frames from the camera

_, image = screenRead.read ()

 

  # Converts to HSV color space, OCV reads colors as BGR

  # the frame is converted to hsv

hsv = cv2.cvtColor (image, cv2.COLOR_BG R2HSV)

 

# define the masking range

blue1 = np.array ([ 110 , 50 , 50 ])

blue2 = np.array ([ 130 , 255 , 255 ])

 

# initialize the mask for

  # collapsed above the input image

  mask = cv2.inRange (hsv, blue1, blue2)

 

# bitwise_and transfer

# every pixel is meandering

res = cv2.bitwise_and (image, image, mask = mask)

 

# core definition i.e. structuring element

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

  

# gradient function definition

# over the image and structuring element

gradient = cv2.morphologyEx (mask, cv2.MORPH_GRADIENT, kernel)

 

# Mask and close operation

# display in the window

cv2.imshow ( `Gradient` , gradient)

  

# Wait for the "a" key to stop the program

  if cv2.waitKey ( 1 ) & amp;  0xFF = = ord ( `a` ):

break

  
# Deallocate any associated memory usage
cv2.destroyAllWindows ()

 
# Close window / release webcam
screenRead.release ()

Result:

Frame of the output the image shows the outline created over the blue book and the blue ob object in the upper left corner.