如何使用 Flask 更改 python 文件的网络摄像头?

问题描述 投票:0回答:1

我正在开发一个人脸识别项目,该项目将 gen_frame() 发送到 video_feed 以在我的 html 文件中呈现。但是,我找不到将本地存储发送到 Flask 的正确方法。有人对我如何使用本地存储更改网络摄像头有一些建议吗?

这是包含 gen_frame 方法的 python attend_taker.py:

`def gen_frame(): cap = cv2.VideoCapture(0) # 这是我想使用 localstorage 更改的内容 人脸识别器 = 人脸识别器()

while True:
    success, frame = cap.read()
    if not success:
        break

    face_recognizer.process(frame)

    ret, buffer = cv2.imencode('.jpg', frame)
    frame = buffer.tobytes()
    yield (b'--frame\r\n'
           b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')`

这是 JavaScript 代码:

`window.addEventListener("DOMContentLoaded", function () { var webcamSelect = document.getElementById("webcamSelect");

webcamSelect.addEventListener("change", function () {
    var selectedWebcamIndex = webcamSelect.selectedIndex;
    localStorage.setItem("selectedWebcamIndex", selectedWebcamIndex);
});

navigator.mediaDevices
    .enumerateDevices()
    .then((devices) => {
        var videoDevices = devices.filter(
            (device) => device.kind === "videoinput",
        );
        videoDevices.forEach((device, index) => {
            var option = document.createElement("option");
            option.value = index;
            option.text = device.label || `Webcam ${index + 1}`;
            webcamSelect.appendChild(option);
        });

        var selectedWebcamIndex = localStorage.getItem(
            "selectedWebcamIndex",
        );
        if (selectedWebcamIndex) {
            webcamSelect.selectedIndex = selectedWebcamIndex;
        }
    })
    .catch((error) => {
        console.error("Error enumerating devices:", error);
    });

}); ` 应用程序.py:

@app.route('/video_feed') def video_feed(): return Response(gen_frame(), mimetype='multipart/x-mixed-replace; boundary=frame')

我尝试使用 jquery 中的 ajax,但不起作用。

javascript flask local-storage
1个回答
0
投票

我对这个问题有点困惑,但这里是:

据我了解,您希望将输出保存为文件服务器端,但是您不需要通过前端 javascript 来执行此操作

# pip install opencv-python

import cv2

# basic opencv2 things here feel free to ignore

cv2.startWindowThread()
cap = cv2.VideoCapture(0) # specify camera

out = cv2.VideoWriter('output.avi', cv2.VideoWriter_fourcc(*'MJPG'), 15., (640, 480)) 
# 'output.avi': outputted file, 'MJPG': motion jpeg, '(640, 480)': output width and height, adjust to needs

while True:
    success, frame = cap.read()
    # ...
    
    out.write(frame.astype('uint8')) # write the output video


# run this afterwards to save the video
out.release() # release video output

多一点 Flask 服务器会有很大帮助,在尝试在 Markdown 中格式化代码块时要小心

  • 多行代码块的三个反引号打开和关闭
  • 单行的单反引号打开和关闭
    code blocks

link 链接到使用 python open-cv 进行面部识别的完整基础示例。

我注意到标题说
how do I change the webcam of a python file using flask
,如果这就是问题本身,你可以使用:

cap = cv2.VideoCapture(0)
指定相机。该数字表示一个单独的相机。 (即:
1
,可以是 USB 安装的摄像头,而
0
可以是嵌入式摄像头,等等)

如果我完全没有达到要求或者您还有其他问题,请告诉我!

© www.soinside.com 2019 - 2024. All rights reserved.