Spaces:
Sleeping

riki74's picture
Update app.py
d026e47 verified
Raw History Blame Contribute Delete
3.41 kB
# app.py
import os
import cv2
import numpy as np
import base64
import tempfile
from flask import Flask, request, jsonify
from PIL import Image
from yolo_manager import get_yolo_model
# Carica il modello YOLO tramite yolo_manager (viene caricato una sola volta all'avvio)
model = get_yolo_model()
# Inizializza l'app Flask
app = Flask(__name__)
def detect_markers(image, confidence=0.5):
"""
Esegue il modello YOLO sull'immagine e disegna i bounding boxes.
Restituisce l'immagine annotata (PIL Image) e la lista dei bounding boxes.
"""
# Esegue l'inferenza sul modello (imgsz=3520 e confidence come parametri)
results = model(image, conf=confidence, imgsz=3520)
bboxes = []
# Itera su tutti i bounding boxes rilevati
for box in results[0].boxes:
x1, y1, x2, y2 = map(int, box.xyxy.cpu().numpy().flatten())
class_id = int(box.cls.cpu().numpy().item())
label = f"Class {class_id}"
# Disegna il rettangolo e il testo sull'immagine (OpenCV lavora in BGR)
cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.putText(image, label, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 1)
bboxes.append({
"class": class_id,
"x1": x1,
"y1": y1,
"x2": x2,
"y2": y2
})
# Converti l'immagine da BGR a RGB e quindi in un oggetto PIL Image
annotated_image = Image.fromarray(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
return annotated_image, bboxes
def pil_to_base64(pil_image):
"""
Converte un'immagine PIL in una stringa Base64 codificata in formato JPEG.
"""
buffered = tempfile.SpooledTemporaryFile()
pil_image.save(buffered, format="JPEG")
buffered.seek(0)
img_bytes = buffered.read()
return base64.b64encode(img_bytes).decode("utf-8")
@app.route("/predict", methods=["POST"])
def predict():
"""
Endpoint API che accetta:
- Un file immagine tramite il campo 'file' (form-data).
- Un parametro 'confidence' (opzionale; default=0.5)
Restituisce un JSON contenente:
- L'immagine annotata (in formato Base64)
- I bounding boxes rilevati.
"""
if "file" not in request.files:
return jsonify({"error": "Nessun file inviato"}), 400
file = request.files["file"]
# Salva il file inviato in una directory temporanea
with tempfile.NamedTemporaryFile(delete=False, suffix=".jpg") as tmp:
file.save(tmp.name)
file_path = tmp.name
image = cv2.imread(file_path)
if image is None:
os.remove(file_path)
return jsonify({"error": "Impossibile leggere l'immagine"}), 400
try:
confidence = float(request.form.get("confidence", 0.5))
except ValueError:
confidence = 0.5
try:
annotated_image, bboxes = detect_markers(image, confidence)
except Exception as e:
os.remove(file_path)
return jsonify({"error": f"Errore durante l'elaborazione: {e}"}), 500
# Converte l'immagine annotata in Base64 per restituirla
annotated_image_b64 = pil_to_base64(annotated_image)
# Rimuove il file temporaneo
os.remove(file_path)
return jsonify({"annotated_image": annotated_image_b64, "detections": bboxes})
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port, debug=True)