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

树莓派运行OpenCV2代码时cvtColor函数断言失败求助

问题:OpenCV运行报错!_src.empty()的排查与解决

我从YouTube教程复制了Python OpenCV代码,代码如下:

import cv2
import utlis

###################################
webcam = True
path = '/home/ftsp23/vert/phone'
cap = cv2.VideoCapture(0)
cap.set(10,160)
cap.set(3,1920)
cap.set(4,1080)
scale = 3
wP = 210 *scale
hP= 297 *scale
###################################

while True:
    if webcam:success,img = cap.read()
    else: img = cv2.imread(path)

    imgContours , conts = utlis.getContours(img,minArea=50000,filter=4)
    if len(conts) != 0:
        biggest = conts[0][2]
        #print(biggest)
        imgWarp = utlis.warpImg(img, biggest, wP,hP)
        imgContours2, conts2 = utlis.getContours(imgWarp,
                                                 minArea=2000, filter=4,
                                                 cThr=[50,50],draw = False)
        if len(conts) != 0:
            for obj in conts2:
                cv2.polylines(imgContours2,[obj[2]],True,(0,255,0),2)
                nPoints = utlis.reorder(obj[2])
                nW = round((utlis.findDis(nPoints[0][0]//scale,nPoints[1][0]//scale)/10),1)
                nH = round((utlis.findDis(nPoints[0][0]//scale,nPoints[2][0]//scale)/10),1)
                cv2.arrowedLine(imgContours2, (nPoints[0][0][0], nPoints[0][0][1]), (nPoints[1][0][0], nPoints[1][0][1]),
                                (255, 0, 255), 3, 8, 0, 0.05)
                cv2.arrowedLine(imgContours2, (nPoints[0][0][0], nPoints[0][0][1]), (nPoints[2][0][0], nPoints[2][0][1]),
                                (255, 0, 255), 3, 8, 0, 0.05)
                x, y, w, h = obj[3]
                cv2.putText(imgContours2, '{}cm'.format(nW), (x + 30, y - 10), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,
                            (255, 0, 255), 2)
                cv2.putText(imgContours2, '{}cm'.format(nH), (x - 70, y + h // 2), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1.5,
                            (255, 0, 255), 2)
        cv2.imshow('A4', imgContours2)

    img = cv2.resize(img,(0,0),None,0.5,0.5)
    cv2.imshow('Original',img)
    cv2.waitKey(1)

运行后报错:

Traceback (most recent call last):
  File "/home/ftsp23/vert/aaa.py", line 24, in <module>
    imgContours , conts = utlis.getContours(img,minArea=50000,filter=4)
  File "/home/ftsp23/vert/utlis.py", line 6, in getContours
    imgGray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.error: OpenCV(4.6.0) /tmp/pip-wheel-u79916uk/opencv-python_ea2489746b3a43bfb3f2b5331b7ab47a/opencv/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cvtColor'

运行环境:树莓派,Python 3.9.2,OpenCV 4.6.0.66(因高版本无法运行指定该版本),多次修复无效,求排查思路或解决方案。


排查思路与解决方案

1. 核心问题定位

报错!_src.empty()说明传入cv2.cvtColor的img是空对象——要么摄像头没读取到帧,要么本地图片加载失败。

2. 分场景排查与修复

场景1:摄像头模式(webcam=True)

  • 检查设备索引:树莓派摄像头的设备索引不一定是0,执行ls /dev/video*查看可用设备,把cv2.VideoCapture(0)里的0换成实际索引(比如1)。
  • 验证摄像头可用性:执行raspistill -o test.jpg测试摄像头是否能正常拍照,若失败,通过raspi-config启用Camera选项,检查摄像头排线是否插紧。
  • 增加读取成功判断:在代码里加入校验,避免空帧流入后续逻辑:
    if webcam:
        success, img = cap.read()
        if not success:
            print("摄像头读取失败")
            continue
    else:
        img = cv2.imread(path)
    
  • 降低分辨率:树莓派摄像头可能不支持1920x1080,将cap.set(3,1920)和cap.set(4,1080)改为cap.set(3,640)和cap.set(4,480)测试。

场景2:本地图片模式(webcam=False)

  • 修正图片路径:确认path指向具体图片文件(而非文件夹),比如改为/home/ftsp23/vert/phone.jpg,执行ls -l /home/ftsp23/vert/phone验证路径有效性。
  • 增加加载校验:
    else:
        img = cv2.imread(path)
        if img is None:
            print(f"图片加载失败,路径:{path}")
            break
    

3. 代码健壮性优化

在调用utlis.getContours前,先判断img是否有效:

if img is not None:
    imgContours , conts = utlis.getContours(img,minArea=50000,filter=4)
    # 后续处理逻辑...
else:
    print("无有效图像可处理")
    # 显示空帧避免崩溃
    import numpy as np
    cv2.imshow('Original', np.zeros((480,640,3), dtype=np.uint8))

4. 依赖与脚本检查

  • 确认utlis.py和主脚本在同一目录,且getContours函数未提前修改img导致其为空。
  • 重新安装OpenCV依赖:pip install --force-reinstall opencv-python==4.6.0.66,确保依赖完整。

内容的提问来源于stack exchange,提问作者yong jie

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 00:26:08