Morphological operations—corrosion

  Image morphology operation is a technique used to process images. Erosion is one of them, which can blur or shrink the edges of objects in the image. The corrosion operation uses a structural element (Kernel) to slide on the image and update the pixel value in the area covered by the structural element to the minimum value of the pixel value in the neighborhood. This can reduce the size of object edges in an image, remove small noise or connect objects, etc. The size and shape of structural elements will affect the corrosion effect. Larger structural elements will lead to more obvious corrosion effects, and structural elements of different shapes will also have different effects on corrosion.
  Mathematically, the corrosion operation can be expressed mathematically as:
Output ( x , y ) = min ⁡ ( s , t ) ∈ kernel Input ( x + s , y + t ) \text{Output}(x, y) = \min_{(s, t) \in \text{kernel}} \text{Input}(x + s, y + t) Output(x,y)=(s,t)kernelminInput(x+s,and+t)
  其中 Input ( x , y ) \text{Input}(x, y) Input(x,y) This is the location of the original image ( x , y ) (x, y) < /span>(x,y)'s image element 值, Output ( x , y ) \text{Output}( x, y) Output(x,y) is the corroded image at position ( x , y ) (x, y ) (x,y)'s image. ( s , t ) (s, t) (s,t) are coordinates in the structure element (Kernel).
Applicable scenarios:

  • Remove small noise or tiny objects;
  • Reduce the size of an object or disconnect parts;
  • segment objects in the image.
      Here is a sample code for corrosion operation using Python and 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 Erosion(image):
    # 定义结构元素(这里使用一个 5x5 的正方形结构元素)
    kernel = np.ones((5, 5), np.uint8)
    # 进行腐蚀操作
    erosion = cv2.erode(image, kernel, iterations=1)
    return erosion

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