Top Hat and Black Hat Transform using Python-OpenCV
Last Updated :
03 Jan, 2023
In morphology and digital image processing, top-hat and black-hat transform are operations that are used to extract small elements and details from given images. These two types of transforms in which, the top-hat transform is defined as the difference between the input image and its opening by some structuring element, while the black-hat transform is defined as the difference between the closing and the input image. These transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others.
Here we will use Opening and Closing morphological operations.
Difference between Top-Hat and Black-Hat
The top-hat filter is used to enhance bright objects of interest in a dark background. The black-hat operation is used to do the opposite, enhance dark objects of interest in a bright background.
Example 1: Top-Hat Transform
Image used:
import cv2
filterSize = ( 3 , 3 )
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,
filterSize)
input_image = cv2.imread( "testing.jpg" )
input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
tophat_img = cv2.morphologyEx(input_image,
cv2.MORPH_TOPHAT,
kernel)
cv2.imshow( "original" , input_image)
cv2.imshow( "tophat" , tophat_img)
cv2.waitKey( 5000 )
|
Output:
As you can observe in the above image, the very small details are enhanced and taken out using the Top-Hat operation. Hence, it is useful in observing the minor details of the inputs when are present as light pixels on a dark background.
Example 2: Black Hat transform
Input Image:
import cv2
filterSize = ( 3 , 3 )
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,
filterSize)
input_image = cv2.imread( "testing.jpg" )
input_image = cv2.cvtColor(input_image, cv2.COLOR_BGR2GRAY)
tophat_img = cv2.morphologyEx(input_image,
cv2.MORPH_BLACKHAT,
kernel)
cv2.imshow( "original" , input_image)
cv2.imshow( "tophat" , tophat_img)
cv2.waitKey( 5000 )
|
Output:
Here in this image, all the objects which are white on a dark background are highlighted due to the Black Hat transformation applied to the input image.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...