Rumah  >  Soal Jawab  >  teks badan

FastAPI dan OpenCV: Memperkasakan aplikasi penstriman video yang canggih

Saya cuba memaparkan halaman HTML yang memaparkan strim video daripada kamera web. Walau bagaimanapun, saya menghadapi ralat berikut:

500 Server Error TypeError: TemplateResponse() missing 1 required positional argument: 'context'

Apl FastAPI Saya:

from fastapi import FastAPI
import uvicorn
from fastapi import Depends, FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import cv2

app = FastAPI(debug=True)
templates = Jinja2Templates(directory="templates")

@app.get("/")
async def index():
    return templates.TemplateResponse("index.html")


async def gen_frames(camera_id):
    cap=  cv2.VideoCapture(0)

    while True:
        # for cap in caps:
        # # Capture frame-by-frame
        success, frame = cap.read()  # read the camera frame
        if not success:
            break
        else:
            ret, buffer = cv2.imencode('.jpg', frame)
            frame = buffer.tobytes()
            yield (b'--framern'b'Content-Type: image/jpegrnrn' + frame + b'rn')  
    
   if __name__ == '__main__':
    uvicorn.run(app,  host="127.0.0.1",port=8000)

Halaman HTML saya (index.html):

<!doctype html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
          integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>Multiple Live Streaming</title>
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-lg-7">
            <h3 class="mt-5">Multiple Live Streaming</h3>
            <img src="{{ url_for('video_feed', id='0') }}" width="100%">
        </div>
    </div>
</div>
</body>
</html>

Traceback:

P粉986937457P粉986937457329 hari yang lalu724

membalas semua(1)saya akan balas

  • P粉884548619

    P粉8845486192023-10-27 10:49:35

    Anda perlu lulus permintaan apabila menggunakan templat.

    from fastapi import Request
    
    @app.get("/")
    async def index(request: Request):
        return templates.TemplateResponse("index.html", {"request": request})

    Jadi anda juga boleh menggunakan StreamingResponse< 将视频作为另一条路径/strong>

    from fastapi.responses import StreamingResponse
    
    
    @app.get("/serve/{camera_id}", include_in_schema=False)
    async def serve_video(camera_id: int):
        return StreamingResponse(gen_frames(camera_id))

    Kemudian gunakan Ajax atau Axios dan lain-lain untuk mendapatkan respons.

    balas
    0
  • Batalbalas