JohnJoelMota commited on
Commit
62a791b
·
verified ·
1 Parent(s): d002069

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +74 -0
  2. requirement.txt +5 -0
app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchvision
3
+ from torchvision.models.detection import FasterRCNN_ResNet50_FPN_Weights
4
+ from PIL import Image
5
+ import numpy as np
6
+ import matplotlib.pyplot as plt
7
+ import gradio as gr
8
+
9
+ # Load the pre-trained model once
10
+ model = torchvision.models.detection.fasterrcnn_resnet50_fpn(weights=FasterRCNN_ResNet50_FPN_Weights.DEFAULT)
11
+ model.eval()
12
+
13
+ # COCO class names
14
+ COCO_INSTANCE_CATEGORY_NAMES = [
15
+ '__background__', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
16
+ 'train', 'truck', 'boat', 'traffic light', 'fire hydrant', 'N/A', 'stop sign',
17
+ 'parking meter', 'bench', 'bird', 'cat', 'dog', 'horse', 'sheep', 'cow',
18
+ 'elephant', 'bear', 'zebra', 'giraffe', 'N/A', 'backpack', 'umbrella', 'N/A', 'N/A',
19
+ 'handbag', 'tie', 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball',
20
+ 'kite', 'baseball bat', 'baseball glove', 'skateboard', 'surfboard', 'tennis racket',
21
+ 'bottle', 'N/A', 'wine glass', 'cup', 'fork', 'knife', 'spoon', 'bowl',
22
+ 'banana', 'apple', 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza',
23
+ 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', 'N/A', 'dining table',
24
+ 'N/A', 'N/A', 'toilet', 'N/A', 'tv', 'laptop', 'mouse', 'remote', 'keyboard', 'cell phone',
25
+ 'microwave', 'oven', 'toaster', 'sink', 'refrigerator', 'N/A', 'book',
26
+ 'clock', 'vase', 'scissors', 'teddy bear', 'hair drier', 'toothbrush'
27
+ ]
28
+
29
+ # Gradio-compatible detection function
30
+ def detect_objects(image, threshold=0.5):
31
+ transform = FasterRCNN_ResNet50_FPN_Weights.DEFAULT.transforms()
32
+ image_tensor = transform(image).unsqueeze(0)
33
+
34
+ with torch.no_grad():
35
+ prediction = model(image_tensor)[0]
36
+
37
+ boxes = prediction['boxes'].cpu().numpy()
38
+ labels = prediction['labels'].cpu().numpy()
39
+ scores = prediction['scores'].cpu().numpy()
40
+
41
+ image_np = np.array(image)
42
+ plt.figure(figsize=(10, 10))
43
+ plt.imshow(image_np)
44
+ ax = plt.gca()
45
+
46
+ for box, label, score in zip(boxes, labels, scores):
47
+ if score >= threshold:
48
+ x1, y1, x2, y2 = box
49
+ ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1,
50
+ fill=False, color='red', linewidth=2))
51
+ class_name = COCO_INSTANCE_CATEGORY_NAMES[label]
52
+ ax.text(x1, y1, f'{class_name}: {score:.2f}', bbox=dict(facecolor='yellow', alpha=0.5),
53
+ fontsize=12, color='black')
54
+
55
+ plt.axis('off')
56
+ plt.tight_layout()
57
+
58
+ # Save the figure to return
59
+ plt.savefig("output.png")
60
+ plt.close()
61
+ return "output.png"
62
+
63
+ # Create Gradio interface
64
+ gr.Interface(
65
+ fn=detect_objects,
66
+ inputs=[
67
+ gr.Image(type="pil"),
68
+ gr.Slider(0, 1, value=0.5, label="Confidence Threshold")
69
+ ],
70
+ outputs=gr.Image(type="filepath"),
71
+ title="Faster R-CNN Object Detection",
72
+ description="Upload an image to detect objects using a pretrained Faster R-CNN model."
73
+ ).launch()
74
+
requirement.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ gradio
4
+ matplotlib
5
+ pillow