如何在图像边缘填充圆形轮廓?

enter image description here

In the image above, I want to eventually be able to fill in the contours of the colored circles. Unfortunately, the yellow circle on the bottom is right at the edge of the image, so cv2.findContours() doesn't work:

_, green_contours, _ = cv2.findContours(green_seg, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

有谁知道即使在图像边缘,我也能以某种方式填充黄色圆圈轮廓?由于它在图像的边缘,因此图像底部边缘的像素值无法完成圆,如果有意义,则不会将其值设为255。

我在网上看了看,有人说可以在图像周围绘制一个大盒子然后绘制轮廓,但是如果我这样做,则opencv仅在整个图像周围绘制大轮廓,而不是圆形。

任何其他想法将不胜感激!

编辑:我上面显示的图像只是我正在考虑的一种情况。我正在尝试思考如何使它足够通用,以便对于边界边缘处的任何轮廓,仍然可以使用cv2.drawContour()填充轮廓。

评论
  • USA
    USA 回复

    If you have (more or less) convex polygons, you actually CAN use cv2.findContours. Having the contours, try to find the center of mass, e.g. using cv2.moments, and then use this as the seed point in cv2.floodFill.

    请参见以下代码段。我想,您可以通过颜色识别多边形。另外,我没有使用质量中心的高级方法,而是使用了每个轮廓的边界矩形的中心点。也许,这对于您的用例也足够了!

    import cv2
    import numpy as np
    
    # Set up test image
    colors = [(0, 255, 0), (0, 0, 255)]
    input = np.zeros((400, 400, 3), np.uint8)
    cv2.circle(input, (100, 100), 50, colors[0], 10)
    cv2.circle(input, (150, 350), 75, colors[1], 10)
    output = input.copy()
    
    # Iterate all colors...
    for i, c in enumerate(colors):
    
        # Mask color
        img = np.all(output == c, axis=2).astype(np.uint8) * 255
    
        # Find contours with respect to OpenCV version
        cnts = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
        cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    
        # Get bounding rectangles; derive seed points for flood filling; flood fill
        rects = [cv2.boundingRect(c) for c in cnts]
        seeds = [(np.int32(r[0] + r[2] / 2), np.int32(r[1] + r[3] / 2)) for r in rects]
        [cv2.floodFill(output, mask=None, seedPoint=s, newVal=c) for s in seeds]
    
    cv2.imshow('input', input)
    cv2.imshow('output', output)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    

    这就是输入:

    Input

    并且,这是输出:

    Output

    希望有帮助!

    ----------------------------------------
    System information
    ----------------------------------------
    Platform:    Windows-10-10.0.16299-SP0
    Python:      3.8.1
    NumPy:       1.18.1
    OpenCV:      4.1.2
    ----------------------------------------