Repository navigation
Expand file tree
/
Copy pathfastapi_app.py
More file actions
82 lines (66 loc) · 2.38 KB
/
Copy pathfastapi_app.py
File metadata and controls
82 lines (66 loc) · 2.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import time
import cv2
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, StreamingResponse
from fastapi.templating import Jinja2Templates
from utils.postprocess import postprocess_frame
from httpx import AsyncClient, Timeout
from contextlib import asynccontextmanager
timeout = Timeout(10.0, connect=5.0)
@asynccontextmanager
async def lifespan(app: FastAPI):
# Initialize a shared HTTP/2 client for the application
app.state.http_client = AsyncClient(http2=True, timeout=timeout)
yield
await app.state.http_client.aclose()
templates = Jinja2Templates(directory="templates")
app = FastAPI(lifespan=lifespan)
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse(name="index.html", context={"request": request})
async def gen():
"""Video streaming generator function."""
camera = cv2.VideoCapture("data/videos/no_person.mp4")
# Initialize variables for measuring frame rate
start_time = time.time_ns()
frame_count = 0
frame_id = 0
fps = -1
while True:
success, frame = camera.read()
if not success:
break
# frame = process_frame(frame=frame, frame_id=frame_id, fps=fps)
# Post-process frame
frame = postprocess_frame(frame=frame, input_size=(500, 320))
# Draw frame information at the top of the image
cv2.putText(
img=frame,
text=f"frame: {frame_id} fps: {fps:.2f}",
org=(0, int(15 * 2)),
fontFace=cv2.FONT_HERSHEY_PLAIN,
fontScale=2,
color=(0, 0, 255),
thickness=2,
)
ret, buffer = cv2.imencode(".jpeg", frame)
frame = buffer.tobytes()
# Calculate and display the frame rate
frame_id += 1
frame_count += 1
if frame_count >= 10:
fps = 1e9 * frame_count / (time.time_ns() - start_time)
print(f"fps: {fps:.2f}")
frame_count = 0
start_time = time.time_ns()
yield (b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n")
camera.release()
@app.get("/video_feed")
async def video_feed():
return StreamingResponse(
gen(), media_type="multipart/x-mixed-replace;boundary=frame"
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)