SoFunction
Updated on 2024-11-16

with respect to Python opencv operating ValueError: too many values to unpack

The () function was recently used in the OpenCV-Python interface to find the contours of detected objects.

According to the online tutorial, the Python OpenCV contour extraction function returns two values, the first one is the point set of the contour, and the second one is the index of the contour in each layer. But when I actually called it, my program reported the following error: too many values to unpack (expected 2)

In fact, it accepts return values that don't match. If you just use a variable a to accept the return value and call len(a), you'll find that the length is 3, which means that the function actually returns three values

The first one, and the dodgiest one, returns the image you're working with

The second one is exactly what we're looking for, the set of points of the contour.

Third, the indexing of the contours of the layers

Use it as follows:

import cv2 
 
img = ('D:\\test\\') 
gray = (img,cv2.COLOR_BGR2GRAY) 
ret, binary = (gray,127,255,cv2.THRESH_BINARY) 
 
contours, hierarchy = (binary,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 
(img,contours,-1,(0,0,255),3) 
 
("img", img) 
(0) 

An error occurs during runtime:ValueError: too many values to unpack

Reason: Due to version 3.2.0.7, the number of return values has changed to 3. Therefore it should be

aa, ctrs, hier = (im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

If the first parameter is not used, it can be written as

_, ctrs, hier = (im_th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

Expansion:

ValueError: too many values to unpack error, mostly caused by inconsistent number of input or output parameters.

Reference:

https:///article/

In fact, it accepts return values that don't match. If you just use a variable a to accept the return value and call len(a), you'll find that the length is 3, which means that the function actually returns three values

The first one, and the dodgiest one, returns the image you're working with

The second one is exactly what we're looking for, the set of points of the contour.

Third, the indexing of the contours of the layers

This is the whole content of this article.