Flask+YOLOv5网页摄像头检测:解决检测框显示问题
本文针对使用Flask和YOLOv5构建的HTML网页应用中,摄像头检测框无法显示的问题,提供详细的排查步骤和代码分析。
前端代码 (HTML & JavaScript):
<div class="row" style="padding:3%;"> <div class="col-lg-6"> <h5>输入视频:</h5> <video autoplay="" id="video"></video> </div> <div class="col-lg-6"> <h5>检测结果:</h5> @@##@@ </div> </div> <script> function start() { navigator.mediaDevices.getUserMedia({ video: true }) .then(stream => { const video = document.querySelector('video'); video.srcObject = stream; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); setInterval(() => { const videoWidth = video.videoWidth; const videoHeight = video.videoHeight; canvas.width = videoWidth; canvas.height = videoHeight; ctx.drawImage(video, 0, 0, videoWidth, videoHeight); const imageData = canvas.toDataURL('image/png', 1); // 压缩图片 $.ajax({ type: 'POST', url: '/image_data', data: { id: $("#uid").val(), image_data: imageData }, success: response => console.log(response) }); }, 1000 / 30); // 每秒30帧 }) .catch(error => console.error(error)); $("#res").attr("src", "/img_feed?id=" + $("#uid").val()); } </script>
后端代码 (Python – Flask):
import cv2 import time import io import base64 from flask import Flask, request, Response, render_template app = Flask(__name__) # 假设 'd' 是你的 YOLOv5 检测对象 # d = ... # 你的 YOLOv5 模型加载代码 # 视频流生成器 def gen(path): cap = cv2.VideoCapture(path) while cap.isOpened(): try: start_time = time.time() success, frame = cap.read() if success: im, label, c = d.detect(frame) # YOLOv5 检测 ret, jpeg = cv2.imencode('.png', im) if ret: frame = jpeg.tobytes() elapsed_time = time.time() - start_time print(f"Processing time: {elapsed_time:.3f} seconds") yield (b'--framern' b'Content-Type: image/jpegrnrn' + frame + b'rnrn') else: break else: break except Exception as e: print(e) continue cap.release() # 视频流路由 @app.route('/video_feed') def video_feed(): f = request.args.get("f") print(f'Processing video: upload/{f}') return Response(gen(f'upload/{f}'), mimetype='multipart/x-mixed-replace; boundary=frame') # 图片数据处理路由 @app.route('/image_data', methods=['POST']) def image_data(): image_data = request.form.get('image_data') user_id = request.form.get('id') image_data = io.BytesIO(base64.b64decode(image_data.split(',')[1])) img = Image.open(image_data) # PIL Image img.save(f'upload/temp{user_id}.png') return "ok" if __name__ == '__main__': app.run(debug=True)
问题排查:
立即学习“”;
-
摄像头路径: cv2.VideoCapture(path) 中的 path 必须正确。对于默认摄像头,通常是 0;如果是RTSP流,则使用RTSP地址;如果是文件,则使用完整路径。确保f变量在/video_feed路由中正确传递了视频源路径。
-
错误信息: 仔细检查控制台的错误信息,这能帮助你快速定位问题。
-
文件路径: 使用绝对路径避免相对路径导致的错误。
-
接口调用: 前端代码必须正确调用 /video_feed 接口,例如:$(“#res”).attr(“src”, “/video_feed?f=” + $(“#uid”).val()); 确保$(“#uid”).val()返回正确的文件名或摄像头标识符。
-
YOLOv5 模型: 确保YOLOv5模型正确加载并能够进行检测。 d.detect(frame)这一行是关键,检查模型是否正确预测并返回处理后的图像。
-
图像编码: 确认cv2.imencode(‘.png’, im)正确编码图像。 尝试使用.jpg编码,查看是否有。
-
前后端数据类型: 确保前后端数据类型匹配。前端发送的是base64编码的图像数据,后端需要正确解码。
通过仔细检查以上步骤,并结合控制台错误信息,你应该能够找到并解决检测框显示问题。 记得安装必要的库:opencv-, Pillow, flask, requests。 同时,确保你的YOLOv5模型已经成功运行,并且能够正确地处理图像并返回检测结果。
以上就是如何解决使用Flask和YOLOv5开发HTML网页时摄像头检测框无法显示的问题?的详细内容,更多请关注php中文网其它相关文章!