Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, File, UploadFile, HTTPException | |
from fastapi.responses import HTMLResponse | |
from pydantic import BaseModel | |
from typing import List | |
import cv2 | |
from PIL import Image | |
import numpy as np | |
from io import BytesIO | |
import mediapipe as mp | |
app = FastAPI() | |
# Initialize MediaPipe Face Detection | |
mp_face_detection = mp.solutions.face_detection | |
face_detection = mp_face_detection.FaceDetection(min_detection_confidence=0.5) | |
def buscar_existe(image): | |
# Convert the image to RGB (MediaPipe requires RGB input) | |
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
# Process the image | |
results = face_detection.process(image_rgb) | |
# Check if any faces were detected | |
if results.detections: | |
return "si" | |
else: | |
return "no" | |
# Ruta de predicción | |
async def predict(file: UploadFile = File(...)): | |
try: | |
# Read the file | |
contents = await file.read() | |
image = Image.open(BytesIO(contents)) | |
# Convert PIL Image to numpy array | |
image_np = np.array(image) | |
# If the image is RGB, convert to BGR (OpenCV uses BGR) | |
if image_np.shape[-1] == 3: | |
image_np = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) | |
# Perform face detection | |
prediction = buscar_existe(image_np) | |
return {"prediction": prediction} | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=str(e)) | |
async def root(): | |
return {"message": "Face Detection API is running"} | |