|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | + |
| 3 | +import os |
| 4 | +import sys |
| 5 | +import numpy as np |
| 6 | +import skimage |
| 7 | +import onnx |
| 8 | +import mock_keras2onnx |
| 9 | + |
| 10 | +from mrcnn.config import Config |
| 11 | +from mrcnn.model import BatchNorm, DetectionLayer |
| 12 | +from mrcnn import model as modellib |
| 13 | +from mrcnn import visualize |
| 14 | + |
| 15 | +from mock_keras2onnx import set_converter |
| 16 | +from mock_keras2onnx.ke2onnx.batch_norm import convert_keras_batch_normalization |
| 17 | +from os.path import dirname, abspath |
| 18 | +sys.path.insert(0, os.path.join(dirname(abspath(__file__)), '../../keras2onnx_tests/')) |
| 19 | +from test_utils import convert_tf_crop_and_resize |
| 20 | + |
| 21 | + |
| 22 | +ROOT_DIR = os.path.abspath("./") |
| 23 | + |
| 24 | +# Directory to save logs and trained model |
| 25 | +MODEL_DIR = os.path.join(ROOT_DIR, "logs") |
| 26 | + |
| 27 | +# Path to trained weights file |
| 28 | +COCO_MODEL_PATH = os.path.join(ROOT_DIR, "mask_rcnn_coco.h5") |
| 29 | + |
| 30 | + |
| 31 | +class CocoConfig(Config): |
| 32 | + """Configuration for training on MS COCO. |
| 33 | + Derives from the base Config class and overrides values specific |
| 34 | + to the COCO dataset. |
| 35 | + """ |
| 36 | + # Give the configuration a recognizable name |
| 37 | + NAME = "coco" |
| 38 | + |
| 39 | + # We use a GPU with 12GB memory, which can fit two images. |
| 40 | + # Adjust down if you use a smaller GPU. |
| 41 | + IMAGES_PER_GPU = 2 |
| 42 | + |
| 43 | + # Uncomment to train on 8 GPUs (default is 1) |
| 44 | + # GPU_COUNT = 8 |
| 45 | + |
| 46 | + # Number of classes (including background) |
| 47 | + NUM_CLASSES = 1 + 80 # COCO has 80 classes |
| 48 | + |
| 49 | + |
| 50 | +class InferenceConfig(CocoConfig): |
| 51 | + # Set batch size to 1 since we'll be running inference on |
| 52 | + # one image at a time. Batch size = GPU_COUNT * IMAGES_PER_GPU |
| 53 | + GPU_COUNT = 1 |
| 54 | + IMAGES_PER_GPU = 1 |
| 55 | + |
| 56 | + |
| 57 | +config = InferenceConfig() |
| 58 | +config.display() |
| 59 | + |
| 60 | +model = modellib.MaskRCNN(mode="inference", model_dir=MODEL_DIR, config=config) |
| 61 | + |
| 62 | +# Load weights trained on MS-COCO |
| 63 | +model.load_weights(COCO_MODEL_PATH, by_name=True) |
| 64 | + |
| 65 | + |
| 66 | +def convert_BatchNorm(scope, operator, container): |
| 67 | + convert_keras_batch_normalization(scope, operator, container) |
| 68 | + |
| 69 | + |
| 70 | +def norm_boxes_graph(scope, operator, container, oopb, image_meta): |
| 71 | + image_shapes = oopb.add_node('Slice', |
| 72 | + [image_meta, |
| 73 | + ('_start', oopb.int64, np.array([4], dtype='int64')), |
| 74 | + ('_end', oopb.int64, np.array([7], dtype='int64')), |
| 75 | + ('_axes', oopb.int64, np.array([1], dtype='int64')) |
| 76 | + ], |
| 77 | + operator.inputs[0].full_name + '_image_shapes') |
| 78 | + image_shape = oopb.add_node('Slice', |
| 79 | + [image_shapes, |
| 80 | + ('_start', oopb.int64, np.array([0], dtype='int64')), |
| 81 | + ('_end', oopb.int64, np.array([1], dtype='int64')), |
| 82 | + ('_axes', oopb.int64, np.array([0], dtype='int64')) |
| 83 | + ], |
| 84 | + operator.inputs[0].full_name + '_image_shape') |
| 85 | + image_shape_squeeze = oopb.apply_squeeze(image_shape, name=operator.full_name + '_image_shape_squeeze', axes=[0])[0] |
| 86 | + |
| 87 | + window = oopb.add_node('Slice', |
| 88 | + [image_meta, |
| 89 | + ('_start', oopb.int64, np.array([7], dtype='int64')), |
| 90 | + ('_end', oopb.int64, np.array([11], dtype='int64')), |
| 91 | + ('_axes', oopb.int64, np.array([1], dtype='int64')) |
| 92 | + ], |
| 93 | + operator.inputs[0].full_name + '_window') |
| 94 | + h_norm = oopb.add_node('Slice', |
| 95 | + [image_shape_squeeze, |
| 96 | + ('_start', oopb.int64, np.array([0], dtype='int64')), |
| 97 | + ('_end', oopb.int64, np.array([1], dtype='int64')), |
| 98 | + ('_axes', oopb.int64, np.array([0], dtype='int64')) |
| 99 | + ], |
| 100 | + operator.inputs[0].full_name + '_h_norm') |
| 101 | + w_norm = oopb.add_node('Slice', |
| 102 | + [image_shape_squeeze, |
| 103 | + ('_start', oopb.int64, np.array([1], dtype='int64')), |
| 104 | + ('_end', oopb.int64, np.array([2], dtype='int64')), |
| 105 | + ('_axes', oopb.int64, np.array([0], dtype='int64')) |
| 106 | + ], |
| 107 | + operator.inputs[0].full_name + '_w_norm') |
| 108 | + h_norm_float = scope.get_unique_variable_name('h_norm_float') |
| 109 | + attrs = {'to': 1} |
| 110 | + container.add_node('Cast', h_norm, h_norm_float, op_version=operator.target_opset, |
| 111 | + **attrs) |
| 112 | + w_norm_float = scope.get_unique_variable_name('w_norm_float') |
| 113 | + attrs = {'to': 1} |
| 114 | + container.add_node('Cast', w_norm, w_norm_float, op_version=operator.target_opset, |
| 115 | + **attrs) |
| 116 | + hw_concat = scope.get_unique_variable_name(operator.inputs[0].full_name + '_hw_concat') |
| 117 | + attrs = {'axis': -1} |
| 118 | + container.add_node("Concat", |
| 119 | + [h_norm_float, w_norm_float, h_norm_float, w_norm_float], |
| 120 | + hw_concat, |
| 121 | + op_version=operator.target_opset, |
| 122 | + name=operator.inputs[0].full_name + '_hw_concat', **attrs) |
| 123 | + scale = oopb.add_node('Sub', |
| 124 | + [hw_concat, |
| 125 | + ('_sub', oopb.float, np.array([1.0], dtype='float32')) |
| 126 | + ], |
| 127 | + operator.inputs[0].full_name + '_scale') |
| 128 | + boxes_shift = oopb.add_node('Sub', |
| 129 | + [window, |
| 130 | + ('_sub', oopb.float, np.array([0.0, 0.0, 1.0, 1.0], dtype='float32')) |
| 131 | + ], |
| 132 | + operator.inputs[0].full_name + '_boxes_shift') |
| 133 | + divide = oopb.add_node('Div', |
| 134 | + [boxes_shift, scale], |
| 135 | + operator.inputs[0].full_name + '_divide') |
| 136 | + # output shape: [batch, 4] |
| 137 | + return divide |
| 138 | + |
| 139 | + |
| 140 | +def convert_DetectionLayer(scope, operator, container): |
| 141 | + # type: (mock_keras2onnx.common.InterimContext, mock_keras2onnx.common.Operator, mock_keras2onnx.common.OnnxObjectContainer) -> None |
| 142 | + pass |
| 143 | + |
| 144 | + |
| 145 | +set_converter(DetectionLayer, convert_DetectionLayer) |
| 146 | +set_converter(BatchNorm, convert_BatchNorm) |
| 147 | + |
| 148 | + |
| 149 | +# Run detection |
| 150 | +class_names = ['BG', 'person', 'bicycle', 'car', 'motorcycle', 'airplane', |
| 151 | + 'bus', 'train', 'truck', 'boat', 'traffic light', |
| 152 | + 'fire hydrant', 'stop sign', 'parking meter', 'bench', 'bird', |
| 153 | + 'cat', 'dog', 'horse', 'sheep', 'cow', 'elephant', 'bear', |
| 154 | + 'zebra', 'giraffe', 'backpack', 'umbrella', 'handbag', 'tie', |
| 155 | + 'suitcase', 'frisbee', 'skis', 'snowboard', 'sports ball', |
| 156 | + 'kite', 'baseball bat', 'baseball glove', 'skateboard', |
| 157 | + 'surfboard', 'tennis racket', 'bottle', 'wine glass', 'cup', |
| 158 | + 'fork', 'knife', 'spoon', 'bowl', 'banana', 'apple', |
| 159 | + 'sandwich', 'orange', 'broccoli', 'carrot', 'hot dog', 'pizza', |
| 160 | + 'donut', 'cake', 'chair', 'couch', 'potted plant', 'bed', |
| 161 | + 'dining table', 'toilet', 'tv', 'laptop', 'mouse', 'remote', |
| 162 | + 'keyboard', 'cell phone', 'microwave', 'oven', 'toaster', |
| 163 | + 'sink', 'refrigerator', 'book', 'clock', 'vase', 'scissors', |
| 164 | + 'teddy bear', 'hair drier', 'toothbrush'] |
| 165 | + |
| 166 | + |
| 167 | +def generate_image(images, molded_images, windows, results): |
| 168 | + results_final = [] |
| 169 | + for i, image in enumerate(images): |
| 170 | + final_rois, final_class_ids, final_scores, final_masks = \ |
| 171 | + model.unmold_detections(results[0][i], results[3][i], # detections[i], mrcnn_mask[i] |
| 172 | + image.shape, molded_images[i].shape, |
| 173 | + windows[i]) |
| 174 | + results_final.append({ |
| 175 | + "rois": final_rois, |
| 176 | + "class_ids": final_class_ids, |
| 177 | + "scores": final_scores, |
| 178 | + "masks": final_masks, |
| 179 | + }) |
| 180 | + r = results_final[i] |
| 181 | + visualize.display_instances(image, r['rois'], r['masks'], r['class_ids'], |
| 182 | + class_names, r['scores']) |
| 183 | + return results_final |
| 184 | + |
| 185 | + |
| 186 | +if __name__ == '__main__': |
| 187 | + if len(sys.argv) < 2: |
| 188 | + print("Need an image file for object detection.") |
| 189 | + exit(-1) |
| 190 | + |
| 191 | + model_file_name = './mrcnn.onnx' |
| 192 | + if not os.path.exists(model_file_name): |
| 193 | + # use opset 11 or later |
| 194 | + set_converter('CropAndResize', convert_tf_crop_and_resize) |
| 195 | + oml = mock_keras2onnx.convert_keras(model.keras_model, target_opset=11) |
| 196 | + onnx.save_model(oml, model_file_name) |
| 197 | + |
| 198 | + # run with ONNXRuntime |
| 199 | + import onnxruntime |
| 200 | + filename = sys.argv[1] |
| 201 | + image = skimage.io.imread(filename) |
| 202 | + images = [image] |
| 203 | + |
| 204 | + sess = onnxruntime.InferenceSession(model_file_name) |
| 205 | + |
| 206 | + # preprocessing |
| 207 | + molded_images, image_metas, windows = model.mold_inputs(images) |
| 208 | + anchors = model.get_anchors(molded_images[0].shape) |
| 209 | + anchors = np.broadcast_to(anchors, (model.config.BATCH_SIZE,) + anchors.shape) |
| 210 | + |
| 211 | + results = \ |
| 212 | + sess.run(None, {"input_image": molded_images.astype(np.float32), |
| 213 | + "input_anchors": anchors, |
| 214 | + "input_image_meta": image_metas.astype(np.float32)}) |
| 215 | + |
| 216 | + # postprocessing |
| 217 | + results_final = generate_image(images, molded_images, windows, results) |
0 commit comments