Edwardhuero's picture
Update app.py
008cb2f verified
Raw History Blame Contribute Delete
3.32 kB
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)