Python-OpenCV实现二值图像孔洞填充


代码如下:

import cv2
import numpy as np

def FillHole(mask):
    contours, hierarchy = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    len_contour = len(contours)
    contour_list = []
    for i in range(len_contour):
        drawing = np.zeros_like(mask, np.uint8)  # create a black image
        img_contour = cv2.drawContours(drawing, contours, i, (255, 255, 255), -1)
        contour_list.append(img_contour)

    out = sum(contour_list)
    return out

if __name__ == '__main__':
    mask_in = cv2.imread('C:\\Users\\admin\\Desktop\\mask_in.tif', 0)
    mask_out = FillHole(mask_in)
    cv2.imwrite('C:\\Users\\admin\\Desktop\\mask_out.tif', mask_out)

效果如下:

      

     孔洞填充前                       孔洞填充后


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM