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
|
import os import pathlib import tensorflow as tf import pathlib import time from object_detection.utils import label_map_util, config_util from object_detection.utils import visualization_utils as viz_utils from object_detection.builders import model_builder import numpy as np import cv2
gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True)
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)
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} 秒.')
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)
@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
cap = cv2.VideoCapture('./data/pedestrians.mp4') i = 0 while True: ret, image_np = cap.read()
image_np_expanded = np.expand_dims(image_np, axis=0)
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor) num_detections = int(detections.pop('num_detections'))
if i == 0: print(f'检测到的物件个数:{num_detections}')
detections = {key: value[0, :num_detections].numpy() for key, value in detections.items()} detections['detection_classes'] = detections['detection_classes'].astype(int)
label_id_offset = 1 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'] + label_id_offset, detections['detection_scores'], category_index, use_normalized_coordinates=True, max_boxes_to_draw=200, min_score_thresh=.60, agnostic_mode=False)
print("i = ", i) img = cv2.resize(image_np_with_detections, (800, 600)) cv2.imshow('object detection', img)
i += 1 if i == 30: cv2.imwrite('./data/pedestrians.png', img)
if cv2.waitKey(25) & 0xFF == ord('q'): break
cap.release() cv2.destroyAllWindows()
|