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

基于Roboflow的摄像头目标检测程序运行报错求助

问题分析与解决

错误根源

cv.imshow触发断言失败,核心原因是传入的image为无效数据(宽高为0或None),大概率是Roboflow API返回非图片响应,或是摄像头帧读取/处理环节出错,导致最终无法解码出有效图像。

修复步骤

1. 增加摄像头帧读取有效性校验

在infer()函数中,读取帧后立即检查是否读取成功,失败则跳过当前帧:

ret, frame = video.read()
if not ret:
    print("无法读取摄像头帧")
    return None

2. 校验Roboflow API请求状态

发送请求后先判断响应状态码,非200则打印错误信息,避免无效数据进入解码流程:

resp = requests.post(upload_url, data=img_str, headers={
    "Content-Type": "application/x-www-form-urlencoded"
}, stream=True)
if resp.status_code != 200:
    print(f"API请求失败: {resp.status_code} - {resp.text}")
    return None
resp_raw = resp.raw

3. 增加图像解码有效性检查

解码完成后确认图像是否有效,无效则返回None:

image = cv.imdecode(image_data, cv.IMREAD_COLOR)
if image is None:
    print("无法解码API返回的图像数据")
    return None

4. 主循环中判断图像有效性再显示

调用infer()后,仅当图像有效时执行显示操作:

image = infer()
if image is not None:
    cv.imshow('image', image)

完整修复代码

import cv2 as cv
import base64
import numpy as np
import requests

ROBOFLOW_API_KEY = "*********"
ROBOFLOW_MODEL = "chess-full-ddsxf"  # eg xx-xxxx--#
ROBOFLOW_SIZE = 416

upload_url = "".join([
    "https://detect.roboflow.com/",
    ROBOFLOW_MODEL,
    "?access_token=",
    ROBOFLOW_API_KEY,
    "&format=image",
    "&stroke=5"
])

video = cv.VideoCapture(1)

# 检查摄像头是否成功打开
if video.isOpened():
    print("successfully opening video stream or file")
else:
    print("无法打开摄像头")
    exit()

# 调用Roboflow Infer API并返回结果
def infer():
    # 读取摄像头当前帧
    ret, frame = video.read()
    if not ret:
        print("无法读取摄像头帧")
        return None

    # 按比例缩放图像(提升速度、节省带宽)
    height, width, channels = frame.shape
    scale = ROBOFLOW_SIZE / max(height, width)
    img = cv.resize(frame, (round(scale * width), round(scale * height)))

    # 将图像编码为base64字符串
    retval, buffer = cv.imencode('.jpg', img)
    if not retval:
        print("无法将图像编码为JPG格式")
        return None
    img_str = base64.b64encode(buffer)

    # 请求Roboflow Infer API
    resp = requests.post(upload_url, data=img_str, headers={
        "Content-Type": "application/x-www-form-urlencoded"
    }, stream=True)
    
    if resp.status_code != 200:
        print(f"API请求失败: {resp.status_code} - {resp.text}")
        return None
    
    resp_raw = resp.raw

    # 解析返回的图像数据
    image_data = np.asarray(bytearray(resp_raw.read()), dtype="uint8")
    image = cv.imdecode(image_data, cv.IMREAD_COLOR)
    
    if image is None:
        print("无法解码返回的图像")
        return None

    return image


# 主循环:持续推理直到按下"q"退出
while video.isOpened():
    key = cv.waitKey(5)
    if key == ord("q"):
        break

    image = infer()
    if image is not None:
        cv.imshow('image', image)

# 释放资源
video.release()
cv.destroyAllWindows()

额外排查方向

  • 确认ROBOFLOW_API_KEY和ROBOFLOW_MODEL是否正确,模型是否已发布到Roboflow平台
  • 尝试修改摄像头索引:如果VideoCapture(1)无法读取,换成0(默认摄像头)
  • 检查网络连接,确保能正常访问Roboflow的API地址

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:50:44