Opencv 使用FastAPI将视频流到web浏览器

Opencv 使用FastAPI将视频流到web浏览器,opencv,flask,fastapi,Opencv,Flask,Fastapi,我在FLASK中找到了一个通过web浏览器中的rtsp协议传输摄像机的示例 我试图在fastapi中使用相同的示例,但我不明白。图像被冻结 烧瓶中的示例(正常工作): 我试图在FastAPI中这样做,但只有第一帧出现,被冻结 def generate(): # grab global references to the output frame and lock variables global outputFrame, lock # loop over frames f

我在FLASK中找到了一个通过web浏览器中的rtsp协议传输摄像机的示例

我试图在fastapi中使用相同的示例,但我不明白。图像被冻结

烧瓶中的示例(正常工作):

我试图在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中使用相同的函数吗

如果有人对完整的代码感兴趣,我在这里举了一个例子:

在这里发布后,我想出了如何修复它

视频喂料功能中,在媒体类型参数中,仅以与烧瓶中相同的方式放置:

@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="multipart/x-mixed-replace;boundary=frame")
并在函数中生成:

yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
               bytearray(encodedImage) + b'\r\n')

在这里发布后,我想出了如何修复它

视频喂料功能中,在媒体类型参数中,仅以与烧瓶中相同的方式放置:

@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="multipart/x-mixed-replace;boundary=frame")
并在函数中生成:

yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
               bytearray(encodedImage) + b'\r\n')