Junior16 commited on
Commit
15e4aa2
verified
1 Parent(s): bcab5b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -1
app.py CHANGED
@@ -4,12 +4,20 @@ import numpy as np
4
  from PIL import Image
5
  import io
6
  import base64
 
 
7
 
8
  app = FastAPI()
9
 
 
 
 
 
 
10
  @app.post("/detect/")
11
  async def detect_face(file: UploadFile = File(...)):
12
  try:
 
13
  image_bytes = await file.read()
14
  image = Image.open(io.BytesIO(image_bytes))
15
  img_np = np.array(image)
@@ -17,6 +25,7 @@ async def detect_face(file: UploadFile = File(...)):
17
  if img_np.shape[2] == 4:
18
  img_np = cv2.cvtColor(img_np, cv2.COLOR_BGRA2BGR)
19
 
 
20
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
21
  gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
22
  faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
@@ -24,19 +33,38 @@ async def detect_face(file: UploadFile = File(...)):
24
  if len(faces) == 0:
25
  raise HTTPException(status_code=404, detail="No se detectaron rostros en la imagen.")
26
 
 
27
  for (x, y, w, h) in faces:
 
 
 
 
 
 
 
 
 
 
 
28
  cv2.rectangle(img_np, (x, y), (x+w, y+h), (255, 0, 0), 2)
 
 
 
 
29
 
 
30
  result_image = Image.fromarray(cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB))
31
  img_byte_arr = io.BytesIO()
32
  result_image.save(img_byte_arr, format='JPEG')
33
  img_byte_arr = img_byte_arr.getvalue()
34
 
 
35
  return {
36
  "message": "Rostros detectados",
37
- "rostros": len(faces),
38
  "imagen_base64": base64.b64encode(img_byte_arr).decode('utf-8')
39
  }
40
 
41
  except Exception as e:
42
  raise HTTPException(status_code=500, detail=str(e))
 
 
4
  from PIL import Image
5
  import io
6
  import base64
7
+ from transformers import AutoModelForImageClassification, AutoFeatureExtractor
8
+ import torch
9
 
10
  app = FastAPI()
11
 
12
+ # Cargar el modelo preentrenado para clasificaci贸n de g茅nero
13
+ model_name = "nateraw/bert-imagenet" # Cambiar a un modelo adecuado si se encuentra uno m谩s espec铆fico
14
+ model = AutoModelForImageClassification.from_pretrained(model_name)
15
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
16
+
17
  @app.post("/detect/")
18
  async def detect_face(file: UploadFile = File(...)):
19
  try:
20
+ # Leer y preparar la imagen
21
  image_bytes = await file.read()
22
  image = Image.open(io.BytesIO(image_bytes))
23
  img_np = np.array(image)
 
25
  if img_np.shape[2] == 4:
26
  img_np = cv2.cvtColor(img_np, cv2.COLOR_BGRA2BGR)
27
 
28
+ # Detecci贸n de rostros con OpenCV
29
  face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
30
  gray = cv2.cvtColor(img_np, cv2.COLOR_BGR2GRAY)
31
  faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
 
33
  if len(faces) == 0:
34
  raise HTTPException(status_code=404, detail="No se detectaron rostros en la imagen.")
35
 
36
+ result_data = []
37
  for (x, y, w, h) in faces:
38
+ # Extraer cada rostro
39
+ face_img = img_np[y:y+h, x:x+w]
40
+ face_img_pil = Image.fromarray(cv2.cvtColor(face_img, cv2.COLOR_BGR2RGB)).resize((224, 224))
41
+
42
+ # Clasificar el rostro
43
+ inputs = feature_extractor(images=face_img_pil, return_tensors="pt")
44
+ outputs = model(**inputs)
45
+ predicted_class = outputs.logits.argmax(dim=-1).item()
46
+ label = model.config.id2label[predicted_class]
47
+
48
+ # Dibujar rect谩ngulo y agregar datos
49
  cv2.rectangle(img_np, (x, y), (x+w, y+h), (255, 0, 0), 2)
50
+ result_data.append({
51
+ "coordenadas": [int(x), int(y), int(w), int(h)],
52
+ "sexo": label
53
+ })
54
 
55
+ # Preparar imagen resultante
56
  result_image = Image.fromarray(cv2.cvtColor(img_np, cv2.COLOR_BGR2RGB))
57
  img_byte_arr = io.BytesIO()
58
  result_image.save(img_byte_arr, format='JPEG')
59
  img_byte_arr = img_byte_arr.getvalue()
60
 
61
+ # Respuesta
62
  return {
63
  "message": "Rostros detectados",
64
+ "resultados": result_data,
65
  "imagen_base64": base64.b64encode(img_byte_arr).decode('utf-8')
66
  }
67
 
68
  except Exception as e:
69
  raise HTTPException(status_code=500, detail=str(e))
70
+