如何在Flask和YOLOv5開發的HTML網頁上解決攝像頭無法顯示檢測框的問題?

如何在flask和yolov5開發的html網頁上成功打開攝像頭并顯示檢測框?

在使用flask框架和yolov5開發html網頁時,打開攝像頭并進行實時檢測是常見的需求。然而,有時會遇到無法成功顯示檢測框的問題。下面我們將逐步分析問題并提供解決方案。

首先來看一下前端代碼:

<body>     <div class="row" style="padding:3%;">         <div class="col-lg-6">             <h5>輸入數據:</h5>             <div>                 <video id="video" autoplay></video>             </div>         </div>         <div class="col-lg-6">             <h5>輸出結果:</h5>             <div class="class="custom-file-container__image-preview">                 @@##@@             </div>         </div>     </div>      <input type="button" onclick="start()" value="開始識別">     <input type="button" onclick="stop()" value="暫停識別">      <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幀       })         $("#res").attr("src", "/img_feed?id="+$("#uid").val())       .catch(function (error) {         console.error(error);       });     } </script>

接著是后端代碼:

# 視頻推流 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)                 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()     cv2.VideoCapture(path)  # 視頻流結果 @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')     id = request.form.get('id')     image_data = io.BytesIO(base64.b64decode(image_data.split(',')[1]))     img = Image.open(image_data)     # 對圖片進行處理,例如壓縮、濾波等     output = io.BytesIO()     img.save(output, format='PNG', quality=85)     output.seek(0)     # 將處理后的圖片保存到服務器     img.save(f'upload/temp{id}.png')     with open(f'upload/temp{id}.png', 'wb') as f:         f.write(output.read())     return "ok"

用戶反饋說在打開攝像頭時無法顯示檢測框,并希望能夠正確識別圖像的置信度。

問題的關鍵在于以下幾點:

立即學習前端免費學習筆記(深入)”;

  1. 攝像頭路徑問題
    在 cv2.videocapture(path) 中,path 參數需要正確設置。可以是以下幾種情況:

    • 本地筆記本攝像頭:填寫數字 0
    • ip攝像頭的rtsp地址
    • 本地絕對路徑文件(如 mp4, jpeg 等)

    但是在你的代碼中,gen(f’upload/{f}’) 通過接口傳遞的 f 是什么?這需要明確。

  2. 報錯信息
    沒有提供具體的報錯信息,這使得問題診斷更加困難。如果有報錯信息,建議提供出來,以便進一步分析。
  3. 接口調用問題
    你提到的 /video_feed 接口在前端代碼中并沒有被調用。需要確保前端正確調用這個接口以顯示檢測結果。

為了解決這個問題,我們可以采取以下步驟:

  • 檢查攝像頭路徑:確保 cv2.videocapture(path) 中的 path 參數設置正確。如果是本地攝像頭,嘗試使用 0。如果是文件路徑,確保使用絕對路徑或完整路徑。
  • 前端調用后端接口:在前端的 start() 函數中,應該調用 /video_feed 接口來獲取檢測結果并顯示在 img 標簽中。例如,可以在 setinterval 函數內添加對 /video_feed 的調用,并更新 img 標簽的 src 屬性。
  • 查看報錯信息:如果有任何報錯信息,仔細查看并分析錯誤原因,可能是權限問題、路徑錯誤或其他配置問題。

通過上述步驟,應該能夠解決在打開攝像頭時無法顯示檢測框的問題,并正確識別圖像的置信度。

如何在Flask和YOLOv5開發的HTML網頁上解決攝像頭無法顯示檢測框的問題?

? 版權聲明
THE END
喜歡就支持一下吧
點贊7 分享