I've been using a little Python program from here. This has been working great until recently I had to wipe and reinstall my RaspberryPi, and now after reinstalling everything including Python and opencv, I seem to have some backward compatibility issue, the following line in the code fails and throwing the error below:
Code
thresh = cv2.dilate(thresh, None, iterations=2)
(_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
This to dilate the thresholded image to fill in any holes, then find contours on thresholded image
Error
File "/home/pi/carspeed/carspeed.py", line 228, in <module>
(_, cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
ValueError: not enough values to unpack (expected 3, got 2)
I tried different things I found online, including changing the lines to this, but to no avail
(_, cnts, _) = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
(The answer I found online is:
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
But since the original code is setting the (_, cnts, _)
variable, I thought I had no choice and used the same.)
CodePudding user response:
The repository you're addressing is using OpenCV 3.x. However You're using OpenCV 4.x. Output of findContours is changed in OpenCV 4
What variable is missing in OpenCV4?
As stated in the documentation, OpenCV3's findContours method used to return the source image itself too, which also is unnecessary in your case. If you want to use source image again, you can just create a new variable and call copy = img.copy
.
Example findContours usage for OpenCV3.x
Example findContours usage for OpenCV4.x
CodePudding user response:
This is solved - The new code for the latest version of opencv should like this:
(cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)