File size: 2,084 Bytes
b942ddb
 
 
907a042
 
 
 
b942ddb
907a042
 
 
b942ddb
 
 
907a042
b942ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
907a042
 
 
b942ddb
907a042
b942ddb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
907a042
b942ddb
 
 
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
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)}")