|
| 1 | +import tensorflow as tf |
| 2 | +import numpy as np |
| 3 | +import cv2 |
| 4 | + |
| 5 | +#https://colab.research.google.com/github/tensorflow/tpu/blob/master/models/official/mask_rcnn/mask_rcnn_demo.ipynb#scrollTo=2oZWLz4xXsyQ |
| 6 | + |
| 7 | +class_mappings = {1: 'person', 3 : 'car', 28: 'umbrella', 31: 'handbag'} |
| 8 | +session = tf.compat.v1.Session() |
| 9 | + |
| 10 | +def load_model(): |
| 11 | + saved_model_dir = 'gs://cloud-tpu-checkpoints/mask-rcnn/1555659850' |
| 12 | + _ = tf.compat.v1.saved_model.loader.load(session, ['serve'], saved_model_dir) |
| 13 | + |
| 14 | + |
| 15 | +def predict(np_image_string, min_score, height, width): |
| 16 | + num_detections, detection_boxes, detection_classes, detection_scores, detection_masks, image_info = session.run( |
| 17 | + ['NumDetections:0', 'DetectionBoxes:0', 'DetectionClasses:0', 'DetectionScores:0', 'DetectionMasks:0', 'ImageInfo:0'], |
| 18 | + feed_dict={'Placeholder:0': np_image_string}) |
| 19 | + num_detections = np.squeeze(num_detections.astype(np.int32), axis=(0,)) |
| 20 | + detection_scores = np.squeeze(detection_scores, axis=(0,))[0:num_detections] |
| 21 | + response = { |
| 22 | + 'boxes' : np.squeeze(detection_boxes * image_info[0, 2], axis=(0,))[0:num_detections], |
| 23 | + 'class_indices' : np.squeeze(detection_classes.astype(np.int32), axis=(0,))[0:num_detections], |
| 24 | + } |
| 25 | + ymin, xmin, ymax, xmax = np.split(response['boxes'], 4, axis=-1) |
| 26 | + instance_masks = np.squeeze(detection_masks, axis=(0,))[0:num_detections] |
| 27 | + processed_boxes = np.concatenate([xmin, ymin, xmax - xmin, ymax - ymin], axis=-1) |
| 28 | + response.update({'seg_masks' : generate_segmentation_from_masks(instance_masks, processed_boxes, height, width)}) |
| 29 | + keep_indices = detection_scores > min_score |
| 30 | + keep_indices = keep_indices & np.isin(response['class_indices'], list(class_mappings.keys())) |
| 31 | + for key in response: |
| 32 | + response[key] = response[key][keep_indices] |
| 33 | + return response |
| 34 | + |
| 35 | + |
| 36 | +def expand_boxes(boxes, scale): |
| 37 | + """Expands an array of boxes by a given scale.""" |
| 38 | + # Reference: https://github.com/facebookresearch/Detectron/blob/master/detectron/utils/boxes.py#L227 # pylint: disable=line-too-long |
| 39 | + # The `boxes` in the reference implementation is in [x1, y1, x2, y2] form, |
| 40 | + # whereas `boxes` here is in [x1, y1, w, h] form |
| 41 | + w_half = boxes[:, 2] * .5 |
| 42 | + h_half = boxes[:, 3] * .5 |
| 43 | + x_c = boxes[:, 0] + w_half |
| 44 | + y_c = boxes[:, 1] + h_half |
| 45 | + |
| 46 | + w_half *= scale |
| 47 | + h_half *= scale |
| 48 | + |
| 49 | + boxes_exp = np.zeros(boxes.shape) |
| 50 | + boxes_exp[:, 0] = x_c - w_half |
| 51 | + boxes_exp[:, 2] = x_c + w_half |
| 52 | + boxes_exp[:, 1] = y_c - h_half |
| 53 | + boxes_exp[:, 3] = y_c + h_half |
| 54 | + |
| 55 | + return boxes_exp |
| 56 | + |
| 57 | +def generate_segmentation_from_masks(masks, |
| 58 | + detected_boxes, |
| 59 | + image_height, |
| 60 | + image_width, |
| 61 | + is_image_mask=False): |
| 62 | + """Generates segmentation result from instance masks. |
| 63 | + Args: |
| 64 | + masks: a numpy array of shape [N, mask_height, mask_width] representing the |
| 65 | + instance masks w.r.t. the `detected_boxes`. |
| 66 | + detected_boxes: a numpy array of shape [N, 4] representing the reference |
| 67 | + bounding boxes. |
| 68 | + image_height: an integer representing the height of the image. |
| 69 | + image_width: an integer representing the width of the image. |
| 70 | + is_image_mask: bool. True: input masks are whole-image masks. False: input |
| 71 | + masks are bounding-box level masks. |
| 72 | + Returns: |
| 73 | + segms: a numpy array of shape [N, image_height, image_width] representing |
| 74 | + the instance masks *pasted* on the image canvas. |
| 75 | + """ |
| 76 | + |
| 77 | + |
| 78 | + _, mask_height, mask_width = masks.shape |
| 79 | + scale = max((mask_width + 2.0) / mask_width, |
| 80 | + (mask_height + 2.0) / mask_height) |
| 81 | + |
| 82 | + ref_boxes = expand_boxes(detected_boxes, scale) |
| 83 | + ref_boxes = ref_boxes.astype(np.int32) |
| 84 | + padded_mask = np.zeros((mask_height + 2, mask_width + 2), dtype=np.float32) |
| 85 | + segms = [] |
| 86 | + for mask_ind, mask in enumerate(masks): |
| 87 | + im_mask = np.zeros((image_height, image_width), dtype=np.uint8) |
| 88 | + if is_image_mask: |
| 89 | + # Process whole-image masks. |
| 90 | + im_mask[:, :] = mask[:, :] |
| 91 | + else: |
| 92 | + # Process mask inside bounding boxes. |
| 93 | + padded_mask[1:-1, 1:-1] = mask[:, :] |
| 94 | + |
| 95 | + ref_box = ref_boxes[mask_ind, :] |
| 96 | + w = ref_box[2] - ref_box[0] + 1 |
| 97 | + h = ref_box[3] - ref_box[1] + 1 |
| 98 | + w = np.maximum(w, 1) |
| 99 | + h = np.maximum(h, 1) |
| 100 | + |
| 101 | + mask = cv2.resize(padded_mask, (w, h)) |
| 102 | + mask = np.array(mask > 0.5, dtype=np.uint8) |
| 103 | + |
| 104 | + x_0 = max(ref_box[0], 0) |
| 105 | + x_1 = min(ref_box[2] + 1, image_width) |
| 106 | + y_0 = max(ref_box[1], 0) |
| 107 | + y_1 = min(ref_box[3] + 1, image_height) |
| 108 | + |
| 109 | + im_mask[y_0:y_1, x_0:x_1] = mask[(y_0 - ref_box[1]):(y_1 - ref_box[1]), ( |
| 110 | + x_0 - ref_box[0]):(x_1 - ref_box[0])] |
| 111 | + segms.append(im_mask) |
| 112 | + |
| 113 | + segms = np.array(segms) |
| 114 | + assert masks.shape[0] == segms.shape[0] |
| 115 | + return segms |
| 116 | + |
| 117 | + |
| 118 | + |
| 119 | + |
| 120 | + |
0 commit comments