mot_jde_infer.py 16.7 KB
Newer Older
W
wangguanzhong 已提交
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
# 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
from collections import defaultdict

import paddle
from paddle.inference import Config
from paddle.inference import create_predictor

from utils import argsparser, Timer, get_current_memory_mb
from det_infer import Detector, get_test_images, print_arguments, PredictConfig
from benchmark_utils import PaddleInferBenchmark
from visualize import plot_tracking_dict

from mot.tracker import JDETracker
from mot.utils import MOTTimer, write_mot_results, flow_statistic

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


class JDE_Detector(Detector):
    """
    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
        device (str): Choose the device you want to run, it can be: CPU/GPU/XPU, default is CPU
        run_mode (str): mode of running(fluid/trt_fp32/trt_fp16)
48
        batch_size (int): size of per batch in inference, default is 1 in tracking models
W
wangguanzhong 已提交
49 50 51 52 53 54
        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
55
        enable_mkldnn (bool): whether to open MKLDNN
W
wangguanzhong 已提交
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
    """

    def __init__(self,
                 pred_config,
                 model_dir,
                 device='CPU',
                 run_mode='fluid',
                 batch_size=1,
                 trt_min_shape=1,
                 trt_max_shape=1088,
                 trt_opt_shape=608,
                 trt_calib_mode=False,
                 cpu_threads=1,
                 enable_mkldnn=False):
        super(JDE_Detector, self).__init__(
            pred_config=pred_config,
            model_dir=model_dir,
            device=device,
            run_mode=run_mode,
            batch_size=batch_size,
            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)
        assert batch_size == 1, "The JDE Detector only supports batch size=1 now"
        assert pred_config.tracker, "Tracking model should have tracker"
        self.num_classes = len(pred_config.labels)

        tp = pred_config.tracker
        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
        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'

        self.tracker = JDETracker(
            num_classes=self.num_classes,
            min_box_area=min_box_area,
            vertical_ratio=vertical_ratio,
            conf_thres=conf_thres,
            tracked_thresh=tracked_thresh,
            metric_type=metric_type)

    def postprocess(self, pred_dets, pred_embs, threshold):
        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
114 115
                if tlwh[2] * tlwh[3] <= self.tracker.min_box_area:
                    continue
W
wangguanzhong 已提交
116 117 118 119 120 121 122 123
                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)
        return online_tlwhs, online_scores, online_ids

124
    def predict(self, image_list, threshold=0.5, repeats=1, add_timer=True):
W
wangguanzhong 已提交
125 126
        '''
        Args:
127 128
            image_list (list[str]): path of images, only support one image path
                (batch_size=1) in tracking model
W
wangguanzhong 已提交
129
            threshold (float): threshold of predicted box' score
130 131
            repeats (int): repeat number for prediction
            add_timer (bool): whether add timer during prediction
W
wangguanzhong 已提交
132 133 134
        Returns:
            online_tlwhs, online_scores, online_ids (dict[np.array])
        '''
135 136 137
        # preprocess
        if add_timer:
            self.det_times.preprocess_time_s.start()
W
wangguanzhong 已提交
138 139 140 141 142 143 144
        inputs = self.preprocess(image_list)

        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]])
145 146 147
        if add_timer:
            self.det_times.preprocess_time_s.end()
            self.det_times.inference_time_s.start()
W
wangguanzhong 已提交
148

149
        # model prediction
W
wangguanzhong 已提交
150 151 152 153 154 155 156
        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()
157 158 159
        if add_timer:
            self.det_times.inference_time_s.end(repeats=repeats)
            self.det_times.postprocess_time_s.start()
W
wangguanzhong 已提交
160

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


F
Feng Ni 已提交
170 171 172 173 174 175
def predict_image(detector,
                  image_list,
                  threshold,
                  output_dir,
                  save_images=True,
                  run_benchmark=False):
W
wangguanzhong 已提交
176 177 178 179 180 181 182 183
    results = []
    num_classes = detector.num_classes
    data_type = 'mcmot' if num_classes > 1 else 'mot'
    ids2names = detector.pred_config.labels

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


F
Feng Ni 已提交
214 215 216 217 218 219 220 221 222 223
def predict_video(detector,
                  video_file,
                  threshold,
                  output_dir,
                  save_images=True,
                  save_mot_txts=True,
                  draw_center_traj=False,
                  secs_interval=10,
                  do_entrance_counting=False,
                  camera_id=-1):
W
wangguanzhong 已提交
224 225 226 227
    video_name = 'mot_output.mp4'
    if camera_id != -1:
        capture = cv2.VideoCapture(camera_id)
    else:
F
Feng Ni 已提交
228 229 230
        capture = cv2.VideoCapture(video_file)
        video_name = os.path.split(video_file)[-1]

W
wangguanzhong 已提交
231 232 233 234 235 236 237
    # Get Video info : resolution, fps, frame count
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
    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))

F
Feng Ni 已提交
238 239 240 241
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    out_path = os.path.join(output_dir, video_name)
    if not save_images:
W
wangguanzhong 已提交
242 243 244 245 246 247 248 249 250 251 252 253
        video_format = 'mp4v'
        fourcc = cv2.VideoWriter_fourcc(*video_format)
        writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
    frame_id = 0
    timer = MOTTimer()
    results = defaultdict(list)  # support single class and multi classes
    num_classes = detector.num_classes
    data_type = 'mcmot' if num_classes > 1 else 'mot'
    ids2names = detector.pred_config.labels
    center_traj = None
    entrance = None
    records = None
F
Feng Ni 已提交
254
    if draw_center_traj:
W
wangguanzhong 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
        center_traj = [{} for i in range(num_classes)]

    if num_classes == 1:
        id_set = set()
        interval_id_set = set()
        in_id_list = list()
        out_id_list = list()
        prev_center = dict()
        records = list()
        entrance = [0, height / 2., width, height / 2.]

    video_fps = fps

    while (1):
        ret, frame = capture.read()
        if not ret:
            break
        timer.tic()
F
Feng Ni 已提交
273 274
        online_tlwhs, online_scores, online_ids = detector.predict([frame],
                                                                   threshold)
W
wangguanzhong 已提交
275 276 277 278 279 280 281 282 283 284 285 286
        timer.toc()

        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]))

        fps = 1. / timer.duration
        # NOTE: just implement flow statistic for one class
        if num_classes == 1:
            result = (frame_id + 1, online_tlwhs[0], online_scores[0],
                      online_ids[0])
            statistic = flow_statistic(
F
Feng Ni 已提交
287 288 289
                result, secs_interval, do_entrance_counting, video_fps,
                entrance, id_set, interval_id_set, in_id_list, out_id_list,
                prev_center, records, data_type, num_classes)
W
wangguanzhong 已提交
290 291 292 293 294 295 296
            id_set = statistic['id_set']
            interval_id_set = statistic['interval_id_set']
            in_id_list = statistic['in_id_list']
            out_id_list = statistic['out_id_list']
            prev_center = statistic['prev_center']
            records = statistic['records']

F
Feng Ni 已提交
297
        elif num_classes > 1 and do_entrance_counting:
W
wangguanzhong 已提交
298 299 300 301 302 303 304 305 306 307 308
            raise NotImplementedError(
                'Multi-class flow counting is not implemented now!')
        im = plot_tracking_dict(
            frame,
            num_classes,
            online_tlwhs,
            online_ids,
            online_scores,
            frame_id=frame_id,
            fps=fps,
            ids2names=ids2names,
F
Feng Ni 已提交
309
            do_entrance_counting=do_entrance_counting,
W
wangguanzhong 已提交
310 311 312 313
            entrance=entrance,
            records=records,
            center_traj=center_traj)

F
Feng Ni 已提交
314 315
        if save_images:
            save_dir = os.path.join(output_dir, video_name.split('.')[-2])
W
wangguanzhong 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328
            if not os.path.exists(save_dir):
                os.makedirs(save_dir)
            cv2.imwrite(
                os.path.join(save_dir, '{:05d}.jpg'.format(frame_id)), im)
        else:
            writer.write(im)

        frame_id += 1
        print('detect frame: %d, fps: %f' % (frame_id, fps))
        if camera_id != -1:
            cv2.imshow('Tracking Detection', im)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
F
Feng Ni 已提交
329 330
    if save_mot_txts:
        result_filename = os.path.join(output_dir,
W
wangguanzhong 已提交
331 332 333 334 335 336
                                       video_name.split('.')[-2] + '.txt')

        write_mot_results(result_filename, results, data_type, num_classes)

        if num_classes == 1:
            result_filename = os.path.join(
F
Feng Ni 已提交
337
                output_dir, video_name.split('.')[-2] + '_flow_statistic.txt')
W
wangguanzhong 已提交
338 339 340 341 342 343
            f = open(result_filename, 'w')
            for line in records:
                f.write(line)
            print('Flow statistic save in {}'.format(result_filename))
            f.close()

F
Feng Ni 已提交
344 345
    if save_images:
        save_dir = os.path.join(output_dir, video_name.split('.')[-2])
W
wangguanzhong 已提交
346 347 348 349 350 351 352 353
        cmd_str = 'ffmpeg -f image2 -i {}/%05d.jpg {}'.format(save_dir,
                                                              out_path)
        os.system(cmd_str)
        print('Save video in {}.'.format(out_path))
    else:
        writer.release()


F
Feng Ni 已提交
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
def predict_naive(model_dir,
                  video_file,
                  image_dir,
                  device='gpu',
                  threshold=0.5,
                  output_dir='output'):
    pred_config = PredictConfig(model_dir)
    detector = JDE_Detector(pred_config, model_dir, device=device.upper())

    if video_file is not None:
        predict_video(
            detector,
            video_file,
            threshold=threshold,
            output_dir=output_dir,
            save_images=True,
            save_mot_txts=True,
            draw_center_traj=False,
            secs_interval=10,
            do_entrance_counting=False)
    else:
        img_list = get_test_images(image_dir, infer_img=None)
        predict_image(
            detector,
            img_list,
            threshold=threshold,
            output_dir=output_dir,
            save_images=True)


W
wangguanzhong 已提交
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
def main():
    pred_config = PredictConfig(FLAGS.model_dir)
    detector = JDE_Detector(
        pred_config,
        FLAGS.model_dir,
        device=FLAGS.device,
        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:
F
Feng Ni 已提交
400 401 402 403 404 405 406 407 408 409 410
        predict_video(
            detector,
            FLAGS.video_file,
            threshold=FLAGS.threshold,
            output_dir=FLAGS.output_dir,
            save_images=FLAGS.save_images,
            save_mot_txts=FLAGS.save_mot_txts,
            draw_center_traj=FLAGS.draw_center_traj,
            secs_interval=FLAGS.secs_interval,
            do_entrance_counting=FLAGS.do_entrance_counting,
            camera_id=FLAGS.camera_id)
W
wangguanzhong 已提交
411 412 413
    else:
        # predict from image
        img_list = get_test_images(FLAGS.image_dir, FLAGS.image_file)
F
Feng Ni 已提交
414 415 416 417 418 419 420
        predict_image(
            detector,
            img_list,
            threshold=FLAGS.threshold,
            output_dir=FLAGS.output_dir,
            save_images=FLAGS.save_images,
            run_benchmark=FLAGS.run_benchmark)
W
wangguanzhong 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        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')


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

    main()