rmayormartins commited on
Commit
af414e2
·
1 Parent(s): c4c4ff4
Files changed (2) hide show
  1. app.py +41 -17
  2. requirements.txt +5 -0
app.py CHANGED
@@ -3,43 +3,67 @@ import numpy as np
3
  from PIL import Image
4
  import torch
5
  import matplotlib.pyplot as plt
 
6
 
7
  # Modelo
8
- model = torch.hub.load('ultralytics/yolov5', 'custom', path='bestyolo5.pt')
9
 
10
  def detect(img):
 
 
 
11
  img_arr = np.array(img)
12
  results = model(img_arr)
13
-
14
- fig, ax = plt.subplots()
 
15
  ax.imshow(img_arr)
16
-
17
  cattle_count = 0
 
 
18
  for *xyxy, conf, cls in results.xyxy[0].cpu().numpy():
19
  x1, y1, x2, y2 = map(int, xyxy)
20
  label = model.names[int(cls)]
 
21
  if label == 'cattle':
22
  cattle_count += 1
23
- ax.add_patch(plt.Rectangle((x1, y1), x2-x1, y2-y1, fill=False, color='red', linewidth=2))
24
- ax.text(x1, y1, f'{label} {conf:.2f}', color='white', fontsize=8, bbox={'facecolor': 'red', 'alpha': 0.5})
25
-
 
 
 
 
 
 
 
 
26
  plt.axis('off')
27
-
28
- fig.canvas.draw()
29
- pil_img = Image.fromarray(np.array(fig.canvas.renderer._renderer))
 
 
 
 
30
  plt.close(fig)
31
-
32
  return pil_img, cattle_count
33
 
34
- # Gradio
35
  iface = gr.Interface(
36
  fn=detect,
37
  inputs=gr.Image(type="pil"),
38
- outputs=[gr.Image(type="pil"), gr.Textbox(label="Number of Cattle Detected")],
39
- title="YOLOv5 Cattle Counter",
40
- description="Object detector trained to count cattle using YOLOv5.",
41
- examples=[["example1.jpg"]]
 
 
 
 
42
  )
43
 
44
  if __name__ == "__main__":
45
- iface.launch()
 
3
  from PIL import Image
4
  import torch
5
  import matplotlib.pyplot as plt
6
+ import io
7
 
8
  # Modelo
9
+ model = torch.hub.load('ultralytics/yolov5', 'custom', path='bestyolo5.pt', trust_repo=True)
10
 
11
  def detect(img):
12
+ if img is None:
13
+ return None, 0
14
+
15
  img_arr = np.array(img)
16
  results = model(img_arr)
17
+
18
+ # Criar figura
19
+ fig, ax = plt.subplots(figsize=(10, 8))
20
  ax.imshow(img_arr)
21
+
22
  cattle_count = 0
23
+
24
+ # Processar detecções
25
  for *xyxy, conf, cls in results.xyxy[0].cpu().numpy():
26
  x1, y1, x2, y2 = map(int, xyxy)
27
  label = model.names[int(cls)]
28
+
29
  if label == 'cattle':
30
  cattle_count += 1
31
+
32
+ # Desenhar bounding box
33
+ ax.add_patch(plt.Rectangle((x1, y1), x2-x1, y2-y1,
34
+ fill=False, color='red', linewidth=2))
35
+
36
+ # Adicionar label
37
+ ax.text(x1, y1-10, f'{label} {conf:.2f}',
38
+ color='white', fontsize=10,
39
+ bbox={'facecolor': 'red', 'alpha': 0.7})
40
+
41
+ ax.set_title(f'Detecções: {cattle_count} gado encontrado')
42
  plt.axis('off')
43
+ plt.tight_layout()
44
+
45
+ # Converter para PIL Image
46
+ buf = io.BytesIO()
47
+ plt.savefig(buf, format='png', bbox_inches='tight', dpi=150)
48
+ buf.seek(0)
49
+ pil_img = Image.open(buf)
50
  plt.close(fig)
51
+
52
  return pil_img, cattle_count
53
 
54
+ # Interface Gradio
55
  iface = gr.Interface(
56
  fn=detect,
57
  inputs=gr.Image(type="pil"),
58
+ outputs=[
59
+ gr.Image(type="pil", label="Imagem com Detecções"),
60
+ gr.Number(label="Número de Gado Detectado")
61
+ ],
62
+ title="🐄 YOLOv5 Contador de Gado",
63
+ description="Detector de objetos treinado para contar gado usando YOLOv5.",
64
+ examples=[["example1.jpg"]] if False else None, # Remova ou adicione imagens de exemplo
65
+ theme=gr.themes.Soft()
66
  )
67
 
68
  if __name__ == "__main__":
69
+ iface.launch(share=True, debug=True)
requirements.txt CHANGED
@@ -2,6 +2,11 @@ gradio==4.29.0
2
  numpy
3
  Pillow
4
  torch
 
5
  matplotlib
6
  opencv-python
7
  seaborn
 
 
 
 
 
2
  numpy
3
  Pillow
4
  torch
5
+ torchvision
6
  matplotlib
7
  opencv-python
8
  seaborn
9
+ ultralytics
10
+ PyYAML
11
+ requests
12
+ tqdm