Spaces:
Sleeping
Sleeping
File size: 3,315 Bytes
fd612f9 8b8d709 fd612f9 a11c281 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 8b8d709 fd612f9 e6fc2f0 008cb2f fd612f9 8b8d709 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | import os
import torch
import numpy as np
import io
from PIL import Image, ImageDraw, ImageFont
import gradio as gr
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
import torchvision
# Path to the local model file
LOCAL_MODEL_PATH = "faster_rcnn_state.pth"
# Load model
if os.path.exists(LOCAL_MODEL_PATH):
# Create model
model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=None, weights_backbone=None)
# Update the box predictor to match the number of classes in the pretrained weights (21)
num_classes = 21 # 20 classes + background
in_features = model.roi_heads.box_predictor.cls_score.in_features
model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes)
# Load weights
model.load_state_dict(torch.load(LOCAL_MODEL_PATH, map_location='cpu'))
model.eval()
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
else:
print("Failed to load model")
# Dictionary for class labels
classes = {0: 'background', 1: 'aeroplane', 2: 'bicycle', 3: 'bird', 4: 'boat', 5: 'bottle', 6: 'bus', 7: 'car', 8: 'cat', 9: 'chair', 10: 'cow', 11: 'diningtable', 12: 'dog', 13: 'horse', 14: 'motorbike', 15: 'person', 16: 'pottedplant', 17: 'sheep', 18: 'sofa', 19: 'train', 20: 'tvmonitor'}
def obj_detector(image):
# Convert image to RGB
img = image.convert("RGB")
# Convert to numpy array and normalize
img_array = np.array(img).astype(np.float32) / 255.0
# Convert to torch tensor
img_tensor = torch.from_numpy(img_array).permute(2, 0, 1).unsqueeze(0)
# Move tensor to the same device as the model
img_tensor = img_tensor.to(device)
with torch.no_grad():
prediction = model(img_tensor)
detection_threshold = 0.7
boxes = prediction[0]['boxes'].cpu().numpy()
labels = prediction[0]['labels'].cpu().numpy()
scores = prediction[0]['scores'].cpu().numpy()
# Filter detections based on detection threshold
mask = scores >= detection_threshold
boxes = boxes[mask]
labels = labels[mask]
scores = scores[mask]
# Create a new image for drawing
draw = ImageDraw.Draw(img)
# Load a font
try:
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 20)
except IOError:
font = ImageFont.load_default()
# Draw bounding boxes and labels on the image
for box, label, score in zip(boxes, labels, scores):
box = box.astype(int)
x1, y1, x2, y2 = box
draw.rectangle(((x1, y1), (x2, y2)), outline="red", width=3)
label_text = f"{classes[label]}: {score:.2f}"
draw.text((x1, y1-25), label_text, fill="red", font=font)
return img
def inference(image):
try:
labeled_image = obj_detector(image)
return labeled_image
except Exception as e:
print(f"An error occurred during inference: {str(e)}")
raise gr.Error(f"Inference failed: {str(e)}")
iface = gr.Interface(
fn=inference,
inputs=gr.components.Image(type="pil"),
outputs=gr.components.Image(type="pil"),
title="Object Detection with Faster R-CNN by Aari Eswar",
description="Upload an image to detect objects",
)
iface.launch(share=True, show_error=True) |