Update app.py
Browse files
app.py
CHANGED
@@ -1,20 +1,88 @@
|
|
1 |
-
from config import model
|
2 |
-
from mmcv.utils import Config
|
3 |
-
from mmdet.models import build_detector
|
4 |
import torch
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
|
|
8 |
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
-
|
|
|
|
|
|
|
13 |
|
14 |
-
dummy_input = torch.randn(1, 3, 800, 1333)
|
15 |
with torch.no_grad():
|
16 |
-
output =
|
17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
18 |
|
19 |
if __name__ == "__main__":
|
20 |
-
|
|
|
|
|
|
|
|
|
1 |
import torch
|
2 |
+
import torchvision
|
3 |
+
from PIL import Image
|
4 |
+
import numpy as np
|
5 |
+
import matplotlib.pyplot as plt
|
6 |
+
import gradio as gr
|
7 |
|
8 |
+
# Load pretrained Mask R-CNN model
|
9 |
+
model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True)
|
10 |
+
model.eval()
|
11 |
|
12 |
+
# COCO labels
|
13 |
+
COCO_INSTANCE_CATEGORY_NAMES = [
|
14 |
+
'__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
|
15 |
+
'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
|
16 |
+
'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
|
17 |
+
'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella',
|
18 |
+
'N/A', 'N/A', 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard',
|
19 |
+
'sports ball', 'kite', 'baseball bat', 'baseball glove', 'skateboard',
|
20 |
+
'surfboard', 'tennis racket', 'bottle', 'N/A', 'wine glass', 'cup', 'fork',
|
21 |
+
'knife', 'spoon', 'bowl', 'banana', 'apple', 'sandwich', 'orange', 'broccoli',
|
22 |
+
'carrot', 'hot dog', 'pizza', 'donut', 'cake', 'chair', 'couch', 'potted plant',
|
23 |
+
'bed', 'N/A', 'dining table', 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop',
|
24 |
+
'mouse', 'remote', 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster',
|
25 |
+
'sink', 'refrigerator', 'N/A', 'book', 'clock', 'vase', 'scissors', 'teddy bear',
|
26 |
+
'hair drier', 'toothbrush'
|
27 |
+
]
|
28 |
|
29 |
+
# Detection and segmentation function
|
30 |
+
def segment_objects(image, threshold=0.5):
|
31 |
+
transform = torchvision.transforms.ToTensor()
|
32 |
+
img_tensor = transform(image).unsqueeze(0)
|
33 |
|
|
|
34 |
with torch.no_grad():
|
35 |
+
output = model(img_tensor)[0]
|
36 |
+
|
37 |
+
masks = output['masks'] # shape: [N, 1, H, W]
|
38 |
+
boxes = output['boxes']
|
39 |
+
labels = output['labels']
|
40 |
+
scores = output['scores']
|
41 |
+
|
42 |
+
image_np = np.array(image).copy()
|
43 |
+
fig, ax = plt.subplots(1, figsize=(10, 10))
|
44 |
+
ax.imshow(image_np)
|
45 |
+
|
46 |
+
for i in range(len(masks)):
|
47 |
+
if scores[i] >= threshold:
|
48 |
+
mask = masks[i, 0].cpu().numpy()
|
49 |
+
mask = mask > 0.5 # convert to binary mask
|
50 |
+
|
51 |
+
# Random color for each mask
|
52 |
+
color = np.random.rand(3)
|
53 |
+
colored_mask = np.zeros_like(image_np, dtype=np.uint8)
|
54 |
+
for c in range(3):
|
55 |
+
colored_mask[:, :, c] = mask * int(color[c] * 255)
|
56 |
+
|
57 |
+
# Blend the mask onto the image
|
58 |
+
image_np = np.where(mask[:, :, None], 0.5 * image_np + 0.5 * colored_mask, image_np).astype(np.uint8)
|
59 |
+
|
60 |
+
# Draw bounding box
|
61 |
+
x1, y1, x2, y2 = boxes[i].cpu().numpy()
|
62 |
+
ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
|
63 |
+
fill=False, color=color, linewidth=2))
|
64 |
+
label = COCO_INSTANCE_CATEGORY_NAMES[labels[i].item()]
|
65 |
+
ax.text(x1, y1, f"{label}: {scores[i]:.2f}",
|
66 |
+
bbox=dict(facecolor='yellow', alpha=0.5), fontsize=10)
|
67 |
+
|
68 |
+
ax.imshow(image_np)
|
69 |
+
ax.axis('off')
|
70 |
+
output_path = "output_maskrcnn_with_masks.png"
|
71 |
+
plt.savefig(output_path, bbox_inches='tight', pad_inches=0)
|
72 |
+
plt.close()
|
73 |
+
return output_path
|
74 |
+
|
75 |
+
# Gradio interface
|
76 |
+
interface = gr.Interface(
|
77 |
+
fn=segment_objects,
|
78 |
+
inputs=[
|
79 |
+
gr.Image(type="pil", label="Upload Image"),
|
80 |
+
gr.Slider(0.0, 1.0, value=0.5, step=0.05, label="Confidence Threshold")
|
81 |
+
],
|
82 |
+
outputs=gr.Image(type="filepath", label="Segmented Output"),
|
83 |
+
title="Mask R-CNN Instance Segmentation",
|
84 |
+
description="Upload an image to detect and segment objects using a pretrained Mask R-CNN model (TorchVision)."
|
85 |
+
)
|
86 |
|
87 |
if __name__ == "__main__":
|
88 |
+
interface.launch(debug=True)
|