在 fastAPI 中通过 websockets 流式传输摄像头

Streaming camera via websockets in fastAPI

提问人:stud1234 提问时间:11/16/2023 更新时间:11/16/2023 访问量:23

问:

大家好,我有一个简单的fastapi端点,可以将相机源流式传输到HTML页面。第一次一切正常,但我无法重新加载页面,当我关闭页面时,我得到

websockets.exceptions.connectionclosederror no close frame received or sent

并且当再次进入页面时,流不会加载

这是我的代码

camera = cv2.VideoCapture(0)

@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
    return templates.TemplateResponse("index.html", {"request": request})

async def get_video_frame(camera):
    while True:
        success, frame = camera.read()
        if not success:
            break

        _, buffer = cv2.imencode('.jpg', frame)
        yield buffer.tobytes()

@app.websocket("/ws")
async def get_stream(websocket: WebSocket, camera=Depends(lambda: camera)):
    await websocket.accept()
    try:
        async for frame in get_video_frame(camera):
            await websocket.send_bytes(frame)
    except WebSocketDisconnect:
        await websocket.close(code=1000)
        print("Client disconnected")
    finally:
        camera.release()

<!DOCTYPE html>
<html>
    <head>
        <title>Live Streaming</title>
    </head>
    <body>
        <img id="frame" src="">
        <script>
            let ws = new WebSocket("ws://localhost:8000/ws");
            let image = document.getElementById("frame");

            image.onload = function(){
                URL.revokeObjectURL(this.src);
            };

            ws.onmessage = function(event) {
                image.src = URL.createObjectURL(event.data);
            };

            ws.onclose = function(event) {
                console.log("WebSocket closed:", event);
            };

            window.addEventListener('beforeunload', function() {
                ws.close();
            });
        </script>
    </body>
</html>

删除

code=1000
finally
or 
camera=Depends(lambda: camera)

什么都不做

当我跑步时

ws.close()

流停止,但服务器中未打印出任何内容

python websocket 视频流 fastapi

评论


答: 暂无答案