1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
| import os import pathlib import tensorflow as tf import cv2 from os import listdir, path from os.path import isfile, join import warnings import time from object_detection.utils import label_map_util, config_util from object_detection.utils import visualization_utils as viz_utils import numpy as np from PIL import Image import matplotlib.pyplot as plt from object_detection.builders import model_builder
gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)
gpus = tf.config.experimental.list_physical_devices('GPU') if gpus: tf.config.experimental.set_virtual_device_configuration(gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024*2)])
def download_model(model_name, model_date): base_url = 'http://download.tensorflow.org/models/object_detection/tf2/' model_file = model_name + '.tar.gz' model_dir = tf.keras.utils.get_file(fname=model_name, origin=base_url + model_date + '/' + model_file, untar=True) return str(model_dir)
MODEL_DATE = '20200711' MODEL_NAME = 'centernet_hg104_1024x1024_coco17_tpu-32'
PATH_TO_MODEL_DIR = download_model(MODEL_NAME, MODEL_DATE) print(PATH_TO_MODEL_DIR)
for f in listdir(PATH_TO_MODEL_DIR): print(f)
warnings.filterwarnings('ignore')
PATH_TO_SAVED_MODEL = PATH_TO_MODEL_DIR + "/saved_model" print('载入模型...', end='') start_time = time.time()
detect_fn = tf.saved_model.load(PATH_TO_SAVED_MODEL) end_time = time.time() elapsed_time = end_time - start_time print(f'共花费 {elapsed_time} 秒.')
def download_labels(filename): base_url = 'https://raw.githubusercontent.com/tensorflow/models' base_url += '/master/research/object_detection/data/' label_dir = tf.keras.utils.get_file(fname=filename, origin=base_url + filename, untar=False) label_dir = pathlib.Path(label_dir) return str(label_dir)
LABEL_FILENAME = 'mscoco_label_map.pbtxt' PATH_TO_LABELS = download_labels(LABEL_FILENAME) print(PATH_TO_LABELS)
category_index = label_map_util.create_category_index_from_labelmap(PATH_TO_LABELS, use_display_name=True)
image_np = np.array(Image.open('./data/zebra.jpg'))
input_tensor = tf.convert_to_tensor(image_np)
input_tensor = input_tensor[tf.newaxis, ...]
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections')) print(f'检测到的物件个数:{num_detections}')
detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()} detections['num_detections'] = num_detections
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
print(f'物件资讯 (候选框, 类别, 机率):') for detection_boxes, detection_classes, detection_scores in \ zip(detections['detection_boxes'], detections['detection_classes'], detections['detection_scores']): print(np.around(detection_boxes, 4), detection_classes, round(detection_scores*100, 2))
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array( image_np_with_detections, detections['detection_boxes'], detections['detection_classes'], detections['detection_scores'], category_index, use_normalized_coordinates=True, max_boxes_to_draw=200, min_score_thresh=.30, agnostic_mode=False)
plt.figure(figsize=(12, 8)) plt.imshow(image_np_with_detections, cmap='viridis')
saved_file = './data/zebra._detection1.png' if os.path.isfile(saved_file): os.remove(saved_file) plt.savefig(saved_file)
PATH_TO_CFG = PATH_TO_MODEL_DIR + "/pipeline.config" PATH_TO_CKPT = PATH_TO_MODEL_DIR + "/checkpoint"
print('Loading model... ', end='') start_time = time.time()
configs = config_util.get_configs_from_pipeline_file(PATH_TO_CFG) model_config = configs['model'] detection_model = model_builder.build(model_config=model_config, is_training=False)
ckpt = tf.compat.v2.train.Checkpoint(model=detection_model)
ckpt.restore(os.path.join(PATH_TO_CKPT, 'ckpt-0')).expect_partial()
end_time = time.time() elapsed_time = end_time - start_time print(f'共花费 {elapsed_time} 秒.')
@tf.function def detect_fn(image): image, shapes = detection_model.preprocess(image) prediction_dict = detection_model.predict(image, shapes) detections = detection_model.postprocess(prediction_dict, shapes)
return detections
image_np = np.array(Image.open('./data/zebra.jpg'))
input_tensor = tf.convert_to_tensor(image_np, dtype=tf.float32)
input_tensor = input_tensor[tf.newaxis, ...]
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections')) print(f'物件个数:{num_detections}')
detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()}
print(f'物件资讯 (候选框, 类别, 机率):') for detection_boxes, detection_classes, detection_scores in \ zip(detections['detection_boxes'], detections['detection_classes'], detections['detection_scores']): print(np.around(detection_boxes, 4), int(detection_classes)+1, round(detection_scores*100, 2))
detections['num_detections'] = num_detections detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
image_np_with_detections = image_np.copy() viz_utils.visualize_boxes_and_labels_on_image_array( image_np_with_detections, detections['detection_boxes'], detections['detection_classes']+1, detections['detection_scores'], category_index, use_normalized_coordinates=True, max_boxes_to_draw=200, min_score_thresh=.30, agnostic_mode=False)
plt.figure(figsize=(12, 8)) plt.imshow(image_np_with_detections, cmap='viridis')
saved_file = './data/zebra._detection2.png' if os.path.isfile(saved_file): os.remove(saved_file) plt.savefig(saved_file)
|