chocoplot's picture
update app.py
a41584c verified
from collections import defaultdict
import gradio as gr
import PIL.Image as Image
from ultralytics import YOLO
model = YOLO("best.pt")
def predict_image(img, conf_threshold, iou_threshold):
"""Predicts and plots labeled objects in an image using YOLOv8 model with adjustable confidence and IOU thresholds."""
results = model.predict(
source=img,
conf=conf_threshold,
iou=iou_threshold,
show_labels=True,
show_conf=True,
imgsz=640,
)
label_counts = defaultdict(int)
for r in results:
if r.boxes is not None:
for box in r.boxes:
label = r.names[
int(box.cls.item())
] # Convert tensor to int and then get the label
label_counts[label] += 1
im_array = r.plot()
im = Image.fromarray(im_array[..., ::-1])
label_counts_str = "\n".join(
[f"{label}: {count}" for label, count in label_counts.items()]
)
return im, label_counts_str
logo_html = """
<style>
table {
margin-left: auto;
margin-right: auto;
}
</style>
<table class="table">
<tbody>
<tr>
<td><img width="100px" src="https://upload.wikimedia.org/wikipedia/commons/e/eb/Univalle.svg" alt="Univalle"> </td>
<td><img width="220px" src="https://i.ibb.co/6vdWxb4/PSI-LOGO.png" alt="PSI"></td>
</tr>
</tbody>
</table>
<h1>Reconocimiento de Medicamentos</h1>
<p>Subir Imagenes para Inferencia con un modelo customizado de YOLOv8</p>
<b>Creado Por:</b></br>
Edwar Stiven Montaño Cely </br>
<b>Correo:</b> Edwar.montano@correounivalle.edu.co</br>
<h2>Imágenes de las 10 cajas de medicamentos seleccionados para el estudio</h2>
<img
sizes="(max-width: 600px) 480px,
800px"
src="https://pub-ae3fb8dcc56d4bcb9396023dc3901a9b.r2.dev/Medicamentos%20a%20reconocer.png"
alt="Medicamentos" />
"""
iface = gr.Interface(
fn=predict_image,
inputs=[
gr.Image(type="pil", label="Upload Image"),
gr.Slider(minimum=0, maximum=1, value=0.4, label="Confidence threshold"),
gr.Slider(minimum=0, maximum=1, value=0.5, label="IoU threshold"),
],
outputs=[
gr.Image(type="pil", label="Result"),
gr.Textbox(label="Total Labels Recognized"),
],
title="Reconocimiento de Mediacamentos",
description=logo_html,
examples=[
["assets/01.jpeg", 0.38, 0.45],
["assets/02.jpeg", 0.38, 0.45],
["assets/03.jpeg", 0.4, 0.5],
["assets/04.jpeg", 0.4, 0.5],
],
allow_flagging="never",
)
if __name__ == "__main__":
iface.launch()