-1

I have an image with a black background and some red outlines of polygons, like this:

enter image description here

I want now to fill those polygons with the same colour, so they look something like this:

enter image description here

I tried using OpenCV, but it doesn't seem to work:

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)

Any help would be appreciated!

OlegRuskiy
  • 173
  • 2
  • 12
  • Which line is giving the error? – TDG Jan 11 '23 at 10:18
  • 1
    Does this answer your question? [too many values to unpack calling cv2.findContours](https://stackoverflow.com/questions/43960257/too-many-values-to-unpack-calling-cv2-findcontours) – Dan Mašek Jan 11 '23 at 10:19
  • 1
    @TDG I bet the `cv2.findContours` -- happens all the time, someone just copies code for OpenCV 3.x, runs it on 4.x, and doesn't bother reading documentation. It's also the only place in the code where a tuple is being unpacked. – Dan Mašek Jan 11 '23 at 10:21
  • Most likely because it's something that has been asked and answered countless times (I pointed you to just one of those cases), and adding more identical questions and answers to the pile is not seen as useful (and contrary to the goals of this site). https://stackoverflow.com/help/duplicates – Dan Mašek Jan 11 '23 at 11:11

1 Answers1

0

As DanMašek suggested in the comments, modifying the unpacking of the tuple is the answer.

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()
OlegRuskiy
  • 173
  • 2
  • 12