Spaces:
Sleeping
Sleeping
Alex
commited on
Commit
·
d56dfe8
1
Parent(s):
cdfd25e
Aggiunto endpoint per rilevamento singolo volto con YOLOv8
Browse files- YoloV8-FaceDetection.pt +3 -0
- app.py +46 -0
- requirements.txt +5 -0
YoloV8-FaceDetection.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:37396ac6a9601ab9f5177e4231b09d81cf6f65a7f22db99ec3b36ab63f674e71
|
3 |
+
size 6247065
|
app.py
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from fastapi import FastAPI, UploadFile, File
|
2 |
+
from PIL import Image
|
3 |
+
from ultralytics import YOLO
|
4 |
+
import io
|
5 |
+
import torch
|
6 |
+
|
7 |
+
app = FastAPI()
|
8 |
+
|
9 |
+
# Carica il modello all'avvio (singleton per efficienza)
|
10 |
+
model = YOLO("yolov8n.pt") # Sostituisci con "yolov8n-face.pt" se disponibile
|
11 |
+
|
12 |
+
def preprocess_image(image: Image.Image, size=(320, 320)):
|
13 |
+
"""Ridimensiona l'immagine per velocizzare l'inferenza"""
|
14 |
+
img = image.convert("RGB")
|
15 |
+
img = img.resize(size, Image.LANCZOS) # 320x320 è veloce su CPU
|
16 |
+
return img
|
17 |
+
|
18 |
+
@app.post("/detect_single_face")
|
19 |
+
async def detect_single_face(file: UploadFile = File(...)):
|
20 |
+
try:
|
21 |
+
# Leggi e preprocessa l'immagine
|
22 |
+
image_bytes = await file.read()
|
23 |
+
image = Image.open(io.BytesIO(image_bytes))
|
24 |
+
image = preprocess_image(image)
|
25 |
+
|
26 |
+
# Esegui l'inferenza con YOLOv8
|
27 |
+
results = model(image)
|
28 |
+
|
29 |
+
# Conta i volti (classe "person" per yolov8n, o "face" se usi modello specifico)
|
30 |
+
boxes = results[0].boxes
|
31 |
+
face_count = 0
|
32 |
+
for box in boxes:
|
33 |
+
# Se usi yolov8n, filtra per classe "person" (class_id 0 in COCO)
|
34 |
+
# Se usi yolov8n-face, conta direttamente tutte le detection
|
35 |
+
if int(box.cls) == 0: # "person" in yolov8n
|
36 |
+
face_count += 1
|
37 |
+
|
38 |
+
# Restituisci True solo se c'è esattamente 1 volto
|
39 |
+
return {"has_single_face": face_count == 1}
|
40 |
+
except Exception as e:
|
41 |
+
return {"error": str(e)}
|
42 |
+
|
43 |
+
# Avvio del server (Hugging Face lo gestisce automaticamente)
|
44 |
+
if __name__ == "__main__":
|
45 |
+
import uvicorn
|
46 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
fastapi==0.115.0
|
2 |
+
uvicorn==0.30.6
|
3 |
+
ultralytics==8.2.103
|
4 |
+
pillow==10.4.0
|
5 |
+
torch==2.4.1
|