OpenCV验证码识别报错:boundingRect参数错误如何解决?
验证码识别程序错误修复
错误原因分析
- OpenCV 4.x版本中
cv2.findContours()返回两个值:轮廓列表和层次结构,你直接把返回值赋值给contours,导致循环时遍历到了层次结构(非轮廓数组),触发boundingRect的参数错误。 - 代码存在拼写错误:
cv2.countourArea应为cv2.contourArea(少写了字母u)。 - 缺失
glob模块的导入语句,运行时会报未定义错误。
修正后的完整代码
import os import cv2 import numpy as np import glob # 补充缺失的导入 archives = glob.glob('captcha_tratado/*') for archive in archives: image = cv2.imread(archive) # cv2.imread读取的是BGR格式,转灰度用COLOR_BGR2GRAY更准确 image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) _, image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY_INV) # OpenCV4.x返回(contours, hierarchy),仅取轮廓列表部分 contours, hierarchy = cv2.findContours( image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) letter_regions = [] for contour in contours: (x, y, width, height) = cv2.boundingRect(contour) # 修正拼写错误:countourArea -> contourArea area = cv2.contourArea(contour) if area > 115: letter_regions.append((x, y, width, height)) if len(letter_regions) <= 2: continue # 有效区域不足时直接跳过后续处理,比pass更合理 # 生成带标记的图像并分割字母 image_final = cv2.merge([image] * 3) i = 0 for rectangle in letter_regions: x, y, width, height = rectangle # 防止切片越界,添加边界判断 y_start = max(0, y-2) y_end = min(image.shape[0], y+height+2) x_start = max(0, x-2) x_end = min(image.shape[1], x+width+2) image_letter = image[y_start:y_end, x_start:x_end] i += 1 fileName = os.path.basename(archive).replace(".png", f"letter{i}.png") cv2.imwrite(f'letras/{fileName}', image_letter) cv2.rectangle(image_final, (x_start, y_start), (x_end, y_end), (0, 255, 0), 1) fileName = os.path.basename(archive) cv2.imwrite(f'identificado/{fileName}', image_final)
额外优化说明
- 替换
COLOR_RGB2GRAY为COLOR_BGR2GRAY,匹配cv2.imread的默认色彩空间。 - 添加切片边界判断,避免因字母靠近图像边缘导致的数组越界问题。
- 用
continue替代pass,逻辑更清晰,减少无意义的代码执行。
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

