Spaces:
Runtime error
Runtime error
Upload gradio.py
Browse files
gradio.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from PIL import Image, ImageDraw
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torchvision.transforms as T
|
| 6 |
+
|
| 7 |
+
# Load your model
|
| 8 |
+
model = torch.hub.load('ultralytics/yolov5', 'custom', path='best.pt') # Adjust path if necessary
|
| 9 |
+
model.eval()
|
| 10 |
+
|
| 11 |
+
# Define your classes
|
| 12 |
+
classes = [
|
| 13 |
+
"Apple", "Banana", "Beetroot", "Bitter_Gourd", "Bottle_Gourd", "Cabbage",
|
| 14 |
+
"Capsicum", "Carrot", "Cauliflower", "Cherry", "Chilli", "Coconut",
|
| 15 |
+
"Cucumber", "EggPlant", "Ginger", "Grape", "Green_Orange", "Kiwi",
|
| 16 |
+
"Maize", "Mango", "Melon", "Okra", "Onion", "Orange", "Peach", "Pear",
|
| 17 |
+
"Peas", "Pineapple", "Pomegranate", "Potato", "Radish", "Strawberry",
|
| 18 |
+
"Tomato", "Turnip", "Watermelon", "walnut", "almond"
|
| 19 |
+
]
|
| 20 |
+
|
| 21 |
+
# Define the inference function
|
| 22 |
+
def detect(image):
|
| 23 |
+
# Transform the image to tensor
|
| 24 |
+
transform = T.Compose([T.ToTensor()])
|
| 25 |
+
input_tensor = transform(image).unsqueeze(0)
|
| 26 |
+
|
| 27 |
+
# Perform inference
|
| 28 |
+
with torch.no_grad():
|
| 29 |
+
detections = model(input_tensor)[0]
|
| 30 |
+
|
| 31 |
+
# Draw bounding boxes and labels on the image
|
| 32 |
+
draw = ImageDraw.Draw(image)
|
| 33 |
+
for detection in detections:
|
| 34 |
+
# Each detection includes [x1, y1, x2, y2, confidence, class]
|
| 35 |
+
x1, y1, x2, y2, conf, cls = detection
|
| 36 |
+
if conf >= 0.5: # Consider detections with confidence >= 0.5
|
| 37 |
+
label = classes[int(cls)]
|
| 38 |
+
draw.rectangle(((x1, y1), (x2, y2)), outline="red", width=2)
|
| 39 |
+
draw.text((x1, y1), f"{label} ({conf:.2f})", fill="red")
|
| 40 |
+
|
| 41 |
+
return np.array(image)
|
| 42 |
+
|
| 43 |
+
# Create a Gradio interface
|
| 44 |
+
iface = gr.Interface(
|
| 45 |
+
fn=detect,
|
| 46 |
+
inputs=gr.inputs.Image(source="webcam", tool="editor"),
|
| 47 |
+
outputs="image",
|
| 48 |
+
live=True,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
# Launch the app
|
| 52 |
+
iface.launch()
|