akhaliq HF Staff commited on
Commit
5d0818f
·
1 Parent(s): 8915112

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -48
app.py CHANGED
@@ -9,6 +9,10 @@ from matplotlib.colors import hsv_to_rgb
9
  import cv2
10
  import gradio as gr
11
 
 
 
 
 
12
 
13
  def preprocess(image):
14
  # Resize
@@ -51,61 +55,67 @@ outputs = sess.get_outputs()
51
 
52
 
53
  classes = [line.rstrip('\n') for line in open('coco_classes.txt')]
54
- num_classes = len(classes)
55
-
56
- def get_palette():
57
- # prepare and return palette
58
- palette = [0] * num_classes * 3
59
-
60
- for hue in range(num_classes):
61
- if hue == 0: # Background color
62
- colors = (0, 0, 0)
63
- else:
64
- colors = hsv_to_rgb((hue / num_classes, 0.75, 0.75))
65
-
66
- for i in range(3):
67
- palette[hue * 3 + i] = int(colors[i] * 255)
68
-
69
- return palette
70
-
71
- def colorize(labels):
72
- # generate colorized image from output labels and color palette
73
- result_img = Image.fromarray(labels).convert('P', colors=num_classes)
74
- result_img.putpalette(get_palette())
75
- return np.array(result_img.convert('RGB'))
76
-
77
- def visualize_output(image, output):
78
- assert(image.shape[0] == output.shape[1] and \
79
- image.shape[1] == output.shape[2]) # Same height and width
80
- assert(output.shape[0] == num_classes)
81
-
82
- # get classification labels
83
- raw_labels = np.argmax(output, axis=0).astype(np.uint8)
84
-
85
- # comput confidence score
86
- confidence = float(np.max(output, axis=0).mean())
87
-
88
- # generate segmented image
89
- result_img = colorize(raw_labels)
90
-
91
- # generate blended image
92
- blended_img = cv2.addWeighted(image[:, :, ::-1], 0.5, result_img, 0.5, 0)
93
-
94
- result_img = Image.fromarray(result_img)
95
- blended_img = Image.fromarray(blended_img)
96
-
97
- return confidence, result_img, blended_img, raw_labels
 
 
 
 
 
98
 
99
  def inference(img):
100
  input_image = Image.open(img)
101
  orig_tensor = np.asarray(input_image)
102
  input_tensor = preprocess(input_image)
 
103
  output_names = list(map(lambda output: output.name, outputs))
104
  input_name = sess.get_inputs()[0].name
105
- detections = sess.run(output_names, {input_name: input_tensor})
106
- output, aux = detections
107
- conf, result_img, blended_img, _ = visualize_output(orig_tensor, output[0])
108
- return blended_img
109
 
110
  title="Mask R-CNN"
111
  description="This model is a real-time neural network for object instance segmentation that detects 80 different classes."
 
9
  import cv2
10
  import gradio as gr
11
 
12
+ import matplotlib.pyplot as plt
13
+ import matplotlib.patches as patches
14
+
15
+ import pycocotools.mask as mask_util
16
 
17
  def preprocess(image):
18
  # Resize
 
55
 
56
 
57
  classes = [line.rstrip('\n') for line in open('coco_classes.txt')]
58
+
59
+
60
+ def display_objdetect_image(image, boxes, labels, scores, masks, score_threshold=0.7):
61
+ # Resize boxes
62
+ ratio = 800.0 / min(image.size[0], image.size[1])
63
+ boxes /= ratio
64
+
65
+ _, ax = plt.subplots(1, figsize=(12,9))
66
+
67
+ image = np.array(image)
68
+
69
+ for mask, box, label, score in zip(masks, boxes, labels, scores):
70
+ # Showing boxes with score > 0.7
71
+ if score <= score_threshold:
72
+ continue
73
+
74
+ # Finding contour based on mask
75
+ mask = mask[0, :, :, None]
76
+ int_box = [int(i) for i in box]
77
+ mask = cv2.resize(mask, (int_box[2]-int_box[0]+1, int_box[3]-int_box[1]+1))
78
+ mask = mask > 0.5
79
+ im_mask = np.zeros((image.shape[0], image.shape[1]), dtype=np.uint8)
80
+ x_0 = max(int_box[0], 0)
81
+ x_1 = min(int_box[2] + 1, image.shape[1])
82
+ y_0 = max(int_box[1], 0)
83
+ y_1 = min(int_box[3] + 1, image.shape[0])
84
+ mask_y_0 = max(y_0 - box[1], 0)
85
+ mask_y_1 = mask_y_0 + y_1 - y_0
86
+ mask_x_0 = max(x_0 - box[0], 0)
87
+ mask_x_1 = mask_x_0 + x_1 - x_0
88
+ im_mask[y_0:y_1, x_0:x_1] = mask[
89
+ mask_y_0 : mask_y_1, mask_x_0 : mask_x_1
90
+ ]
91
+ im_mask = im_mask[:, :, None]
92
+
93
+ # OpenCV version 4.x
94
+ contours, hierarchy = cv2.findContours(
95
+ im_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
96
+ )
97
+
98
+ image = cv2.drawContours(image, contours, -1, 25, 3)
99
+
100
+ rect = patches.Rectangle((box[0], box[1]), box[2] - box[0], box[3] - box[1], linewidth=1, edgecolor='b', facecolor='none')
101
+ ax.annotate(classes[label] + ':' + str(np.round(score, 2)), (box[0], box[1]), color='w', fontsize=12)
102
+ ax.add_patch(rect)
103
+
104
+ ax.imshow(image)
105
+ plt.savefig('out.png', bbox_inches='tight')
106
+
107
 
108
  def inference(img):
109
  input_image = Image.open(img)
110
  orig_tensor = np.asarray(input_image)
111
  input_tensor = preprocess(input_image)
112
+
113
  output_names = list(map(lambda output: output.name, outputs))
114
  input_name = sess.get_inputs()[0].name
115
+
116
+ boxes, labels, scores, masks = sess.run(output_names, {input_name: input_tensor})
117
+ display_objdetect_image(input_image, boxes, labels, scores, masks)
118
+ return 'out.png'
119
 
120
  title="Mask R-CNN"
121
  description="This model is a real-time neural network for object instance segmentation that detects 80 different classes."