我对流式传输 Flask 服务器视频有疑问

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

运行代码A连接Flask服务器时出现如下错误,可以看到应用到Flask服务器的索引画面,但是视频流还在继续。 Flask 服务器上除视频流之外的其他功能 (GPIO) 工作正常。我尝试用 B 代码运行它以防图像对象出现问题,但是图像运行没有任何问题。

图片是服务器执行代码A时输出的图片,视频不是推流的

enter image description here

(即使您使用 A 代码以外的 python 视频流代码,同样的现象也会继续重复。)

cv2.error: OpenCV(4.6.0) /home/pi/opencv/opencv-4.6.0/modules/imgproc/src/color.cpp:182: error: (-215:Assertion failed) !_src.empty( ) 在函数 'cvtColor' 中

0.0.0.0 - - [29/Apr/2023 01:30:16] “GET /video_feed HTTP/1.1” 200 -

运行程序的时候,webcam好像不是cam的问题,好像是将视频转成'jpg'文件发送到Flask服务器有问题,于是写信询问是否在这种情况下,有一个解决方案可以让视频出现在服务器上。

我会在下面附上使用代码。

代码A

# Import necessary libraries
from flask import Flask, render_template, Response

import cv2

# Initialize Flask application
app = Flask(__name__)

# Create a VideoCapture object to capture video from the default camera
capture = cv2.VideoCapture(0)

# Set the frame width and height of the captured video
capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)


# A generator function that continuously captures video frames and converts them into JPEG format
def gen_frames():
    while True:
        # Capture a video frame
        ref, frame = capture.read()  
        # If there's no frame, break out of the loop
        if not ref:
            break
        else:
            # Convert the frame into JPEG format
            ref, buffer = cv2.imencode('.jpg', frame)   
            frame = buffer.tobytes()
            # Yield the frame as a multipart response
            yield (b'--frame\r\n'
                   b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')  


# Define a route for the index page
@app.route('/')
def index():
    """Render the index.html template"""
    return render_template('index.html')


# Define a route for the video feed
@app.route('/video_feed')


def video_feed():
    """Stream the video feed to the client"""
    return Response(gen_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')


# Start the Flask application
if __name__ == "__main__":
    app.run(host="0.0.0.0", port = "8080")

代码B

import cv2

cap = cv2.VideoCapture(0)

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap.set(cv2.CAP_PROP_FPS, 20)

while True:
    ret, frame = cap.read()

    if not ret:
        break

    cv2.imshow('frame', frame)
    if cv2.waitKey(1) == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
python flask web streaming
© www.soinside.com 2019 - 2024. All rights reserved.