利用yolov模型和django实现网页摄像头调用进行实时预测
前端:
<img id="video" width="640" height="480" ref="video"></img>
调用方法:
startCamera() {
var video1 = document.getElementById("video");
video1.src = "http://localhost:8080/api/webcam/"
}
后端:
def webcam_feed(): cap = cv2.VideoCapture(0) while True: ret, frame = cap.read() if not ret: break processed_frame = process_frame(frame) # 将处理后的帧转换为JPEG格式 ret, buffer = cv2.imencode('.jpg', processed_frame) frame_data = buffer.tobytes() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame_data + b'\r\n') cap.release() def webcam_view(request): return StreamingHttpResponse(webcam_feed(), content_type="multipart/x-mixed-replace;boundary=frame") def process_frame(frame): # 在这里对视频帧进行处理 # 这里只是一个示例,你可以根据需要自定义处理逻辑 # 例如这里就返回yolo检测的结果 # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) res = model(frame) # predict on an image res_plotted = res[0].plot() return res_plotted