简体   繁体   English

如何填充接触图像边界的轮廓?

[英]How to fill contours touching the image border?

I have images which I draw contours on from a brightness threshold, the contours are filled after this from the inside.我有从亮度阈值绘制轮廓的图像,然后从内部填充轮廓。 The issue I have ran in to is filling the contours which are hitting the borders.我遇到的问题是填充触及边界的轮廓。

The latest attempt was to add borders around the image and removing them after contour fill, yet it does not work with all the files.最新的尝试是在图像周围添加边框并在轮廓填充后删除它们,但它不适用于所有文件。

Example of the issue displayed [1]: https://imgur.com/a/XyOj0zC显示的问题示例 [1]: https://imgur.com/a/XyOj0zC

I am open to new approaches to the problem, thank you in advance.我愿意接受解决该问题的新方法,在此先感谢您。

    #open the image as a numpy array, in grayscale
    img_input = cv2.imread(input_folder + "\\" + filename, cv2.IMREAD_GRAYSCALE)

    #blur for more accurate contour detection
    img_blurred = cv2.GaussianBlur(img_input, (5,5), cv2.BORDER_DEFAULT)

    #contour selection with otsu's threshold
    image = cv2.threshold(img_blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

    #border creation to fill border hitting contours
    row, col = image.shape[:2]
    bottom = image[row - 2:row, 0:col]
    mean = cv2.mean(bottom)[0]
    bordersize = 10
    image = cv2.copyMakeBorder(
        image,
        top=bordersize,
        bottom=bordersize,
        left=bordersize,
        right=bordersize,
        borderType=cv2.BORDER_CONSTANT,
        value=255
        )

    #border hole creation so the whole image doesnt get filled due to continous contour by the borders
    image[100:101,0:10] = [0]

    #filling the contours
    cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    cv2.fillPoly(image, cnts, [255, 255, 255])

    #removing the created borders
    y, x = image.shape
    final_img = image[10:y-10, 10:x-10]

    #saving the file
    cv2.imwrite(output_folder + "\\" + filename[:-4] + ".png", final_img)
image = cv2.copyMakeBorder(
    image,
    top=bordersize,
    bottom=bordersize,
    left=bordersize,
    right=bordersize,
    borderType=cv2.BORDER_CONSTANT,
    value=0
    )

I think value=0 is better than value=255.我认为 value=0 比 value=255 好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM