如何将CV2 YOLO8s实时视频流接入Django网页?
将YOLO8s实时检测视频流传入Django网页的实现方案
核心思路
通过Django视图生成MJPEG视频流,把YOLO检测后的帧编码为JPEG格式持续输出给前端;前端用<img>标签直接指向该视图URL,就能实现实时播放。
步骤1:改造YOLO检测类(替换cv2.imshow为帧字节输出)
修改你的Main_field类,调整视频处理逻辑为生成器模式,输出编码后的帧字节,适配Django流响应:
from ultralytics import YOLO import cv2 from database.db import * from pprint import pprint as pt class Main_field: def __init__(self, model_path, size, source, conf_): self.model = self.load_model(model_path) self.size = size self.source = source self.conf_ = conf_ self.cap = None def load_model(self, model_path): model = YOLO(model_path) model.fuse() return model def generate_frames(self): self.cap = cv2.VideoCapture(self.source) while True: ret, frame = self.cap.read() if not ret: break # 执行YOLO检测 results = self.model.predict(frame, conf=self.conf_, imgsz=self.size) mask_ids = results[0].boxes.cpu().numpy().cls.astype(int).tolist() pt(mask_ids) # 保留原有数据库操作逻辑 db_output = [check_(local_list, str(itr)) for itr in mask_ids if itr] # 绘制检测结果到帧上 frame_with_detections = results[0].plot() # 将帧编码为JPEG字节 ret_jpeg, buffer = cv2.imencode('.jpg', frame_with_detections) frame_bytes = buffer.tobytes() # 按MJPEG流格式返回数据 yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_bytes + b'\r\n') def release_resources(self): if self.cap: self.cap.release() cv2.destroyAllWindows() def init_model(path: str) -> YOLO: return YOLO(path)
步骤2:编写Django视图函数
在项目的views.py中创建视图,调用改造后的检测类返回流响应:
from django.http import StreamingHttpResponse from .your_yolo_module import Main_field, init_model # 全局初始化YOLO模型,避免重复加载 yolo_model = init_model("path/to/your/trained/yolov8s.pt") detector = Main_field( model_path="path/to/your/trained/yolov8s.pt", size=640, # 对应你的模型输入尺寸 source=0, # 0为本地摄像头,也可传入视频文件路径 conf_=0.5 # 检测置信度阈值 ) def video_stream(request): # 返回MJPEG流响应 response = StreamingHttpResponse( detector.generate_frames(), content_type='multipart/x-mixed-replace; boundary=frame' ) # 请求结束时自动释放资源 def cleanup(): detector.release_resources() request.add_finisher(cleanup) return response
步骤3:配置URL路由
在项目的urls.py中添加路由映射:
from django.urls import path from .views import video_stream urlpatterns = [ # 其他已有路由... path('video-stream/', video_stream, name='video_stream'), ]
步骤4:前端模板展示视频流
创建HTML模板(如stream.html),通过<img>标签加载流:
<!DOCTYPE html> <html> <head> <title>YOLO8s实时检测</title> </head> <body> <h1>YOLO8s实时检测视频流</h1> <img src="{% url 'video_stream' %}" width="800" height="600"> </body> </html>
关键注意事项
- 模型加载优化:全局初始化YOLO模型,避免每次请求重复加载,减少资源消耗。
- 线程安全:若多用户同时访问,可给每个请求创建独立的
Main_field实例,避免资源冲突。 - 性能调优:开启GPU加速(确保YOLO使用CUDA)、适当降低模型输入尺寸,避免流卡顿。
- 资源释放:通过Django请求结束钩子释放摄像头,防止资源泄漏。
内容的提问来源于stack exchange,提问作者George Galkin Faso
相关产品推荐
相关产品推荐

