本文分析了使用flask和yolov5开发html网页时,摄像头实时检测无法显示检测框和置信度的问题,并提出了可能的解决方案。
前端代码使用JavaScript捕获摄像头画面并将其发送到后端进行处理:
<div class="row" style="padding:3%;"> <div class="col-lg-6"> <h5>输入数据:</h5> <div><video autoplay="" id="video"></video></div> </div> <div class="col-lg-6"> <h5>输出结果:</h5> <div class="custom-file-container__image-preview"> @@##@@</img></div> </div> </div> <script> function start() { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { var video = document.querySelector('video'); video.srcObject = stream; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); setInterval(function () { var videoWidth = video.videoWidth; var videoHeight = video.videoHeight; canvas.width = videoWidth; canvas.height = videoHeight; ctx.drawImage(video, 0, 0, videoWidth, videoHeight); var imageData = canvas.toDataURL('image/png',1); // 压缩图片 // 发送数据到后端 $.ajax({ type: 'POST', url: '/image_data', data: { id :$("#uid").val(), image_data: imageData }, success: function (response) { console.log(response); } }); }, 1000 / 30); // 每秒30帧 }) .catch(function (error) { console.error(error); }); } </script>
后端python代码使用opencv处理图像并进行视频流传输:
import cv2 import time import io import base64 from flask import Flask, request, Response from PIL import Image app = Flask(__name__) # ... (假设d.detect函数已定义,用于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"frame 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'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') uid = request.form.get('id') try: image_data = io.BytesIO(base64.b64decode(image_data.split(',')[1])) img = Image.open(image_data) img.save(f'upload/temp{uid}.png') return "ok" except Exception as e: print(f"Error processing image: {e}") return "error" if __name__ == '__main__': app.run(debug=True)
问题可能原因及解决方案:
立即学习“前端免费学习笔记(深入)”;
-
cv2.VideoCapture(path) 路径错误: path 应为正确的摄像头索引 (例如 0 为默认摄像头) 或 RTSP 地址。 前端代码应将正确的摄像头信息传递给后端。
-
前端未调用 /video_feed: 前端代码缺少调用 /video_feed 接口的代码。 应在 start() 函数中添加以下代码:
$("#res").attr("src", "/video_feed?f=temp" + $("#uid").val());
-
错误处理: 后端代码缺少更全面的错误处理。 建议使用 try…except 块捕获并处理可能的异常,例如文件IO错误、图像处理错误等。 同时,前端也应该处理AJAX请求失败的情况。
-
YOLOv5 检测结果显示: 后端代码的 d.detect(frame) 函数应该返回包含检测框和置信度的结果,并将其整合到 im 中,然后才能正确显示。 需要仔细检查 d.detect 函数的实现以及如何将检测结果绘制到图像上。
-
图片格式: 确保 cv2.imencode(‘.png’, im) 编码后的图片格式与前端显示的图片格式一致。
通过修正以上几点,特别是摄像头路径、前端调用后端视频流接口以及完善错误处理机制,就能解决这个问题。 记住检查YOLOv5的检测结果是否正确地绘制在图像上。 如果问题仍然存在,请提供完整的错误日志信息,以便进一步排查。