在 Flask 应用程序中,无法播放使用 cv2.VideoWriter

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

代码运行没有错误,我的网页正确显示实时流,按录制和停止录制按钮显示没有错误,它甚至以正确的名称保存文件。但当我必须启动它时,VLC 没有显示任何内容,并且赛璐珞播放器抱怨无法识别的文件格式。

在属性中,我可以读取文件格式是mp4,它有字节,例如44,或70(不是0字节)

我尝试了不同的 Fourcc 代码和 avi。

另外,如果重要的话,我正在使用 Linux Mint 21。

from datetime import datetime
import os
import time
from flask import Flask, render_template, Response


app = Flask(__name__)

recordings_dir = os.path.join('recordings')
if not os.path.exists(recordings_dir):
    os.makedirs(recordings_dir)

# Store video access in variable
vid = cv2.VideoCapture(0)
frame_width = vid.get(cv2.CAP_PROP_FRAME_WIDTH)
frame_height = vid.get(cv2.CAP_PROP_FRAME_HEIGHT)
isRecording = False
out = None


def gen():
    # Run forever
    while True:
        time.sleep(0.1)

        # State holds true or false depending on the success of updating frame variable to be a frame from the video stream
        state, frame = vid.read()

        # Break out of while loop when its unsuccesful
        if not state:
            break

        else:

            if isRecording:
                out.write(frame)
            # Flag holds true or false
            # Imencode converts image formats (jpeg here) into streaming data and stores them in memory cache, effectively transforming them into bytes
            flag, buffer = cv2.imencode('.jpg', frame)
            
            # Generator function yields interruptable stream of JPEG bytes
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + bytearray(buffer) + b'\r\n')
    


@app.route('/video_feed')
def video_feed():

    # Generator function response
    return Response(gen(),
                    mimetype='multipart/x-mixed-replace; boundary=frame')    

@app.route("/")
def index():
    return render_template("videos.html")

@app.route('/start_rec', methods=["POST"])
def start_recording():
    global isRecording, out
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")

    if not isRecording:
        fourcc = cv2.VideoWriter_fourcc(*'MJPG')
        out = cv2.VideoWriter(os.path.join(recordings_dir, f'{timestamp}_recording.mp4'), fourcc, 20.0, frame_width, frame_height)
    return '', 203   


        

@app.route('/stop_rec', methods=["POST"])
def stop_recording():

    global isRecording, out
    
    if isRecording:
        out.release()
        isRecording = False
    return '', 203    
python opencv flask
1个回答
0
投票

已修复,愚蠢的错误,我忘记将

isRecording = True
添加到录音功能中的循环中。

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