用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="custom-file-container__image-preview">
                <img id="res" src="#" >
            </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('.jpg', im)
                if ret:
                    frame = jpeg.tobytes()
                    # 计算处理时间
                    elapsed_time = time.time() - start_time
                    print(f"Frame processing time: {elapsed_time:.3f} seconds")
                    yield (b'--frame\r\n'
                           b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
                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}.jpg')
    with open(f'upload/temp{id}.jpg', 'wb') as f:
        f.write(output.read())
    return "ok"
因为不知道怎么写,所以没有尝试,我希望在打开摄像头的时候可以显示检测框,以便我能正确识别到图像的置信度
回答:
cv2.VideoCapture(path) 这里面的path要么是本地笔记本摄像头,填写数字0,要么是IP摄像头的rtsp地址, 要么是一个本地绝对路径文件<mp4, jpeg等等>。你这里通过接口传递过去的那是啥?gen(f'upload/{f}')。
还有报错信息是什么?如果是本地文件路径的话,建议改成绝对路径,或者完整路径试试看。
还有你的 /video_feed 接口也没有调用啊。
以上是 用flask框架和yolov5开发html网页,打开摄像头检测框失败,该如何解决? 的全部内容, 来源链接: utcz.com/p/939092.html

