Morphological operations—top hat operations

  Top hat operation is an operation in image morphology processing, which is used to highlight small brightness changes or local brightness differences in the image. This operation can highlight the fine details in the image and is usually widely used in image enhancement, feature extraction and other fields.
Principle:
  Top hat operation is implemented by taking the difference between the original image and its opening operation (Opening). The opening operation is to first erode the image and then perform a dilation operation, which can eliminate small objects in the image, smooth the boundaries of objects, and retain the structural characteristics of large objects. The top hat operation is to subtract the image after the opening operation from the original image. The result is to highlight the small features and details in the original image.
Mathematical formula:
  The mathematical expression of the top hat operation is: TopHat ( I ) = I − Opening ( I ​​) \ text{TopHat}(I) = I - \text{Opening}(I) TopHat(I)=IOpening(I)
  其中, I I I Display primitive image, TopHat ( I ) \text{TopHat}(I) TopHat(I) means performing top hat operation The resulting image.
Code example (using Python’s OpenCV library):

import cv2
import numpy as np

def show_images(image):
    cv2.namedWindow('image',cv2.WINDOW_KEEPRATIO)
    cv2.imshow('image',image)
    cv2.waitKey()
    cv2.destroyAllWindows()

def Top_hat(image):
    # 定义结构元素(这里使用一个 5x5 的正方形结构元素)
    kernel = np.ones((5, 5), np.uint8)
    # 执行开运算
    opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)
    # 执行顶帽运算
    tophat = cv2.subtract(image, opening)
    return tophat

if __name__ == '__main__':
    # 读取图像
    img = cv2.imread('cat-dog.png', flags=0)
    re_img=Top_hat(img)
    # top_row = np.hstack((img, re_img[0]))
    # bottom_row = np.hstack((re_img[1], re_img[2])) #水平
    # combined_img = np.vstack((img, re_img))# 垂直
    combined_img=np.hstack((img,re_img))
    show_images(combined_img)

Applicable scene:

  1. Image enhancement: Highlight the subtle details in the image to make the image clearer.
  2. Feature extraction: Used to detect small structures or features in images, such as textures, edges, etc.

Guess you like

Origin blog.csdn.net/qq_50993557/article/details/134652284