Morphological operations—closing operations

  Closing is an operation in image morphology, which combines dilation and erosion operations. The principle of the closed operation is to first perform an erosion operation on the image and then perform a dilation operation. This process is able to eliminate small holes in images, fill small breaks, smooth the boundaries of objects, and connect narrow gaps.
Function:

  • Fill small holes or breaks
  • Smooth and close object boundaries
  • closely connected but discontinuous parts of an object

Applicable scene:

  • Denoising and smoothing in image preprocessing
  • Object connection and boundary extraction in image segmentation
  • Foreground extraction and shape recognition in image analysis

Mathematical formula:
  Closing operation can be expressed in mathematical form as: Closing ( A , B ) = ( A ⊖ B ) ⊕ B \ text{Closing}(A, B) = (A \ominus B) \oplus B Closing(A,B)=(AB)B
  Among them, A A A This is the imported statue, B B B is a constituent element, ⊖ \ominus Display rot operation, ⊕ \oplus represents the expansion operation.
Code example:

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 Close(image):
    # 定义结构元素(这里使用一个5x5的正方形结构元素)
    kernel = np.ones((5, 5), np.uint8)

    # 执行闭运算
    closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)
    return closing

if __name__ == '__main__':
    # 读取图像
    img = cv2.imread('cat-dog.png', flags=0)
    re_img=Close(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)

Guess you like

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