You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. The processed input image (it's mostly the same as your thresholded image, and often not needed)
  2. A list of detected contours (this is the key data you'll use to draw text boxes)
  3. 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:
    _, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    Pro tip: Use the named constants like cv2.RETR_EXTERNAL instead 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:00:04