Black Hat
The black-hat operation is used to do the opposite, enhancing dark objects of interest on a bright background. The output of this operation is the difference between the closing of the input image and the input image.
Code:
- Import the necessary packages as shown.
- Read the image.
- Binarize the image.
- As it is advised to keep the foreground white, we are performing OpenCV’s invert operation on the binarized image to make the foreground as white.
- We are defining a 5×5 kernel filled with ones.
- Then we can use the Opencv cv.morphologyEx() function to perform a Top Hat operation on the image.
Python3
# import the necessary packages import cv2 # read the image img = cv2.imread( "your image path" , 0 ) # binarize the image binr = cv2.threshold(img, 0 , 255 , cv2.THRESH_BINARY + cv2.THRESH_OTSU)[ 1 ] # define the kernel kernel = np.ones(( 5 , 5 ), np.uint8) # invert the image invert = cv2.bitwise_not(binr) # use morph gradient morph_gradient = cv2.morphologyEx(invert, cv2.MORPH_BLACKHAT, kernel) # print the output plt.imshow(morph_gradient, cmap = 'gray' ) |
Output:
Python OpenCV – Morphological Operations
Python OpenCV Morphological operations are one of the Image processing techniques that processes image based on shape. This processing strategy is usually performed on binary images.
Morphological operations based on OpenCV are as follows:
- Erosion
- Dilation
- Opening
- Closing
- Morphological Gradient
- Top hat
- Black hat
For all the above techniques the two important requirements are the binary image and a kernel structuring element that is used to slide across the image.