|
|
|
"""Deploy Barcelo demo.ipynb |
|
Automatically generated by Colaboratory. |
|
Original file is located at |
|
https://colab.research.google.com/drive/1FxaL8DcYgvjPrWfWruSA5hvk3J81zLY9 |
|
![ ](https://www.vicentelopez.gov.ar/assets/images/logo-mvl.png) |
|
# Modelo |
|
YOLO es una familia de modelos de detección de objetos a escala compuesta entrenados en COCO dataset, e incluye una funcionalidad simple para Test Time Augmentation (TTA), model ensembling, hyperparameter evolution, and export to ONNX, CoreML and TFLite. |
|
## Gradio Inferencia |
|
![](https://i.ibb.co/982NS6m/header.png) |
|
Este Notebook se acelera opcionalmente con un entorno de ejecución de GPU |
|
---------------------------------------------------------------------- |
|
YOLOv5 Gradio demo |
|
*Author: Ultralytics LLC and Gradio* |
|
# Código |
|
""" |
|
|
|
|
|
|
|
import os |
|
import re |
|
import json |
|
import numpy as np |
|
import pandas as pd |
|
import gradio as gr |
|
import torch |
|
from PIL import Image |
|
|
|
|
|
torch.hub.download_url_to_file('https://huggingface.co/spaces/Municipalidad-de-Vicente-Lopez/Trampas_Barcelo/resolve/main/2024-03-11T10-50-27.jpg', 'ejemplo1.jpg') |
|
torch.hub.download_url_to_file('https://i.pinimg.com/originals/c2/ce/e0/c2cee05624d5477ffcf2d34ca77b47d1.jpg', 'ejemplo2.jpg') |
|
|
|
|
|
model = torch.hub.load('/content/yolov9', 'custom', path='/content/yolov9/best.pt', source='local', force_reload=True, autoshape=True) |
|
|
|
|
|
|
|
class YOLODetect(): |
|
def __init__(self, modelo): |
|
self.modelo = modelo |
|
|
|
def predecir(self, img, imgsz=640, conf=0.5, iou=0.40): |
|
|
|
|
|
self.modelo.iou = iou |
|
self.modelo.conf = conf |
|
self.results = self.modelo(img) |
|
return self.results |
|
|
|
def to_json(self): |
|
detail = [] |
|
|
|
for index, row in self.results_df.iterrows(): |
|
item = { |
|
"quantity": row['Cantidad'], |
|
"description": row['Especie'] |
|
} |
|
detail.append(item) |
|
|
|
data = { |
|
"image": self.results.files[0], |
|
"size": f"{self.results.s[2]}x{self.results.s[3]}", |
|
"detail": detail |
|
} |
|
|
|
return data |
|
|
|
def to_dataframe(self): |
|
labels_map = { |
|
'Aedes': "Aedes", |
|
'Mosquito': "Mosquitos", |
|
'Mosca': "Moscas", |
|
} |
|
labels = list(labels_map.keys()) |
|
|
|
columns_name = {'class': 'Cantidad', 'name': 'Especie'} |
|
self.results_df = self.results.pandas().xyxy[0][['class','name']].groupby('name').count().reset_index().rename(columns=columns_name) |
|
self.results_df = pd.merge(pd.DataFrame(labels, columns=['Especie']), self.results_df, how='left', on='Especie').fillna(0) |
|
self.results_df['Cantidad'] = self.results_df['Cantidad'].astype(int) |
|
self.results_df['Especie'] = self.results_df['Especie'].map(labels_map) |
|
return self.results_df |
|
|
|
|
|
modelo_yolo = YOLODetect(model) |
|
|
|
|
|
def yolo(size, iou, conf, im): |
|
'''Wrapper fn for gradio''' |
|
g = (int(size) / max(im.size)) |
|
im = im.resize((int(x * g) for x in im.size), Image.LANCZOS) |
|
im = np.asarray(im, dtype=np.float32) |
|
|
|
resultado = modelo_yolo.predecir(im, imgsz=size, conf=conf, iou=iou) |
|
resultado.render() |
|
resultado_df = modelo_yolo.to_dataframe() |
|
resultado_json = modelo_yolo.to_json() |
|
return Image.fromarray(resultado.ims[0]), resultado_df, resultado_json |
|
|
|
|
|
|
|
in1 = gr.inputs.Radio(['640', '1280'], label="Tamaño de la imagen", default='640', type='value') |
|
in2 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, default=0.25, label='NMS IoU threshold') |
|
in3 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, default=0.50, label='Umbral o threshold') |
|
in4 = gr.inputs.Image(type='pil', label="Original Image") |
|
|
|
out2 = gr.outputs.Image(type="pil", label="YOLOv9") |
|
out3 = gr.outputs.Dataframe(label="Cantidad_especie", headers=['Cantidad','Especie'], type="pandas") |
|
out4 = gr.outputs.JSON(label="JSON") |
|
|
|
title = 'Trampas Barceló' |
|
description = """ |
|
<p> |
|
<center> |
|
Sistemas de Desarrollado por Subsecretaría de Modernización del Municipio de Vicente López. Advertencia solo usar fotos provenientes de las trampas Barceló, no de celular o foto de internet. |
|
<img src="https://www.vicentelopez.gov.ar/assets/images/logo-mvl.png" alt="logo" width="250"/> |
|
</center> |
|
</p> |
|
""" |
|
article ="<p style='text-align: center'><a href='https://docs.google.com/presentation/d/1T5CdcLSzgRe8cQpoi_sPB4U170551NGOrZNykcJD0xU/edit?usp=sharing' target='_blank'>Para mas info, clik para ir al white paper</a></p><p style='text-align: center'><a href='https://drive.google.com/drive/folders/1owACN3HGIMo4zm2GQ_jf-OhGNeBVRS7l?usp=sharing ' target='_blank'>Google Colab Demo</a></p><p style='text-align: center'><a href='https://github.com/Municipalidad-de-Vicente-Lopez/Trampa_Barcelo' target='_blank'>Repo Github</a></p></center></p>" |
|
|
|
examples = [['640',0.25, 0.5,'ejemplo1.jpg'], ['640',0.25, 0.5,'ejemplo2.jpg']] |
|
|
|
iface = gr.Interface(yolo, |
|
inputs=[in1, in2, in3, in4], |
|
outputs=[out2,out3,out4], title=title, |
|
description=description, |
|
article=article, |
|
examples=examples, |
|
analytics_enabled=False, |
|
allow_flagging="manual", |
|
flagging_options=["Correcto", "Incorrecto", "Casi correcto", "Error", "Otro"], |
|
|
|
) |
|
|
|
|
|
iface.launch(server_name="0.0.0.0", server_port=7860, enable_queue=True, debug=True) |
|
|
|
"""For YOLOv5 PyTorch Hub inference with **PIL**, **OpenCV**, **Numpy** or **PyTorch** inputs please see the full [YOLOv5 PyTorch Hub Tutorial](https://github.com/ultralytics/yolov5/issues/36). |
|
## Citation |
|
[![DOI](https://zenodo.org/badge/264818686.svg)](https://zenodo.org/badge/latestdoi/264818686) |
|
""" |