mot_sde_infer.py 26.7 KB
Newer Older
G
George Ni 已提交
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
F
Feng Ni 已提交
20
from collections import defaultdict
G
George Ni 已提交
21

F
Feng Ni 已提交
22
import paddle
G
George Ni 已提交
23 24
from paddle.inference import Config
from paddle.inference import create_predictor
F
Feng Ni 已提交
25

26
from picodet_postprocess import PicoDetPostProcess
G
George Ni 已提交
27
from utils import argsparser, Timer, get_current_memory_mb
28
from infer import Detector, DetectorPicoDet, get_test_images, print_arguments, PredictConfig
29
from infer import load_predictor
F
Feng Ni 已提交
30 31 32 33 34
from benchmark_utils import PaddleInferBenchmark

from ppdet.modeling.mot.tracker import DeepSORTTracker
from ppdet.modeling.mot.visualization import plot_tracking
from ppdet.modeling.mot.utils import MOTTimer, write_mot_results
G
George Ni 已提交
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

# Global dictionary
MOT_SUPPORT_MODELS = {'DeepSORT'}


def bench_log(detector, img_list, model_info, batch_size=1, name=None):
    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)
    data_info = {
        'batch_size': batch_size,
        'shape': "dynamic_shape",
        'data_num': perf_info['img_num']
    }
    log = PaddleInferBenchmark(detector.config, model_info, data_info,
                               perf_info, mems)
    log(name)


def scale_coords(coords, input_shape, im_shape, scale_factor):
    im_shape = im_shape[0]
    ratio = scale_factor[0][0]
    pad_w = (input_shape[1] - int(im_shape[1])) / 2
    pad_h = (input_shape[0] - int(im_shape[0])) / 2
    coords[:, 0::2] -= pad_w
    coords[:, 1::2] -= pad_h
    coords[:, 0:4] /= ratio
    coords[:, :4] = np.clip(coords[:, :4], a_min=0, a_max=coords[:, :4].max())
    return coords.round()


def clip_box(xyxy, input_shape, im_shape, scale_factor):
    im_shape = im_shape[0]
    ratio = scale_factor[0][0]
    img0_shape = [int(im_shape[0] / ratio), int(im_shape[1] / ratio)]
    xyxy[:, 0::2] = np.clip(xyxy[:, 0::2], a_min=0, a_max=img0_shape[1])
    xyxy[:, 1::2] = np.clip(xyxy[:, 1::2], a_min=0, a_max=img0_shape[0])
75 76 77 78 79
    w = xyxy[:, 2:3] - xyxy[:, 0:1]
    h = xyxy[:, 3:4] - xyxy[:, 1:2]
    mask = np.logical_and(h > 0, w > 0)
    keep_idx = np.nonzero(mask)
    return xyxy[keep_idx[0]], keep_idx
G
George Ni 已提交
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100


def preprocess_reid(imgs,
                    w=64,
                    h=192,
                    mean=[0.485, 0.456, 0.406],
                    std=[0.229, 0.224, 0.225]):
    im_batch = []
    for img in imgs:
        img = cv2.resize(img, (w, h))
        img = img[:, :, ::-1].astype('float32').transpose((2, 0, 1)) / 255
        img_mean = np.array(mean).reshape((3, 1, 1))
        img_std = np.array(std).reshape((3, 1, 1))
        img -= img_mean
        img /= img_std
        img = np.expand_dims(img, axis=0)
        im_batch.append(img)
    im_batch = np.concatenate(im_batch, 0)
    return im_batch


101
class SDE_Detector(Detector):
G
George Ni 已提交
102 103 104 105 106
    """
    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
107
        run_mode (str): mode of running(paddle/trt_fp32/trt_fp16)
G
George Ni 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120
        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,
                 device='CPU',
121
                 run_mode='paddle',
122
                 batch_size=1,
G
George Ni 已提交
123 124 125 126 127 128
                 trt_min_shape=1,
                 trt_max_shape=1088,
                 trt_opt_shape=608,
                 trt_calib_mode=False,
                 cpu_threads=1,
                 enable_mkldnn=False):
129 130 131
        super(SDE_Detector, self).__init__(
            pred_config=pred_config,
            model_dir=model_dir,
G
George Ni 已提交
132
            device=device,
133 134
            run_mode=run_mode,
            batch_size=batch_size,
G
George Ni 已提交
135 136 137 138 139 140
            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)
141
        assert batch_size == 1, "The JDE Detector only supports batch size=1 now"
142
        self.pred_config = pred_config
G
George Ni 已提交
143

144 145
    def postprocess(self, boxes, input_shape, im_shape, scale_factor, threshold,
                    scaled):
146 147 148 149 150
        over_thres_idx = np.nonzero(boxes[:, 1:2] >= threshold)[0]
        if len(over_thres_idx) == 0:
            pred_dets = np.zeros((1, 6), dtype=np.float32)
            pred_xyxys = np.zeros((1, 4), dtype=np.float32)
            return pred_dets, pred_xyxys
151 152
        else:
            boxes = boxes[over_thres_idx]
153

154
        if not scaled:
155 156 157
            # scaled means whether the coords after detector outputs
            # have been scaled back to the original image, set True 
            # in general detector, set False in JDE YOLOv3.
158 159 160 161 162
            pred_bboxes = scale_coords(boxes[:, 2:], input_shape, im_shape,
                                       scale_factor)
        else:
            pred_bboxes = boxes[:, 2:]

163 164
        pred_xyxys, keep_idx = clip_box(pred_bboxes, input_shape, im_shape,
                                        scale_factor)
165 166 167 168 169
        if len(keep_idx[0]) == 0:
            pred_dets = np.zeros((1, 6), dtype=np.float32)
            pred_xyxys = np.zeros((1, 4), dtype=np.float32)
            return pred_dets, pred_xyxys

170 171 172 173 174 175 176 177 178
        pred_scores = boxes[:, 1:2][keep_idx[0]]
        pred_cls_ids = boxes[:, 0:1][keep_idx[0]]
        pred_tlwhs = np.concatenate(
            (pred_xyxys[:, 0:2], pred_xyxys[:, 2:4] - pred_xyxys[:, 0:2] + 1),
            axis=1)

        pred_dets = np.concatenate(
            (pred_tlwhs, pred_scores, pred_cls_ids), axis=1)

179
        return pred_dets, pred_xyxys
G
George Ni 已提交
180

W
wangguanzhong 已提交
181
    def predict(self, image, scaled, threshold=0.5, repeats=1, add_timer=True):
G
George Ni 已提交
182 183 184
        '''
        Args:
            image (np.ndarray): image numpy data
185 186
            scaled (bool): whether the coords after detector outputs are scaled,
                default False in jde yolov3, set True in general detector.
W
wangguanzhong 已提交
187 188 189
            threshold (float): threshold of predicted box' score
            repeats (int): repeat number for prediction
            add_timer (bool): whether add timer during prediction
G
George Ni 已提交
190
        Returns:
191
            pred_dets (np.ndarray, [N, 6])
G
George Ni 已提交
192
        '''
W
wangguanzhong 已提交
193 194 195
        # preprocess
        if add_timer:
            self.det_times.preprocess_time_s.start()
G
George Ni 已提交
196 197 198 199 200 201 202
        inputs = self.preprocess(image)

        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 已提交
203 204 205 206
        if add_timer:
            self.det_times.preprocess_time_s.end()
            self.det_times.inference_time_s.start()
        # model prediction
G
George Ni 已提交
207 208 209 210 211 212
        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])
            boxes = boxes_tensor.copy_to_cpu()

W
wangguanzhong 已提交
213 214 215 216 217
        if add_timer:
            self.det_times.inference_time_s.end(repeats=repeats)
            self.det_times.postprocess_time_s.start()

        # postprocess
218 219 220 221 222 223 224 225 226 227 228
        if len(boxes) == 0:
            pred_dets = np.zeros((1, 6), dtype=np.float32)
            pred_xyxys = np.zeros((1, 4), dtype=np.float32)
        else:
            input_shape = inputs['image'].shape[2:]
            im_shape = inputs['im_shape']
            scale_factor = inputs['scale_factor']

            pred_dets, pred_xyxys = self.postprocess(
                boxes, input_shape, im_shape, scale_factor, threshold, scaled)

W
wangguanzhong 已提交
229 230 231
        if add_timer:
            self.det_times.postprocess_time_s.end()
            self.det_times.img_num += 1
232
        return pred_dets, pred_xyxys
G
George Ni 已提交
233 234


235 236 237 238 239 240
class SDE_DetectorPicoDet(DetectorPicoDet):
    """
    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
241
        run_mode (str): mode of running(paddle/trt_fp32/trt_fp16)
242 243 244 245 246 247 248 249 250 251 252 253 254
        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,
                 device='CPU',
255
                 run_mode='paddle',
256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
                 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(SDE_DetectorPicoDet, 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"
        self.pred_config = pred_config

W
wangguanzhong 已提交
278 279
    def postprocess_bboxes(self, boxes, input_shape, im_shape, scale_factor,
                           threshold):
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
        over_thres_idx = np.nonzero(boxes[:, 1:2] >= threshold)[0]
        if len(over_thres_idx) == 0:
            pred_dets = np.zeros((1, 6), dtype=np.float32)
            pred_xyxys = np.zeros((1, 4), dtype=np.float32)
            return pred_dets, pred_xyxys
        else:
            boxes = boxes[over_thres_idx]

        pred_bboxes = boxes[:, 2:]

        pred_xyxys, keep_idx = clip_box(pred_bboxes, input_shape, im_shape,
                                        scale_factor)
        if len(keep_idx[0]) == 0:
            pred_dets = np.zeros((1, 6), dtype=np.float32)
            pred_xyxys = np.zeros((1, 4), dtype=np.float32)
            return pred_dets, pred_xyxys

        pred_scores = boxes[:, 1:2][keep_idx[0]]
        pred_cls_ids = boxes[:, 0:1][keep_idx[0]]
        pred_tlwhs = np.concatenate(
            (pred_xyxys[:, 0:2], pred_xyxys[:, 2:4] - pred_xyxys[:, 0:2] + 1),
            axis=1)

        pred_dets = np.concatenate(
            (pred_tlwhs, pred_scores, pred_cls_ids), axis=1)
        return pred_dets, pred_xyxys

W
wangguanzhong 已提交
307
    def predict(self, image, scaled, threshold=0.5, repeats=1, add_timer=True):
308 309 310 311 312
        '''
        Args:
            image (np.ndarray): image numpy data
            scaled (bool): whether the coords after detector outputs are scaled,
                default False in jde yolov3, set True in general detector.
W
wangguanzhong 已提交
313 314 315 316
            threshold (float): threshold of predicted box' score
            repeats (int): repeat number for prediction
            add_timer (bool): whether add timer during prediction
           
317 318 319
        Returns:
            pred_dets (np.ndarray, [N, 6])
        '''
W
wangguanzhong 已提交
320 321 322
        # preprocess
        if add_timer:
            self.det_times.preprocess_time_s.start()
323 324 325 326 327 328 329
        inputs = self.preprocess(image)

        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 已提交
330 331 332
        if add_timer:
            self.det_times.preprocess_time_s.end()
            self.det_times.inference_time_s.start()
333

W
wangguanzhong 已提交
334 335
        # model prediction
        np_score_list, np_boxes_list = [], []
336 337 338 339 340 341 342 343 344 345 346 347 348 349
        for i in range(repeats):
            self.predictor.run()
            np_score_list.clear()
            np_boxes_list.clear()
            output_names = self.predictor.get_output_names()
            num_outs = int(len(output_names) / 2)
            for out_idx in range(num_outs):
                np_score_list.append(
                    self.predictor.get_output_handle(output_names[out_idx])
                    .copy_to_cpu())
                np_boxes_list.append(
                    self.predictor.get_output_handle(output_names[
                        out_idx + num_outs]).copy_to_cpu())

W
wangguanzhong 已提交
350 351 352 353 354 355
        if add_timer:
            self.det_times.inference_time_s.end(repeats=repeats)
            self.det_times.img_num += 1
            self.det_times.postprocess_time_s.start()

        # postprocess
356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        self.postprocess = PicoDetPostProcess(
            inputs['image'].shape[2:],
            inputs['im_shape'],
            inputs['scale_factor'],
            strides=self.pred_config.fpn_stride,
            nms_threshold=self.pred_config.nms['nms_threshold'])
        boxes, boxes_num = self.postprocess(np_score_list, np_boxes_list)

        if len(boxes) == 0:
            pred_dets = np.zeros((1, 6), dtype=np.float32)
            pred_xyxys = np.zeros((1, 4), dtype=np.float32)
        else:
            input_shape = inputs['image'].shape[2:]
            im_shape = inputs['im_shape']
            scale_factor = inputs['scale_factor']
            pred_dets, pred_xyxys = self.postprocess_bboxes(
                boxes, input_shape, im_shape, scale_factor, threshold)
W
wangguanzhong 已提交
373 374
        if add_timer:
            self.det_times.postprocess_time_s.end()
375
        return pred_dets, pred_xyxys
W
wangguanzhong 已提交
376

377

378
class SDE_ReID(object):
G
George Ni 已提交
379 380 381 382
    def __init__(self,
                 pred_config,
                 model_dir,
                 device='CPU',
383
                 run_mode='paddle',
384
                 batch_size=50,
G
George Ni 已提交
385 386 387 388 389 390 391 392 393 394
                 trt_min_shape=1,
                 trt_max_shape=1088,
                 trt_opt_shape=608,
                 trt_calib_mode=False,
                 cpu_threads=1,
                 enable_mkldnn=False):
        self.pred_config = pred_config
        self.predictor, self.config = load_predictor(
            model_dir,
            run_mode=run_mode,
395
            batch_size=batch_size,
G
George Ni 已提交
396 397 398 399 400 401 402 403 404 405 406
            min_subgraph_size=self.pred_config.min_subgraph_size,
            device=device,
            use_dynamic_shape=self.pred_config.use_dynamic_shape,
            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)
        self.det_times = Timer()
        self.cpu_mem, self.gpu_mem, self.gpu_util = 0, 0, 0
407
        self.batch_size = batch_size
408
        assert pred_config.tracker, "Tracking model should have tracker"
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
        pt = pred_config.tracker
        max_age = pt['max_age'] if 'max_age' in pt else 30
        max_iou_distance = pt[
            'max_iou_distance'] if 'max_iou_distance' in pt else 0.7
        self.tracker = DeepSORTTracker(
            max_age=max_age, max_iou_distance=max_iou_distance)

    def get_crops(self, xyxy, ori_img):
        w, h = self.tracker.input_size
        self.det_times.preprocess_time_s.start()
        crops = []
        xyxy = xyxy.astype(np.int64)
        ori_img = ori_img.transpose(1, 0, 2)  # [h,w,3]->[w,h,3]
        for i, bbox in enumerate(xyxy):
            crop = ori_img[bbox[0]:bbox[2], bbox[1]:bbox[3], :]
            crops.append(crop)
        crops = preprocess_reid(crops, w, h)
        self.det_times.preprocess_time_s.end()

        return crops
G
George Ni 已提交
429 430

    def preprocess(self, crops):
431
        # to keep fast speed, only use topk crops
432
        crops = crops[:self.batch_size]
G
George Ni 已提交
433 434 435 436
        inputs = {}
        inputs['crops'] = np.array(crops).astype('float32')
        return inputs

437 438 439 440 441 442 443 444
    def postprocess(self, pred_dets, pred_embs):
        tracker = self.tracker
        tracker.predict()
        online_targets = tracker.update(pred_dets, pred_embs)

        online_tlwhs, online_scores, online_ids = [], [], []
        for t in online_targets:
            if not t.is_confirmed() or t.time_since_update > 1:
G
George Ni 已提交
445
                continue
446 447 448 449 450 451 452 453 454 455 456
            tlwh = t.to_tlwh()
            tscore = t.score
            tid = t.track_id
            if tlwh[2] * tlwh[3] <= tracker.min_box_area: continue
            if tracker.vertical_ratio > 0 and tlwh[2] / tlwh[
                    3] > tracker.vertical_ratio:
                continue
            online_tlwhs.append(tlwh)
            online_scores.append(tscore)
            online_ids.append(tid)

G
George Ni 已提交
457 458
        return online_tlwhs, online_scores, online_ids

W
wangguanzhong 已提交
459 460 461 462
    def predict(self, crops, pred_dets, repeats=1, add_timer=True):
        # preprocess
        if add_timer:
            self.det_times.preprocess_time_s.start()
G
George Ni 已提交
463 464 465 466 467 468
        inputs = self.preprocess(crops)

        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 已提交
469 470 471
        if add_timer:
            self.det_times.preprocess_time_s.end()
            self.det_times.inference_time_s.start()
G
George Ni 已提交
472

W
wangguanzhong 已提交
473
        # model prediction
G
George Ni 已提交
474 475 476 477
        for i in range(repeats):
            self.predictor.run()
            output_names = self.predictor.get_output_names()
            feature_tensor = self.predictor.get_output_handle(output_names[0])
478
            pred_embs = feature_tensor.copy_to_cpu()
W
wangguanzhong 已提交
479 480 481
        if add_timer:
            self.det_times.inference_time_s.end(repeats=repeats)
            self.det_times.postprocess_time_s.start()
G
George Ni 已提交
482

W
wangguanzhong 已提交
483
        # postprocess
484 485
        online_tlwhs, online_scores, online_ids = self.postprocess(pred_dets,
                                                                   pred_embs)
W
wangguanzhong 已提交
486 487 488
        if add_timer:
            self.det_times.postprocess_time_s.end()
            self.det_times.img_num += 1
G
George Ni 已提交
489

490
        return online_tlwhs, online_scores, online_ids
491

G
George Ni 已提交
492 493

def predict_image(detector, reid_model, image_list):
G
George Ni 已提交
494
    image_list.sort()
G
George Ni 已提交
495 496 497
    for i, img_file in enumerate(image_list):
        frame = cv2.imread(img_file)
        if FLAGS.run_benchmark:
W
wangguanzhong 已提交
498
            # warmup
499
            pred_dets, pred_xyxys = detector.predict(
W
wangguanzhong 已提交
500 501 502 503 504 505 506 507 508 509 510 511
                [frame],
                FLAGS.scaled,
                FLAGS.threshold,
                repeats=10,
                add_timer=True)
            # run benchmark
            pred_dets, pred_xyxys = detector.predict(
                [frame],
                FLAGS.scaled,
                FLAGS.threshold,
                repeats=10,
                add_timer=True)
G
George Ni 已提交
512 513 514 515 516 517
            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(i, img_file))
        else:
518 519
            pred_dets, pred_xyxys = detector.predict([frame], FLAGS.scaled,
                                                     FLAGS.threshold)
G
George Ni 已提交
520

521
        if len(pred_dets) == 1 and np.sum(pred_dets) == 0:
522 523 524
            print('Frame {} has no object, try to modify score threshold.'.
                  format(i))
            online_im = frame
G
George Ni 已提交
525
        else:
526 527 528 529
            # reid process
            crops = reid_model.get_crops(pred_xyxys, frame)

            if FLAGS.run_benchmark:
W
wangguanzhong 已提交
530 531 532 533
                # warmup
                online_tlwhs, online_scores, online_ids = reid_model.predict(
                    crops, pred_dets, repeats=10, add_timer=False)
                # run benchmark
534
                online_tlwhs, online_scores, online_ids = reid_model.predict(
W
wangguanzhong 已提交
535
                    crops, pred_dets, repeats=10, add_timer=False)
536 537 538
            else:
                online_tlwhs, online_scores, online_ids = reid_model.predict(
                    crops, pred_dets)
F
Feng Ni 已提交
539
                online_im = plot_tracking(
540
                    frame, online_tlwhs, online_ids, online_scores, frame_id=i)
G
George Ni 已提交
541

542 543 544 545 546 547 548
        if FLAGS.save_images:
            if not os.path.exists(FLAGS.output_dir):
                os.makedirs(FLAGS.output_dir)
            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 已提交
549 550 551 552 553 554 555 556 557


def predict_video(detector, reid_model, camera_id):
    if camera_id != -1:
        capture = cv2.VideoCapture(camera_id)
        video_name = 'mot_output.mp4'
    else:
        capture = cv2.VideoCapture(FLAGS.video_file)
        video_name = os.path.split(FLAGS.video_file)[-1]
558
    # Get Video info : resolution, fps, frame count
G
George Ni 已提交
559 560
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
561 562 563 564
    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))

G
George Ni 已提交
565 566 567
    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 已提交
568
    if not FLAGS.save_images:
W
wangguanzhong 已提交
569
        fourcc = cv2.VideoWriter_fourcc(* 'mp4v')
G
George Ni 已提交
570
        writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
G
George Ni 已提交
571 572
    frame_id = 0
    timer = MOTTimer()
F
Feng Ni 已提交
573
    results = defaultdict(list)
G
George Ni 已提交
574 575 576 577 578
    while (1):
        ret, frame = capture.read()
        if not ret:
            break
        timer.tic()
579 580 581
        pred_dets, pred_xyxys = detector.predict([frame], FLAGS.scaled,
                                                 FLAGS.threshold)

582
        if len(pred_dets) == 1 and np.sum(pred_dets) == 0:
583 584 585 586 587 588 589 590 591
            print('Frame {} has no object, try to modify score threshold.'.
                  format(frame_id))
            timer.toc()
            im = frame
        else:
            # reid process
            crops = reid_model.get_crops(pred_xyxys, frame)
            online_tlwhs, online_scores, online_ids = reid_model.predict(
                crops, pred_dets)
F
Feng Ni 已提交
592
            results[0].append(
593 594 595 596
                (frame_id + 1, online_tlwhs, online_scores, online_ids))
            timer.toc()

            fps = 1. / timer.average_time
F
Feng Ni 已提交
597
            im = plot_tracking(
598 599 600 601 602 603 604
                frame,
                online_tlwhs,
                online_ids,
                online_scores,
                frame_id=frame_id,
                fps=fps)

G
George Ni 已提交
605 606 607 608 609
        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 已提交
610
                os.path.join(save_dir, '{:05d}.jpg'.format(frame_id)), im)
G
George Ni 已提交
611 612
        else:
            writer.write(im)
613

G
George Ni 已提交
614
        frame_id += 1
615 616
        print('detect frame:%d' % (frame_id))

G
George Ni 已提交
617 618 619 620
        if camera_id != -1:
            cv2.imshow('Tracking Detection', im)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
621

G
George Ni 已提交
622 623 624 625
    if FLAGS.save_mot_txts:
        result_filename = os.path.join(FLAGS.output_dir,
                                       video_name.split('.')[-2] + '.txt')
        write_mot_results(result_filename, results)
G
George Ni 已提交
626 627 628

    if FLAGS.save_images:
        save_dir = os.path.join(FLAGS.output_dir, video_name.split('.')[-2])
F
Feng Ni 已提交
629 630
        cmd_str = 'ffmpeg -f image2 -i {}/%05d.jpg {}'.format(save_dir,
                                                              out_path)
G
George Ni 已提交
631 632 633 634
        os.system(cmd_str)
        print('Save video in {}.'.format(out_path))
    else:
        writer.release()
G
George Ni 已提交
635 636 637 638


def main():
    pred_config = PredictConfig(FLAGS.model_dir)
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
    detector_func = 'SDE_Detector'
    if pred_config.arch == 'PicoDet':
        detector_func = 'SDE_DetectorPicoDet'

    detector = eval(detector_func)(pred_config,
                                   FLAGS.model_dir,
                                   device=FLAGS.device,
                                   run_mode=FLAGS.run_mode,
                                   batch_size=FLAGS.batch_size,
                                   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)
G
George Ni 已提交
654 655

    pred_config = PredictConfig(FLAGS.reid_model_dir)
656
    reid_model = SDE_ReID(
G
George Ni 已提交
657 658 659 660
        pred_config,
        FLAGS.reid_model_dir,
        device=FLAGS.device,
        run_mode=FLAGS.run_mode,
661
        batch_size=FLAGS.reid_batch_size,
G
George Ni 已提交
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
        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, reid_model, FLAGS.camera_id)
    else:
        # predict from image
        img_list = get_test_images(FLAGS.image_dir, FLAGS.image_file)
        predict_image(detector, reid_model, img_list)

        if not FLAGS.run_benchmark:
            detector.det_times.info(average=True)
            reid_model.det_times.info(average=True)
        else:
            mode = FLAGS.run_mode
            det_model_dir = FLAGS.model_dir
            det_model_info = {
                'model_name': det_model_dir.strip('/').split('/')[-1],
                'precision': mode.split('_')[-1]
            }
            bench_log(detector, img_list, det_model_info, name='Det')

            reid_model_dir = FLAGS.reid_model_dir
            reid_model_info = {
                'model_name': reid_model_dir.strip('/').split('/')[-1],
                'precision': mode.split('_')[-1]
            }
            bench_log(reid_model, img_list, reid_model_info, name='ReID')


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