mot_jde_infer.py 13.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import time
import yaml
import cv2
import numpy as np
20
from collections import defaultdict
21

22
import paddle
23 24
from paddle.inference import Config
from paddle.inference import create_predictor
25

26
from utils import argsparser, Timer, get_current_memory_mb
27
from infer import Detector, get_test_images, print_arguments, PredictConfig
28 29 30 31 32
from benchmark_utils import PaddleInferBenchmark

from ppdet.modeling.mot.tracker import JDETracker
from ppdet.modeling.mot.visualization import plot_tracking_dict
from ppdet.modeling.mot.utils import MOTTimer, write_mot_results
33 34 35 36 37 38 39 40

# Global dictionary
MOT_SUPPORT_MODELS = {
    'JDE',
    'FairMOT',
}


41
class JDE_Detector(Detector):
42 43 44 45
    """
    Args:
        pred_config (object): config of model, defined by `Config(model_dir)`
        model_dir (str): root path of model.pdiparams, model.pdmodel and infer_cfg.yml
46
        device (str): Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU
47
        run_mode (str): mode of running(paddle/trt_fp32/trt_fp16)
48
        batch_size (int): size of pre batch in inference
49 50 51 52 53 54 55 56 57 58 59 60
        trt_min_shape (int): min shape for dynamic shape in trt
        trt_max_shape (int): max shape for dynamic shape in trt
        trt_opt_shape (int): opt shape for dynamic shape in trt
        trt_calib_mode (bool): If the model is produced by TRT offline quantitative
            calibration, trt_calib_mode need to set True
        cpu_threads (int): cpu threads
        enable_mkldnn (bool): whether to open MKLDNN 
    """

    def __init__(self,
                 pred_config,
                 model_dir,
61
                 device='CPU',
62
                 run_mode='paddle',
63
                 batch_size=1,
64 65 66 67 68 69
                 trt_min_shape=1,
                 trt_max_shape=1088,
                 trt_opt_shape=608,
                 trt_calib_mode=False,
                 cpu_threads=1,
                 enable_mkldnn=False):
70 71 72
        super(JDE_Detector, self).__init__(
            pred_config=pred_config,
            model_dir=model_dir,
73
            device=device,
74 75
            run_mode=run_mode,
            batch_size=batch_size,
76 77 78 79 80 81
            trt_min_shape=trt_min_shape,
            trt_max_shape=trt_max_shape,
            trt_opt_shape=trt_opt_shape,
            trt_calib_mode=trt_calib_mode,
            cpu_threads=cpu_threads,
            enable_mkldnn=enable_mkldnn)
82
        assert batch_size == 1, "The JDE Detector only supports batch size=1 now"
83
        assert pred_config.tracker, "Tracking model should have tracker"
84 85
        self.num_classes = len(pred_config.labels)

86
        tp = pred_config.tracker
F
Feng Ni 已提交
87 88
        min_box_area = tp['min_box_area'] if 'min_box_area' in tp else 200
        vertical_ratio = tp['vertical_ratio'] if 'vertical_ratio' in tp else 1.6
89 90 91
        conf_thres = tp['conf_thres'] if 'conf_thres' in tp else 0.
        tracked_thresh = tp['tracked_thresh'] if 'tracked_thresh' in tp else 0.7
        metric_type = tp['metric_type'] if 'metric_type' in tp else 'euclidean'
92

G
George Ni 已提交
93
        self.tracker = JDETracker(
94
            num_classes=self.num_classes,
F
Feng Ni 已提交
95 96
            min_box_area=min_box_area,
            vertical_ratio=vertical_ratio,
G
George Ni 已提交
97 98 99
            conf_thres=conf_thres,
            tracked_thresh=tracked_thresh,
            metric_type=metric_type)
100

101
    def postprocess(self, pred_dets, pred_embs, threshold):
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
        online_targets_dict = self.tracker.update(pred_dets, pred_embs)

        online_tlwhs = defaultdict(list)
        online_scores = defaultdict(list)
        online_ids = defaultdict(list)
        for cls_id in range(self.num_classes):
            online_targets = online_targets_dict[cls_id]
            for t in online_targets:
                tlwh = t.tlwh
                tid = t.track_id
                tscore = t.score
                if tscore < threshold: continue
                if tlwh[2] * tlwh[3] <= self.tracker.min_box_area: continue
                if self.tracker.vertical_ratio > 0 and tlwh[2] / tlwh[
                        3] > self.tracker.vertical_ratio:
                    continue
                online_tlwhs[cls_id].append(tlwh)
                online_ids[cls_id].append(tid)
                online_scores[cls_id].append(tscore)
G
George Ni 已提交
121
        return online_tlwhs, online_scores, online_ids
122

W
wangguanzhong 已提交
123
    def predict(self, image_list, threshold=0.5, repeats=1, add_timer=True):
124 125
        '''
        Args:
126
            image_list (list): list of image
127
            threshold (float): threshold of predicted box' score
W
wangguanzhong 已提交
128 129
            repeats (int): repeat number for prediction
            add_timer (bool): whether add timer during prediction
130
        Returns:
131
            online_tlwhs, online_scores, online_ids (dict[np.array])
132
        '''
W
wangguanzhong 已提交
133 134 135
        # preprocess
        if add_timer:
            self.det_times.preprocess_time_s.start()
136
        inputs = self.preprocess(image_list)
G
George Ni 已提交
137

138 139 140 141 142
        pred_dets, pred_embs = None, None
        input_names = self.predictor.get_input_names()
        for i in range(len(input_names)):
            input_tensor = self.predictor.get_input_handle(input_names[i])
            input_tensor.copy_from_cpu(inputs[input_names[i]])
W
wangguanzhong 已提交
143 144 145
        if add_timer:
            self.det_times.preprocess_time_s.end()
            self.det_times.inference_time_s.start()
146

W
wangguanzhong 已提交
147
        # model prediction
148 149 150 151 152 153 154 155
        for i in range(repeats):
            self.predictor.run()
            output_names = self.predictor.get_output_names()
            boxes_tensor = self.predictor.get_output_handle(output_names[0])
            pred_dets = boxes_tensor.copy_to_cpu()
            embs_tensor = self.predictor.get_output_handle(output_names[1])
            pred_embs = embs_tensor.copy_to_cpu()

W
wangguanzhong 已提交
156 157 158 159 160
        if add_timer:
            self.det_times.inference_time_s.end(repeats=repeats)
            self.det_times.postprocess_time_s.start()

        # postprocess
161 162
        online_tlwhs, online_scores, online_ids = self.postprocess(
            pred_dets, pred_embs, threshold)
W
wangguanzhong 已提交
163 164 165
        if add_timer:
            self.det_times.postprocess_time_s.end()
            self.det_times.img_num += 1
G
George Ni 已提交
166
        return online_tlwhs, online_scores, online_ids
167 168


G
George Ni 已提交
169 170
def predict_image(detector, image_list):
    results = []
171 172
    num_classes = detector.num_classes
    data_type = 'mcmot' if num_classes > 1 else 'mot'
173 174
    ids2names = detector.pred_config.labels

G
George Ni 已提交
175
    image_list.sort()
176
    for frame_id, img_file in enumerate(image_list):
G
George Ni 已提交
177 178
        frame = cv2.imread(img_file)
        if FLAGS.run_benchmark:
W
wangguanzhong 已提交
179 180 181 182 183 184
            # warmup
            detector.predict(
                [frame], FLAGS.threshold, repeats=10, add_timer=False)
            # run benchmark
            detector.predict(
                [frame], FLAGS.threshold, repeats=10, add_timer=True)
G
George Ni 已提交
185 186 187 188
            cm, gm, gu = get_current_memory_mb()
            detector.cpu_mem += cm
            detector.gpu_mem += gm
            detector.gpu_util += gu
189
            print('Test iter {}, file name:{}'.format(frame_id, img_file))
G
George Ni 已提交
190 191
        else:
            online_tlwhs, online_scores, online_ids = detector.predict(
192
                [frame], FLAGS.threshold)
W
wangguanzhong 已提交
193 194 195 196 197 198 199 200
            online_im = plot_tracking_dict(
                frame,
                num_classes,
                online_tlwhs,
                online_ids,
                online_scores,
                frame_id,
                ids2names=ids2names)
G
George Ni 已提交
201 202 203
            if FLAGS.save_images:
                if not os.path.exists(FLAGS.output_dir):
                    os.makedirs(FLAGS.output_dir)
204 205 206 207
                img_name = os.path.split(img_file)[-1]
                out_path = os.path.join(FLAGS.output_dir, img_name)
                cv2.imwrite(out_path, online_im)
                print("save result to: " + out_path)
G
George Ni 已提交
208 209


210
def predict_video(detector, camera_id):
211
    video_name = 'mot_output.mp4'
212 213 214 215 216
    if camera_id != -1:
        capture = cv2.VideoCapture(camera_id)
    else:
        capture = cv2.VideoCapture(FLAGS.video_file)
        video_name = os.path.split(FLAGS.video_file)[-1]
217
    # Get Video info : resolution, fps, frame count
218 219
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
220 221 222 223
    fps = int(capture.get(cv2.CAP_PROP_FPS))
    frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))
    print("fps: %d, frame_count: %d" % (fps, frame_count))

224 225 226
    if not os.path.exists(FLAGS.output_dir):
        os.makedirs(FLAGS.output_dir)
    out_path = os.path.join(FLAGS.output_dir, video_name)
G
George Ni 已提交
227
    if not FLAGS.save_images:
W
wangguanzhong 已提交
228
        fourcc = cv2.VideoWriter_fourcc(* 'mp4v')
G
George Ni 已提交
229
        writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
230 231
    frame_id = 0
    timer = MOTTimer()
232 233 234
    results = defaultdict(list)  # support single class and multi classes
    num_classes = detector.num_classes
    data_type = 'mcmot' if num_classes > 1 else 'mot'
235 236
    ids2names = detector.pred_config.labels

237 238 239 240 241
    while (1):
        ret, frame = capture.read()
        if not ret:
            break
        timer.tic()
G
George Ni 已提交
242
        online_tlwhs, online_scores, online_ids = detector.predict(
243
            [frame], FLAGS.threshold)
244 245
        timer.toc()

246 247 248 249
        for cls_id in range(num_classes):
            results[cls_id].append((frame_id + 1, online_tlwhs[cls_id],
                                    online_scores[cls_id], online_ids[cls_id]))

G
George Ni 已提交
250
        fps = 1. / timer.average_time
251
        im = plot_tracking_dict(
252
            frame,
253
            num_classes,
254 255
            online_tlwhs,
            online_ids,
G
George Ni 已提交
256
            online_scores,
257
            frame_id=frame_id,
258 259
            fps=fps,
            ids2names=ids2names)
G
George Ni 已提交
260 261 262 263 264
        if FLAGS.save_images:
            save_dir = os.path.join(FLAGS.output_dir, video_name.split('.')[-2])
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            cv2.imwrite(
G
George Ni 已提交
265
                os.path.join(save_dir, '{:05d}.jpg'.format(frame_id)), im)
G
George Ni 已提交
266 267
        else:
            writer.write(im)
268

269
        frame_id += 1
270
        print('detect frame: %d' % (frame_id))
271 272 273 274
        if camera_id != -1:
            cv2.imshow('Tracking Detection', im)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
G
George Ni 已提交
275
    if FLAGS.save_mot_txts:
G
George Ni 已提交
276 277
        result_filename = os.path.join(FLAGS.output_dir,
                                       video_name.split('.')[-2] + '.txt')
278 279

        write_mot_results(result_filename, results, data_type, num_classes)
G
George Ni 已提交
280 281 282

    if FLAGS.save_images:
        save_dir = os.path.join(FLAGS.output_dir, video_name.split('.')[-2])
F
Feng Ni 已提交
283 284
        cmd_str = 'ffmpeg -f image2 -i {}/%05d.jpg {}'.format(save_dir,
                                                              out_path)
G
George Ni 已提交
285 286 287 288
        os.system(cmd_str)
        print('Save video in {}.'.format(out_path))
    else:
        writer.release()
289 290 291


def main():
G
George Ni 已提交
292
    pred_config = PredictConfig(FLAGS.model_dir)
293
    detector = JDE_Detector(
294 295
        pred_config,
        FLAGS.model_dir,
296
        device=FLAGS.device,
297 298 299 300 301 302 303 304 305 306 307 308
        run_mode=FLAGS.run_mode,
        trt_min_shape=FLAGS.trt_min_shape,
        trt_max_shape=FLAGS.trt_max_shape,
        trt_opt_shape=FLAGS.trt_opt_shape,
        trt_calib_mode=FLAGS.trt_calib_mode,
        cpu_threads=FLAGS.cpu_threads,
        enable_mkldnn=FLAGS.enable_mkldnn)

    # predict from video file or camera video stream
    if FLAGS.video_file is not None or FLAGS.camera_id != -1:
        predict_video(detector, FLAGS.camera_id)
    else:
G
George Ni 已提交
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
        # predict from image
        img_list = get_test_images(FLAGS.image_dir, FLAGS.image_file)
        predict_image(detector, img_list)
        if not FLAGS.run_benchmark:
            detector.det_times.info(average=True)
        else:
            mems = {
                'cpu_rss_mb': detector.cpu_mem / len(img_list),
                'gpu_rss_mb': detector.gpu_mem / len(img_list),
                'gpu_util': detector.gpu_util * 100 / len(img_list)
            }
            perf_info = detector.det_times.report(average=True)
            model_dir = FLAGS.model_dir
            mode = FLAGS.run_mode
            model_info = {
                'model_name': model_dir.strip('/').split('/')[-1],
                'precision': mode.split('_')[-1]
            }
            data_info = {
                'batch_size': 1,
                'shape': "dynamic_shape",
                'data_num': perf_info['img_num']
            }
            det_log = PaddleInferBenchmark(detector.config, model_info,
                                           data_info, perf_info, mems)
            det_log('MOT')
335 336 337 338 339 340 341


if __name__ == '__main__':
    paddle.enable_static()
    parser = argsparser()
    FLAGS = parser.parse_args()
    print_arguments(FLAGS)
342 343 344
    FLAGS.device = FLAGS.device.upper()
    assert FLAGS.device in ['CPU', 'GPU', 'XPU'
                            ], "device should be CPU, GPU or XPU"
345 346

    main()