【问题标题】:Fill perforated shape in image using python libs?使用python库填充图像中的穿孔形状?
【发布时间】:2018-11-26 03:33:14
【问题描述】:

我有带有“穿孔”的 BW 图像。穿孔级别可以不同

是否有任何“标准”方法可以用黑色完全填充形状以使它们更相似?

首选 Pillow 和 opencv,但 imagemagick 也可以。

【问题讨论】:

    标签: python opencv image-processing imagemagick pillow


    【解决方案1】:

    您可以使用image morphology(i.e: closing) 来实现此目的。

    import cv2
    import numpy as np
    
    if __name__ == '__main__':
        # read image
        image = cv2.imread('image.png',cv2.IMREAD_UNCHANGED)
    
        # convert image to gray
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
        # ensure only black and white pixels exist
        ret,binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
    
        # morphology works with white forground
        binary = cv2.bitwise_not(binary)
    
        # get kernel for morphology
        kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
        # number of iterations depends on the type of image you're providing
        binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel, iterations=3)
    
        # get black foreground
        binary = cv2.bitwise_not(binary)
    
        cv2.imshow('image', binary)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    

    【讨论】:

    • 为什么倒置?你不能用打开而不是关闭吗?
    • @filippo 我可以,但我不想混淆 OP,因为他似乎是 OpenCV 的初学者。这是一个关闭操作,所以我使用了cv2.MORPH_CLOSE
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2014-11-10
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 1970-01-01
    相关资源
    最近更新 更多