# -*- coding: utf-8 -*- """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 """ #!pip install -qr https://raw.githubusercontent.com/ultralytics/yolov5/master/requirements.txt gradio # install dependencies import os import re import json import numpy as np import pandas as pd import gradio as gr import torch from PIL import Image from ultralytics import YOLO #from ultralyticsplus import render_result # Images torch.hub.download_url_to_file('https://i.pinimg.com/originals/7f/5e/96/7f5e9657c08aae4bcd8bc8b0dcff720e.jpg', 'ejemplo1.jpg') torch.hub.download_url_to_file('https://i.pinimg.com/originals/c2/ce/e0/c2cee05624d5477ffcf2d34ca77b47d1.jpg', 'ejemplo2.jpg') # Model class YOLODetect(): def __init__(self, modelo): self.modelo = modelo def predecir(self, url): # conf float 0.25 umbral de confianza del objeto para la detección # iou float 0.7 umbral de intersección sobre unión (IoU) para NMS self.source = url self.results = self.modelo.predict(source=self.source, imgsz=640, conf=0.5, iou=0.40) return self.results def show(self): render = None #render_result(model=self.modelo, image=self.source, result=self.results[0]) return render def to_json(self): results = self.results[0] img_size = results.orig_shape img_name = results.path array_numpy = results.boxes.cls.cpu().numpy().astype(np.int32) # Definir las clases y sus nombres correspondientes clases = { 0: "Aedes", 1: "Mosquitos", 2: "Moscas" } # Contabilizar las clases conteo_clases = np.bincount(array_numpy) self.json_result = [{'Especie': clases[i], 'Cantidad': str(conteo_clases[i]) if i < len(conteo_clases) else str(0)} for i in range(len(clases))] # Crear un diccionario con los elementos necesarios result_dict = { "image": str(img_name), "size": str(img_size), "detail": self.json_result } print(f"{type(result_dict)} - {result_dict}") # Convertir el diccionario a una cadena JSON self.json_result = json.dumps(result_dict) print(f"{type(self.json_result)} - {self.json_result}") # Convertir la cadena JSON a un objeto Python (diccionario) self.json_result = json.loads(self.json_result) print(f"{type(self.json_result)} - {self.json_result}") return self.json_result def to_dataframe(self): return pd.DataFrame(self.json_result) modelo_yolo = YOLO('best.pt') def yolo(size, iou, conf, im): '''Wrapper fn for gradio''' g = (int(size) / max(im.size)) # gain im = im.resize((int(x * g) for x in im.size), Image.LANCZOS) # resize with antialiasing # model.iou = iou # model.conf = conf # results2 = model(im) # inference # #print(type(results2)) print(type(im)) source = im#Image.open(im) model = YOLODetect(modelo_yolo) results = model.predecir(source) result_json = model.to_json() print(result_json) result_df = None#model.to_dataframe() print(result_df) result_img = source#model.show() #result_img, result_df, result_json = source, None, None return result_img, result_df, result_json #------------ Interface------------- in1 = gr.inputs.Radio(['640', '1280'], label="Tamaño de la imagen", type='value') in2 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, label='NMS IoU threshold') in3 = gr.inputs.Slider(minimum=0, maximum=1, step=0.05, label='Umbral o threshold') in4 = gr.inputs.Image(type='pil', label="Original Image") out2 = gr.outputs.Image(type="pil", label="YOLOv5") out3 = gr.outputs.Dataframe(label="Cantidad_especie", headers=['Cantidad','Especie'], type="pandas") out4 = gr.outputs.JSON(label="JSON") #-------------- Text----- title = 'Trampas Barceló' description = """