Implementing an HTTP endpoint to perform face detection on a single image
Before working with WebSockets, we'll start simple and implement, using FastAPI, a classic HTTP endpoint for accepting image uploads and performing face detection on them. As you'll see, the main difference from the previous example is in how we acquire the image: instead of streaming it from the webcam, we get it from a file upload that we have to convert into an OpenCV image object.
You can see the whole implementation in the following code:
chapter14_api.py
from typing import List, Tuple import cv2 import numpy as np from fastapi import FastAPI, File, UploadFile from pydantic import BaseModel app = FastAPI() cascade_classifier = cv2.CascadeClassifier() class Faces(BaseModel): faces: List[Tuple[int, int, int, int]] @app.post("/face-detection", response_model=Faces) async def face_detection(image: UploadFile = File(...)) -> Faces: ...