[英]Fill contours with OpenCV
I have an image with a black background and some red outlines of polygons, like this:我有一个黑色背景和一些红色多边形轮廓的图像,如下所示:
I want now to fill those polygons with the same colour, so they look something like this:我现在想用相同的颜色填充这些多边形,所以它们看起来像这样:
I tried using OpenCV, but it doesn't seem to work:我尝试使用 OpenCV,但它似乎不起作用:
import cv2
image = cv2.imread("image_to_read.jpg")
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, contours, _ = cv2.findContours(gray_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
cv2.drawContours(image, [contour], 0, (255, 0, 0), -1)
cv2.imshow("Filled Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
I am getting this error:我收到此错误:
ValueError: not enough values to unpack (expected 3, got 2)
ValueError:没有足够的值来解压(预期 3,得到 2)
Any help would be appreciated!任何帮助,将不胜感激!
As DanMašek suggested in the comments, modifying the unpacking of the tuple is the answer.正如 DanMašek 在评论中建议的那样,修改元组的解包就是答案。
import cv2
img = cv2.imread('output.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
contours, hierarchy = cv2.findContours(edged,
cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
for contour in contours:
cv2.drawContours(image, [contour], 0, (255, 0, 0), -1)
cv2.imshow("Filled Image", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.