1

I am trying to get through an OpenCV tutorial and I am using the provided source code. I run into this error:

Traceback (most recent call last):
  File "segmented.py", line 34, in <module>
    result = segment(image)
  File "segmented.py", line 22, in segment
    retval, rect = cv2.floodFill(inv_edges, None, (0, 0), 0)
ValueError: too many values to unpack (expected 2)

Here is the code:

import cv2
import numpy as np

def segment(image):

# convert BGR image to grayscale
image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image_gray = cv2.GaussianBlur(image_gray, (5, 5), 0)

# get contours
edges = cv2.Canny(image_gray, 20, 60)
contours, _ = cv2.findContours(edges, mode=cv2.RETR_EXTERNAL,
                               method=cv2.CHAIN_APPROX_SIMPLE)

# compute object mask
cv2.drawContours(edges, contours, -1, 255, 2)
inv_edges = cv2.bitwise_not(edges)
retval, rect = cv2.floodFill(inv_edges, None, (0, 0), 0)
mask = cv2.bitwise_or(edges, inv_edges)

# masking object
result = np.zeros(image.shape, dtype='uint8')
result[mask > 0, :] = image[mask > 0, :]

return result

if __name__ == '__main__':
image = cv2.imread('adonis.jpg')
result = segment(image)
cv2.imwrite('adonisseg.jpg', result)

how to fix the problem? I use Open CV version 4.2.0

  • On OpenCV(4.1.1), `cv2.floodFill()` returns 4 parameters `retval`, `image`, `mask`, and `rect`. When I tested it, I just changed the line to `retval, img, msk, rect = cv2.floodFill(inv_edges, None, (0, 0), 0)` and it worked fine. – Axe319 Mar 20 '20 at 13:19
  • it's better if you clearly specify your opencv version in your question since functions behavior vary from one version to another – kareem_emad Mar 20 '20 at 13:24
  • I use Open CV version 4.2.0 – rama gilang Mar 20 '20 at 13:32
  • 1
    With version 4.2.0, changing `retval, rect = cv2.floodFill(inv_edges, None, (0, 0), 0)` to `retval, img, msk, rect = cv2.floodFill(inv_edges, None, (0, 0), 0)` should work as well. If you're using an editor like VSCode, it should give you clear hints on what a function or method returns. – Axe319 Mar 20 '20 at 13:40
  • okayy, thanks for help. It's work – rama gilang Mar 20 '20 at 13:51

0 Answers0