Created
August 5, 2024 09:35
-
-
Save junaire/ea446053dfa26d78fdf17ed0d0ea9d7e to your computer and use it in GitHub Desktop.
Live Stream your webcam
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# pip install fastapi uvicorn opencv-python | |
from fastapi import FastAPI | |
from fastapi.responses import StreamingResponse | |
import cv2 | |
import time | |
app = FastAPI() | |
def gen_frames(): | |
cap = cv2.VideoCapture(0) | |
while True: | |
success, frame = cap.read() | |
if not success: | |
break | |
else: | |
frame = cv2.flip(frame, 1) | |
_, buffer = cv2.imencode(".jpg", frame) | |
frame = buffer.tobytes() | |
yield ( | |
b"--frame\r\n" b"Content-Type: image/jpeg\r\n\r\n" + frame + b"\r\n" | |
) | |
time.sleep(0.05) | |
@app.get("/") | |
def video_feed(): | |
return StreamingResponse( | |
gen_frames(), media_type="multipart/x-mixed-replace; boundary=frame" | |
) | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=8888) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment