Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Install required libraries if not already installed
|
| 2 |
+
# !pip install gradio opencv-python torch torchvision
|
| 3 |
+
|
| 4 |
+
import gradio as gr
|
| 5 |
+
import cv2
|
| 6 |
+
import torch
|
| 7 |
+
from torchvision import models, transforms
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
# Load the pre-trained Faster R-CNN model
|
| 11 |
+
model = models.detection.fasterrcnn_resnet50_fpn(pretrained=True)
|
| 12 |
+
model.eval()
|
| 13 |
+
|
| 14 |
+
# Define the transformation for the input image
|
| 15 |
+
transform = transforms.Compose([
|
| 16 |
+
transforms.ToTensor()
|
| 17 |
+
])
|
| 18 |
+
|
| 19 |
+
# Function to perform object detection
|
| 20 |
+
def detect_objects(input_image):
|
| 21 |
+
# Convert the Gradio image to PIL Image
|
| 22 |
+
image_pil = Image.fromarray(input_image.astype('uint8'), 'RGB')
|
| 23 |
+
|
| 24 |
+
# Apply transformations
|
| 25 |
+
image = transform(image_pil)
|
| 26 |
+
image = image.unsqueeze(0) # Add batch dimension
|
| 27 |
+
|
| 28 |
+
# Get predictions
|
| 29 |
+
with torch.no_grad():
|
| 30 |
+
predictions = model(image)
|
| 31 |
+
|
| 32 |
+
# Process predictions
|
| 33 |
+
boxes = predictions[0]['boxes'].detach().numpy()
|
| 34 |
+
labels = predictions[0]['labels'].detach().numpy()
|
| 35 |
+
scores = predictions[0]['scores'].detach().numpy()
|
| 36 |
+
|
| 37 |
+
# Convert PIL Image to OpenCV format
|
| 38 |
+
image_cv = cv2.cvtColor(np.array(image_pil), cv2.COLOR_RGB2BGR)
|
| 39 |
+
|
| 40 |
+
# Draw bounding boxes on the image
|
| 41 |
+
for box, label, score in zip(boxes, labels, scores):
|
| 42 |
+
if score < 0.5:
|
| 43 |
+
continue # Skip detections with low confidence
|
| 44 |
+
x1, y1, x2, y2 = box.astype(int)
|
| 45 |
+
cv2.rectangle(image_cv, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
| 46 |
+
cv2.putText(image_cv, f'{label}: {score:.2f}', (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
|
| 47 |
+
|
| 48 |
+
# Convert back to RGB for Gradio
|
| 49 |
+
image_rgb = cv2.cvtColor(image_cv, cv2.COLOR_BGR2RGB)
|
| 50 |
+
return image_rgb
|
| 51 |
+
|
| 52 |
+
# Create the Gradio interface
|
| 53 |
+
app = gr.Interface(
|
| 54 |
+
fn=detect_objects,
|
| 55 |
+
inputs="image",
|
| 56 |
+
outputs="image",
|
| 57 |
+
title="Object Detection using Faster R-CNN",
|
| 58 |
+
description="Upload an image and the model will detect objects and draw bounding boxes around them."
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Launch the app
|
| 62 |
+
app.launch()
|