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

Django集成YOLOv5实现摄像头检测报fromarray缺少obj参数错误

报错根因

直接触发TypeError: fromarray() missing 1 required positional argument: 'obj'的原因是调用PIL库的Image.fromarray()方法时未传入必填参数:该方法要求传入一个numpy数组格式的图像对象作为入参,你的代码中写的data=im.fromarray()是空参调用,完全不符合方法调用规范。
除了这个显性报错,代码中还有3处逻辑错误会导致页面无法正常显示检测视频流:

  • 缺少render方法的导入,index视图运行时会直接抛NameError
  • 每帧检测结果都写入本地磁盘文件demo.jpg再读取返回,高频IO极易造成流阻塞、中断
  • 最终返回给前端的是未做检测标注的原始摄像头帧,就算不报错也看不到YOLO的检测结果
修复方案

按照以下顺序修改代码即可跑通功能:

  1. 补全缺失的导入项,在views.py头部添加from django.shortcuts import render
  2. 删除冗余的PIL图像转换、本地文件读写逻辑,YOLOv5的results.render()会直接返回绘制好检测框、类别标签的numpy数组格式帧,不需要转PIL存本地
  3. 直接在内存中把标注完成的帧编码为JPEG格式字节流,通过StreamingHttpResponse返回给前端,避免磁盘IO开销
  4. 把返回内容替换为YOLO渲染后的标注帧,而非原始采集帧
修复后完整views.py代码
from django.shortcuts import render
from django.http import StreamingHttpResponse
import cv2
import torch

# 模型路径配置
path_hubconfig = r"D:\University\FYP\FYP-CovidDefence\stream\ObjectDetection\yolov5"
path_weightfile = r"D:\University\FYP\FYP-CovidDefence\stream\ObjectDetection\yolov5\best.pt"
# 全局加载一次模型,避免每次请求重复加载增加开销
model = torch.hub.load(path_hubconfig, 'custom', path=path_weightfile, source='local')

def index(request):
    return render(request,'index.html')

def stream():
    cap = cv2.VideoCapture(0)
    # 配置摄像头分辨率,可根据需求调整,平衡清晰度和延迟
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error: failed to capture image")
            cap.release()
            break
        # 运行YOLO检测
        results = model(frame, augment=True)
        # 获取绘制完成检测标注的帧
        annotated_frame = results.render()[0]
        # 内存中直接编码为JPEG,无需写本地文件
        _, encode_buffer = cv2.imencode('.jpg', annotated_frame)
        frame_bytes = encode_buffer.tobytes()
        # 按MJPEG流格式返回帧数据
        yield (b'--frame\r\n'
               b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n')

def video_feed(request):
    return StreamingHttpResponse(stream(), content_type='multipart/x-mixed-replace; boundary=frame')
额外校验点

如果修改后仍看不到画面,检查以下配置:

  • 确认urls.py中已经正确配置index和video_feed两个路由
  • 确认index.html中的视频流img标签地址正确,示例写法:<img src="/video_feed" width="640" height="480">
  • 本地运行时确认摄像头没有被其他程序占用,Python进程有摄像头访问权限
  • 如果显存不足,可以在加载模型后加model.to('cpu')强制用CPU推理,避免CUDA内存错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 18:42:25