bacngv commited on
Commit
48e5d61
·
verified ·
1 Parent(s): 8f49b26

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -84
app.py CHANGED
@@ -1,19 +1,19 @@
1
  import gradio as gr
2
- import cv2
3
  import torch
4
- from torchvision.models.detection import fasterrcnn_resnet50_fpn
5
- import numpy as np
 
6
  import torchvision.transforms.functional as F
 
7
  import albumentations as A
8
  from albumentations.pytorch import ToTensorV2
9
- import matplotlib.pyplot as plt
10
-
11
- # Define class names and color mapping
12
- CLASS_NAMES = ['bone-fracture', 'angle', 'fracture', 'line', 'messed_up_angle']
13
 
14
- def map_label_to_class(label_id):
15
- return CLASS_NAMES[label_id - 1]
 
16
 
 
 
17
  COLOR_MAP = {
18
  'bone-fracture': (255, 0, 0),
19
  'angle': (0, 255, 0),
@@ -22,96 +22,75 @@ COLOR_MAP = {
22
  'messed_up_angle': (255, 165, 0)
23
  }
24
 
25
- def draw_boxes_with_labels(image, boxes, labels):
26
- # Convert the image from tensor to numpy
27
- image_np = image.permute(1, 2, 0).numpy() * 255
28
- image_np = image_np.astype(np.uint8)
29
 
30
- # Plot the image
31
- plt.figure(figsize=(10, 10))
32
- plt.imshow(image_np)
33
 
34
- # Draw bounding boxes and labels
35
  for box, label in zip(boxes, labels):
36
- x1, y1, x2, y2 = box.int().tolist()
37
  color = COLOR_MAP[label]
 
 
 
 
 
38
 
39
- # Draw rectangle
40
- plt.gca().add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, linewidth=2, edgecolor=color, facecolor='none'))
41
-
42
- # Draw label
43
- plt.text(x1, y1, label, color='white', fontsize=12, bbox=dict(facecolor=color, alpha=0.5))
44
-
45
- plt.axis('off')
46
- plt.close() # Prevents the figure from showing in an interactive mode
47
- return image_np # Return the image as a numpy array
48
 
49
- def get_transforms(train):
50
  if train:
51
- return A.Compose([
52
- A.HorizontalFlip(p=0.5),
53
- A.RandomBrightnessContrast(p=0.2),
54
- A.Resize(height=800, width=800),
55
- ToTensorV2(),
56
- ])
 
 
57
  else:
58
- return A.Compose([
59
- A.Resize(height=800, width=800),
60
- ToTensorV2(),
61
- ])
62
-
63
- def predict_image(image, model, device, transform, threshold=0.1):
64
- image = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
 
 
 
 
 
65
  transformed = transform(image=image)
66
- image_tensor = transformed['image'].to(device)
67
  image_tensor = image_tensor.float() / 255.0
68
 
69
- model.eval()
70
  with torch.no_grad():
71
- prediction = model([image_tensor])
72
- pred = prediction[0]
73
-
74
- boxes = pred['boxes'][pred['scores'] > threshold]
75
- labels = pred['labels'][pred['scores'] > threshold]
76
-
77
- # Convert the image to uint8 format for drawing
78
- image_uint8 = (image_tensor * 255).byte().cpu()
79
-
80
- # Map labels to class names
81
  label_names = [map_label_to_class(label.item()) for label in labels]
82
 
83
- # Draw bounding boxes with labels
 
 
 
84
  drawn_image = draw_boxes_with_labels(image_uint8, boxes.cpu(), label_names)
85
- return drawn_image # Return the modified image
86
- # Tải mô hình
87
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
88
- model = fasterrcnn_resnet50_fpn(pretrained=False)
89
-
90
- pretrained_dict = torch.load('faster-rcnn.pth', map_location=torch.device('cpu'))
91
- model_dict = model.state_dict()
92
- # Lọc các khóa không cần thiết
93
- pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
94
- # Ghi đè các mục trong state_dict hiện có
95
- model_dict.update(pretrained_dict)
96
- # Tải state_dict mới
97
- model.load_state_dict(model_dict)
98
- model.to(device).eval()
99
 
100
- # Define Gradio interface function
101
- def process_image(input_image):
102
- transform = get_transforms(train=False)
103
- output_image = predict_image(input_image, model, device, transform)
104
  return output_image
105
 
106
- # Create Gradio interface
107
- iface = gr.Interface(
108
- fn=process_image,
109
- inputs=gr.Image(type="numpy"),
110
- outputs=gr.Image(type="numpy"),
111
- title="Object Detection with Faster R-CNN",
112
- description="Upload an image to detect objects."
113
- )
114
-
115
- # Run the application
116
- if __name__ == "__main__":
117
- iface.launch(share=True) # To create a public link
 
1
  import gradio as gr
 
2
  import torch
3
+ from torchvision.utils import draw_bounding_boxes
4
+ import matplotlib.pyplot as plt
5
+ from PIL import Image, ImageDraw
6
  import torchvision.transforms.functional as F
7
+ import cv2
8
  import albumentations as A
9
  from albumentations.pytorch import ToTensorV2
 
 
 
 
10
 
11
+ # Load your trained model
12
+ model = torch.load("faster_rcnn.pth", map_location=torch.device('cpu'))
13
+ model.eval()
14
 
15
+ # Define class names and color map
16
+ CLASS_NAMES = ['bone-fracture', 'angle', 'fracture', 'line', 'messed_up_angle']
17
  COLOR_MAP = {
18
  'bone-fracture': (255, 0, 0),
19
  'angle': (0, 255, 0),
 
22
  'messed_up_angle': (255, 165, 0)
23
  }
24
 
25
+ def map_label_to_class(label_id):
26
+ return CLASS_NAMES[label_id - 1]
 
 
27
 
28
+ def draw_boxes_with_labels(image, boxes, labels):
29
+ pil_image = F.to_pil_image(image)
30
+ draw = ImageDraw.Draw(pil_image)
31
 
 
32
  for box, label in zip(boxes, labels):
33
+ x1, y1, x2, y2 = box
34
  color = COLOR_MAP[label]
35
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=4)
36
+ text_position = (x1, y1 - 10)
37
+ text_bbox = draw.textbbox(text_position, label)
38
+ draw.rectangle(text_bbox, fill=color)
39
+ draw.text(text_position, label, fill="white")
40
 
41
+ return F.to_tensor(pil_image)
 
 
 
 
 
 
 
 
42
 
43
+ def get_transforms(train=False):
44
  if train:
45
+ transform = A.Compose([
46
+ A.Resize(800, 800),
47
+ A.HorizontalFlip(p=0.3),
48
+ A.VerticalFlip(p=0.3),
49
+ A.RandomBrightnessContrast(p=0.1),
50
+ A.ColorJitter(p=0.1),
51
+ ToTensorV2()
52
+ ], bbox_params=A.BboxParams(format='coco'))
53
  else:
54
+ transform = A.Compose([
55
+ A.Resize(800, 800),
56
+ ToTensorV2()
57
+ ], bbox_params=A.BboxParams(format='coco'))
58
+ return transform
59
+
60
+ def predict_image(image):
61
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
62
+
63
+ # Preprocess the input image
64
+ image = np.array(image)
65
+ transform = get_transforms(train=False)
66
  transformed = transform(image=image)
67
+ image_tensor = transformed['image'].unsqueeze(0).to(device)
68
  image_tensor = image_tensor.float() / 255.0
69
 
70
+ # Predict using the model
71
  with torch.no_grad():
72
+ prediction = model(image_tensor)
73
+
74
+ # Extract predictions (boxes, labels, scores)
75
+ pred = prediction[0]
76
+ boxes = pred['boxes'][pred['scores'] > 0.5]
77
+ labels = pred['labels'][pred['scores'] > 0.5]
78
+ scores = pred['scores'][pred['scores'] > 0.5]
79
+
80
+ # Convert labels to class names
 
81
  label_names = [map_label_to_class(label.item()) for label in labels]
82
 
83
+ # Convert image to uint8 for visualization
84
+ image_uint8 = (image_tensor.squeeze(0) * 255).byte().cpu()
85
+
86
+ # Draw the boxes and labels on the image
87
  drawn_image = draw_boxes_with_labels(image_uint8, boxes.cpu(), label_names)
88
+
89
+ return F.to_pil_image(drawn_image)
 
 
 
 
 
 
 
 
 
 
 
 
90
 
91
+ # Define the Gradio interface
92
+ def predict(img):
93
+ output_image = predict_image(img)
 
94
  return output_image
95
 
96
+ gr.Interface(fn=predict, inputs=gr.Image(type="pil"), outputs=gr.Image()).launch()