Python + Corrosion and expansion processing of image OpenCV

Morphological operations actually change the shape of the object , binarization is generally applied to the FIG., Adjacent to the connecting element or separated into independent elements.

Corrosion takes principle is a local minimum in a small area of ​​the original. Because binarizing, only 0 and 255, so there is a small area of ​​the pixel is 0 to 0

The principle is the expansion takes a local maximum in a small area of ​​the original

 Corrosion and expansion of python achieve

import cv2

"""
腐蚀算法:变瘦
    用kernel,扫描图像的每一个像素;用kernel与其覆盖的二值图像做 “与” 操作;如果都为1,结果图像的该像素为1;否则为0.
    结果:使二值图像减小一圈
"""
def erode_demo(image):
    print(image.shape)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    cv2.imshow("binary", binary)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    dst = cv2.erode(binary, kernel)
    cv2.imshow("erode", dst)


"""
膨胀算法:变胖
    用kernel,扫描图像的每一个像素;用kernel与其覆盖的二值图像做 “与” 操作;如果都为0,结果图像的该像素为0;否则为1.
    结果:使二值图像扩大一圈
"""
def dilate_demo(image):
    print(image.shape)
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY)
    cv2.imshow("binary", binary)
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
    dst = cv2.dilate(binary, kernel)
    cv2.imshow("dilate", dst)


if __name__ == "__main__":
    img = cv2.imread("img.jpg")
    cv2.namedWindow("input image", cv2.WINDOW_AUTOSIZE)
    cv2.imshow("input image", img)
    erode_demo(img)
    dilate_demo(img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# img = cv2.imread("image/123.jpg")
# cv2.namedWindow("input image",cv2.WINDOW_AUTOSIZE)
# cv2.imshow("input image",img)
# kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
# dst = cv2.erode(img, kernel)       # 腐蚀
# dst1 = cv2.dilate(img, kernel)     # 膨胀
# cv2.imshow("erode result", dst)
# cv2.imshow("dilate result", dst1)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

运行结果如下

可以不进行灰度处理,直接对彩色图像进行腐蚀和膨胀处理,结果如下

腐蚀函数cv2.erode(src, kernel, dst=None, anchor=None, iterations=None, borderType=None, borderValue=None)         

膨胀函数cv2.dilate(src, kernel, dst=None, anchor=None, iterations=None, borderType=None, borderValue=None)

获取不同形状的结构元素cv2.getStructuringElement(shape, ksize, anchor=None),返回指定形状和尺寸的结构元素

参数shape:表示内核的形状,矩形:MORPH_RECT    十字形:MORPH_CORSS      椭圆形:MORPH_ELLIPSE;

参数ksize:是内核的尺寸(n,n)

参数anchor:锚点的位置

 

Guess you like

Origin www.cnblogs.com/qianxia/p/11105883.html
Recommended