我正在尝试使用 FastAPI 从相机流式传输视频,类似于我为 Flask 找到的示例。在 Flask 中,该示例工作正常,并且视频流传输没有任何问题。然而,当我尝试在 FastAPI 中复制相同的功能时,遇到了视频流在第一帧后冻结的问题。
我已按照此 Flask 代码中提供的示例进行操作https://www.pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/ https://www.pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/但是当我将其适配为 FastAPI 时,视频仅显示第一帧,然后保持冻结状态。我怀疑 FastAPI 处理流响应的方式可能与 Flask 有所不同。
Flask 中的示例(正常工作):
def generate():
# grab global references to the output frame and lock variables
global outputFrame, lock
# loop over frames from the output stream
while True:
# wait until the lock is acquired
with lock:
# check if the output frame is available, otherwise skip
# the iteration of the loop
if outputFrame is None:
continue
# encode the frame in JPEG format
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
# ensure the frame was successfully encoded
if not flag:
continue
# yield the output frame in the byte format
yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
bytearray(encodedImage) + b'\r\n')
@app.route("/")
def video_feed():
# return the response generated along with the specific media
# type (mime type)
return Response(generate(),
mimetype="multipart/x-mixed-replace; boundary=frame")
这是我的 FastAPI 代码:
def generate():
# grab global references to the output frame and lock variables
global outputFrame, lock
# loop over frames from the output stream
while True:
# wait until the lock is acquired
with lock:
# check if the output frame is available, otherwise skip
# the iteration of the loop
if outputFrame is None:
continue
# encode the frame in JPEG format
(flag, encodedImage) = cv2.imencode(".jpg", outputFrame)
# ensure the frame was successfully encoded
if not flag:
continue
# yield the output frame in the byte format
yield b''+bytearray(encodedImage)
@app.get("/")
def video_feed():
# return the response generated along with the specific media
# type (mime type)
# return StreamingResponse(generate())
return StreamingResponse(generate(), media_type="image/jpeg")
我也回顾了这个问题使用 FastAPI 和 OpenCV 的视频流应用程序 https://stackoverflow.com/questions/63667466/video-streaming-app-using-fastapi-and-opencv,但我找不到解决我的具体问题的解决方案。
有人可以帮助我了解需要在 FastAPI 代码中进行哪些修改才能确保视频流不断更新并且在第一帧后不会冻结吗?我将不胜感激任何指导或建议。谢谢你!