Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from ultralytics import YOLO
|
3 |
+
import cv2
|
4 |
+
import numpy as np
|
5 |
+
import os
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
|
9 |
+
def perform(image):
|
10 |
+
"""Perform the task of detection"""
|
11 |
+
# Predict with the model
|
12 |
+
results = model(image, save=True) # predict on an image
|
13 |
+
# get the saved prediction
|
14 |
+
prediction_image = Image.open(os.path.join(results[0].save_dir, os.listdir(results[0].save_dir)[0]))
|
15 |
+
# initialize the output list to save the bbox
|
16 |
+
outputs = []
|
17 |
+
# Access the results
|
18 |
+
for result in results[0]:
|
19 |
+
xywh = result.boxes.xyxy[0].numpy().tolist() # top-left-x, top-left-y, bottom-right-x, bottom-right-y
|
20 |
+
name = result.names[result.boxes.cls.item()] # classes
|
21 |
+
confs = float(result.boxes.conf) # confidence score of each box
|
22 |
+
outputs.append({"xywh":xywh ,"conf":confs, "name":name})
|
23 |
+
# return the image and the bbox
|
24 |
+
return prediction_image, outputs
|
25 |
+
|
26 |
+
def load_model(model_name:str = "yolo11n.pt"):
|
27 |
+
"""Model loading"""
|
28 |
+
try:
|
29 |
+
print(f"Loading the model {model_name}")
|
30 |
+
model = YOLO(model_name)
|
31 |
+
except Exception as e:
|
32 |
+
print(f"Error loading the model {e}")
|
33 |
+
return model
|
34 |
+
|
35 |
+
# loading the model
|
36 |
+
model = load_model()
|
37 |
+
|
38 |
+
# Create the Gradio interface
|
39 |
+
demo = gr.Interface(
|
40 |
+
fn=perform,
|
41 |
+
inputs=[gr.Image(type="pil")], # PIL Image format
|
42 |
+
outputs=[gr.Image(type="pil"), gr.JSON()],
|
43 |
+
title="Object Detection using YOLO",
|
44 |
+
description="Upload an image and get image with bbox in it",
|
45 |
+
examples=None # You can add example images here if needed
|
46 |
+
)
|
47 |
+
|
48 |
+
# Launch the app
|
49 |
+
if __name__ == "__main__":
|
50 |
+
username = os.environ.get('username')
|
51 |
+
password = os.environ.get('password')
|
52 |
+
print(username, " ",password)
|
53 |
+
demo.launch(share=True,
|
54 |
+
auth=(username, password)
|
55 |
+
)
|