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

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)
``````

• 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):

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()
``````

这就是输入：

并且，这是输出：

希望有帮助！

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