OpenCV Python中cv2.findContours报“too many values to unpack”错误求助
Hey there! Let's break down this error and get you on track with detecting text boxes in OpenCV.
Why the "too many values to unpack" error happens
The core issue here is OpenCV version differences. In the 3.0-beta version you're using, the cv2.findContours() function returns three values:
- The processed input image (it's mostly the same as your thresholded image, and often not needed)
- A list of detected contours (this is the key data you'll use to draw text boxes)
- Hierarchy information about the contours (useful for nested contours, but optional for basic text detection)
If your code tried to unpack these three values into only two variables (like contours, hierarchy = cv2.findContours(thresh, 1, 2)), Python throws the "too many values to unpack" error — you're asking it to fit three items into two slots.
Fix the error immediately
You have two clean ways to resolve this:
- Option 1 (Recommended): Capture all three values, using an underscore
_to ignore the unused image output:
Pro tip: Use the named constants like_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cv2.RETR_EXTERNALinstead of raw numbers (1/2) — it makes your code way easier to read later! - Option 2: Ignore both the unused image and hierarchy if you don't need them:
_, contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
Quick next step for text bounding boxes
Now that you have the contours, here's a simple snippet to draw bounding boxes around text (adjust parameters based on your image):
import cv2 # Load your image and prepare it (grayscale + thresholding) img = cv2.imread("your_text_image.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Adjust threshold and mode based on your text/background colors _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV) # Get contours correctly _, contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # Draw boxes around valid contours for cnt in contours: x, y, w, h = cv2.boundingRect(cnt) # Filter out tiny noise contours if w > 15 and h > 15: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2) # Show the result cv2.imshow("Text Bounding Boxes", img) cv2.waitKey(0) cv2.destroyAllWindows()
Note: You might need to tweak the threshold value (127) or threshold mode (THRESH_BINARY_INV vs THRESH_BINARY) depending on whether your text is light on dark or dark on light background.
内容的提问来源于stack exchange,提问作者Corentin Mar

