ayoubsa's picture
Update app.py
43a659b verified
raw
history blame
6.77 kB
"""import gradio as gr
import torch
from PIL import Image
from pathlib import Path
import numpy as np
# Load YOLO Model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='https://huggingface.co/ayoubsa/yolo_model/blob/main/best.pt') # Replace 'model.pt' with your uploaded model's path
# Function to make predictions
def predict(image):
# Convert input to PIL image if it's not
if isinstance(image, np.ndarray):
image = Image.fromarray(image)
# Run inference
results = model(image)
# Extract predictions (bounding boxes, labels, confidence scores)
predictions = results.pandas().xyxy[0] # Pandas dataframe
annotated_image = np.array(results.render()[0]) # Annotated image as NumPy array
return annotated_image, predictions[['name', 'confidence']].to_dict(orient="records")
# Create Gradio Interface
image_input = gr.inputs.Image(type="numpy", label="Input Image")
output_image = gr.outputs.Image(type="numpy", label="Annotated Image")
output_text = gr.outputs.JSON(label="Predictions (Labels & Confidence)")
interface = gr.Interface(
fn=predict,
inputs=image_input,
outputs=[output_image, output_text],
title="YOLO Object Detection",
description="Upload an image to detect objects using YOLO.",
examples=["example1.jpg", "example2.jpg", "example3.jpg"] # Provide paths to example images
)
interface.launch()
from datasets import load_dataset
import gradio as gr
import random
import numpy as np
from PIL import Image
import torch
# Load the YOLO model
model = torch.hub.load('ultralytics/yolov5', 'custom', path='https://huggingface.co/ayoubsa/yolo_model/blob/main/best.pt') # Replace with your uploaded model's path
# Load your dataset from Hugging Face
dataset = load_dataset("https://huggingface.co/datasets/ayoubsa/Sign_Road_Detection_Dataset/tree/main") # Replace with your dataset's repository name on Hugging Face
# Function to get random examples from the dataset
def get_random_examples(dataset, num_examples=3):
images = dataset['test'][:]['image'] # Assuming the images are in the 'train' split and column 'image'
random_examples = random.sample(images, num_examples)
return random_examples
# Define the prediction function
def predict(image):
results = model(image) # Perform object detection using YOLO
results.render() # Render bounding boxes on the image
output_image = Image.fromarray(results.imgs[0]) # Convert to PIL image
return output_image
# Get examples for Gradio app
example_images = get_random_examples(dataset, num_examples=3)
# Create the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=gr.inputs.Image(type="pil"), # PIL Image for compatibility with YOLO
outputs=gr.outputs.Image(type="pil"),
examples=example_images # Linking examples directly from Hugging Face dataset
)
# Launch the Gradio app
iface.launch()
import gradio as gr
import torch
from PIL import Image
import zipfile
import os
import random
# Define the paths for the model and dataset
MODEL_PATH = 'https://huggingface.co/ayoubsa/yolo_model/resolve/main/best.pt' # YOLO model file
DATASET_PATH = 'test.zip' # The name of the uploaded test dataset zip file
# Load the YOLO model
model = torch.hub.load('ultralytics/yolov5', 'custom', path=MODEL_PATH)
# Unzip the dataset
if not os.path.exists("unzipped_test"):
with zipfile.ZipFile(DATASET_PATH, 'r') as zip_ref:
zip_ref.extractall("unzipped_test") # Extract images to this folder
# Get all image paths from the unzipped folder
image_folder = "unzipped_test"
all_images = [os.path.join(image_folder, f) for f in os.listdir(image_folder) if f.endswith(('.jpg', '.png', '.jpeg'))]
# Function to get random examples
def get_random_examples(num_examples=3):
if len(all_images) >= num_examples:
return random.sample(all_images, num_examples)
else:
return all_images # Return whatever is available if less than required
# Define the prediction function
def predict(image):
results = model(image) # Perform object detection using YOLO
results.render() # Render bounding boxes on the image
output_image = Image.fromarray(results.imgs[0]) # Convert to PIL image
return output_image
# Get example images
example_images = get_random_examples(num_examples=3)
# Create the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=gr.inputs.Image(type="pil", label="Upload an Image"),
outputs=gr.outputs.Image(type="pil", label="Predicted Image with Bounding Boxes"),
examples=example_images # Link the example images
)
# Launch the Gradio app
iface.launch()
import gradio as gr
import torch
from PIL import Image
import numpy as np
from ultralytics import YOLO
# Load the YOLO model
MODEL_URL= 'https://huggingface.co/ayoubsa/yolo_model/resolve/main/best.pt'
model = YOLO(MODEL_URL)
# Define the prediction function
def predict(image):
results = model(image) # Perform object detection using YOLO
results.render() # Render bounding boxes on the image
output_image = Image.fromarray(results.imgs[0]) # Convert to PIL image
return output_image
# Create the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil", label="Upload an Image"), # Upload input as PIL Image
outputs=gr.Image(type="pil", label="Predicted Image with Bounding Boxes"), # Output image
title="Object Detection App",
description="Upload an image, and the YOLO model will detect objects in it."
)
# Launch the Gradio app
iface.launch()"""
from PIL import Image
import numpy as np
from ultralytics import YOLO
import gradio as gr
# Load the YOLO model
MODEL_URL = 'https://huggingface.co/ayoubsa/yolo_model/resolve/main/best.pt'
model = YOLO(MODEL_URL)
# Define the prediction function
def predict(image):
try:
print("Received image:", type(image)) # Check the type of the received image
results = model(image) # Perform object detection using YOLO
results.render() # Render bounding boxes on the image
output_image = Image.fromarray(results.imgs[0]) # Convert to PIL image
print("Predicted image:", type(output_image)) # Ensure output is PIL Image
return output_image
except Exception as e:
print("Error during prediction:", e)
return None
# Create the Gradio interface
iface = gr.Interface(
fn=predict,
inputs=gr.Image(type="pil", label="Upload an Image"), # Upload input as PIL Image
outputs=gr.Image(type="pil", label="Predicted Image with Bounding Boxes"), # Output image
title="Object Detection App",
description="Upload an image, and the YOLO model will detect objects in it."
)
# Launch the Gradio app
iface.launch()