使用 OpenCV 填充轮廓

问题描述 投票:0回答:1

我有一个带有黑色背景和一些红色多边形轮廓的图像,如下所示:

我现在想用相同的颜色填充这些多边形,所以它们看起来像这样:

我尝试使用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()

我收到此错误:

ValueError:没有足够的值来解包(预期为 3 个,实际为 2)

如有任何帮助,我们将不胜感激!

python opencv shapes fill
1个回答
0
投票

正如 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()
© www.soinside.com 2019 - 2024. All rights reserved.