OpenCV Python车辆计数程序报错:int与NoneType无法执行+运算
问题:OpenCV车辆计数程序绘制矩形框报错
我正在开发基于OpenCV Python的车辆计数程序,但尝试为车辆绘制矩形框时出现错误,请求帮助解决:
ret, frame1 = capVideo.read() gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3,3),5) img_sub = carAlgo.apply(blur) dillat = cv2.dilate(img_sub, np.ones((5,5))) kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) dillData = cv2.morphologyEx(dillat, cv2.MORPH_CLOSE, kernal) dillData = cv2.morphologyEx(dillData, cv2.MORPH_CLOSE, kernal) countVehcal, h= ( cv2.findContours(dillData, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)) #If we pass dilladat in (imshow then it will provide grey effect) #to draw a line on the videoView cv2.line(frame1,(25, lineLength), (1400, lineLength), (255,127,0),3) for (i,c) in enumerate (countVehcal): #w=width , z= hight; (x,y,w,h) = cv2.boundingRect(c) vd_count = (w>=min_rectangle_with) and (h>=min_rectangle_hight) if not vd_count: continue cv2.rectangle(frame1, (x,y), (x+w, y+h), (0,0,255), 2) cv2.imshow('Vehical Count', frame1)
出现的错误信息:
Traceback (most recent call last): File "D:\Vehical project\main.py", line 42, in <module> cv2.rectangle(frame1, (x,y), (x+w, y+h), (0,0,255), 2) TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
解决方法
错误原因
- 循环逻辑错误:绘制矩形的代码写在
for循环外部,导致只有最后一个轮廓的变量会被使用;如果所有轮廓都因尺寸不达标被continue跳过,x,y,w,h会处于未定义或None状态,触发运算错误。 - 变量作用域问题:
x,y,w,h是循环内的局部变量,循环结束后若没有符合条件的轮廓,这些变量无有效值。 - 拼写错误:代码中
min_rectangle_with应为min_rectangle_width,可能导致尺寸判断逻辑失效。
修复步骤
- 将绘制矩形的代码移到循环内部:每找到一个符合尺寸要求的车辆轮廓,立即绘制对应矩形框。
- 添加帧读取有效性判断:避免视频读取失败时后续代码报错。
- 修正变量名拼写:确保尺寸判断的变量名正确。
修复后的代码示例:
ret, frame1 = capVideo.read() # 先判断是否成功读取帧 if not ret: print("无法读取视频帧") exit() gray = cv2.cvtColor(frame1, cv2.COLOR_BGR2GRAY) blur = cv2.GaussianBlur(gray, (3,3),5) img_sub = carAlgo.apply(blur) dillat = cv2.dilate(img_sub, np.ones((5,5))) kernal = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)) dillData = cv2.morphologyEx(dillat, cv2.MORPH_CLOSE, kernal) dillData = cv2.morphologyEx(dillData, cv2.MORPH_CLOSE, kernal) # 适配OpenCV常见版本的findContours返回值 countVehcal, h = cv2.findContours(dillData, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # 绘制计数线 cv2.line(frame1,(25, lineLength), (1400, lineLength), (255,127,0),3) for (i,c) in enumerate(countVehcal): (x,y,w,h) = cv2.boundingRect(c) # 修正变量名拼写错误 vd_count = (w >= min_rectangle_width) and (h >= min_rectangle_hight) if not vd_count: continue # 移到循环内,每符合条件就绘制矩形 cv2.rectangle(frame1, (x,y), (x+w, y+h), (0,0,255), 2) cv2.imshow('Vehicle Count', frame1)
额外提示
- 确保
min_rectangle_width和min_rectangle_hight(建议统一改成min_rectangle_height)已被正确赋值,比如设置为min_rectangle_width = 40、min_rectangle_height = 80这类符合场景的数值。 - 若使用OpenCV 3.x版本,
cv2.findContours会返回三个值:image, contours, hierarchy,需调整接收变量避免解包错误。
内容的提问来源于stack exchange,提问作者Anurag Bca
相关产品推荐
相关产品推荐

