Spaces:
Sleeping

Faster-RCNN / app.py
bacngv's picture
Update app.py
813da59 verified
Raw History Blame Contribute Delete
3.5 kB
import gradio as gr
import torch
import numpy as np
from torchvision.models.detection import fasterrcnn_resnet50_fpn_v2
from PIL import Image, ImageDraw
import albumentations as A
from albumentations.pytorch import ToTensorV2
# Initialize Faster R-CNN model
model = fasterrcnn_resnet50_fpn_v2(pretrained=True)
# Load the saved state_dict
state_dict = torch.load("faster-rcnn.pth", map_location=torch.device('cpu'))
model.load_state_dict(state_dict)
# Set the model to evaluation mode
model.eval()
# Define class names and color map
CLASS_NAMES = ['bone-fracture', 'angle', 'fracture', 'line', 'messed_up_angle']
COLOR_MAP = {
'bone-fracture': (255, 0, 0),
'angle': (0, 255, 0),
'fracture': (0, 0, 255),
'line': (255, 255, 0),
'messed_up_angle': (255, 165, 0)
}
def map_label_to_class(label_id):
return CLASS_NAMES[label_id - 1]
def draw_boxes_with_labels(image, boxes, labels):
draw = ImageDraw.Draw(image)
for box, label in zip(boxes, labels):
x1, y1, x2, y2 = box
# Convert the box coordinates to integers
x1, y1, x2, y2 = map(int, [x1, y1, x2, y2])
color = COLOR_MAP[label]
draw.rectangle([x1, y1, x2, y2], outline=color, width=4)
text_position = (x1, y1 - 10)
# Draw label background
text_bbox = draw.textbbox(text_position, label)
draw.rectangle(text_bbox, fill=color)
# Draw label text
draw.text(text_position, label, fill="white")
return image
def get_transforms(train=False):
if train:
transform = A.Compose([
A.Resize(800, 800),
A.HorizontalFlip(p=0.3),
A.VerticalFlip(p=0.3),
A.RandomBrightnessContrast(p=0.1),
A.ColorJitter(p=0.1),
ToTensorV2()
], bbox_params=A.BboxParams(format='coco'))
else:
transform = A.Compose([
A.Resize(800, 800),
ToTensorV2()
], bbox_params=A.BboxParams(format='coco'))
return transform
def predict_image(image):
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Preprocess the input image
original_image = np.array(image) # Lưu lại hình ảnh gốc
transform = get_transforms(train=False)
transformed = transform(image=original_image)
image_tensor = transformed['image'].unsqueeze(0).to(device)
image_tensor = image_tensor.float() / 255.0 # Normalize image tensor
# Predict using the model
with torch.no_grad():
prediction = model(image_tensor)
# Extract predictions (boxes, labels, scores)
pred = prediction[0]
boxes = pred['boxes'][pred['scores'] > 0.1]
labels = pred['labels'][pred['scores'] > 0.1]
# Convert labels to class names
label_names = [map_label_to_class(label.item()) for label in labels]
# Adjust box coordinates according to original image size
height, width = original_image.shape[:2]
boxes[:, [0, 2]] *= (800 / width) # scale x-coordinates
boxes[:, [1, 3]] *= (800 / height) # scale y-coordinates
# Convert the original image back to PIL format
pil_image = Image.fromarray(original_image)
# Draw the boxes and labels on the image
drawn_image = draw_boxes_with_labels(pil_image, boxes.cpu(), label_names)
return drawn_image
# Define the Gradio interface
def predict(img):
output_image = predict_image(img)
return output_image
gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs=gr.Image()).launch()