eyedetector / app.py
axvg
up
b942ddb
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from typing import List, Dict
import cv2
from PIL import Image
import numpy as np
from io import BytesIO
import base64
app = FastAPI()
def detect_eyes(image: np.ndarray) -> List[Dict[str, str]]:
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
eyes = eye_cascade.detectMultiScale(gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
print("Detected eyes:", eyes, type(eyes))
if len(eyes) == 0:
return []
detections = []
for (x, y, w, h) in eyes:
# para dibujar rectangulos en ojos detectados
cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
detections.append({
"label": "eye",
"bounding_box": {
"x": int(x),
"y": int(y),
"width": int(w),
"height": int(h)
}
})
return detections
@app.post('/predict/')
async def predict(file: UploadFile = File(...)) -> JSONResponse:
try:
image = Image.open(BytesIO(await file.read())).convert("RGB")
image_np = np.array(image)
detections = detect_eyes(image_np)
if len(detections) == 0:
return JSONResponse(content={
"detections": detections,
"count": 0,
"image_with_detections": None
})
_, buffer = cv2.imencode('.jpg', image_np)
image_base64 = base64.b64encode(buffer).decode('utf-8')
return JSONResponse(content={
"detections": detections,
"count": len(detections),
"image_with_detections": image_base64
})
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Error al procesar la imagen: {str(e)}")