mot_keypoint_unite_infer.py 11.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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
W
wangguanzhong 已提交
16
import json
17 18 19 20
import cv2
import math
import numpy as np
import paddle
W
wangguanzhong 已提交
21 22 23
import yaml
import copy
from collections import defaultdict
24

25
from mot_keypoint_unite_utils import argsparser
W
wangguanzhong 已提交
26
from preprocess import decode_image
27
from infer import print_arguments, get_test_images, bench_log
28
from mot_sde_infer import SDE_Detector
W
wangguanzhong 已提交
29 30 31 32 33 34 35
from mot_jde_infer import JDE_Detector, MOT_JDE_SUPPORT_MODELS
from keypoint_infer import KeyPointDetector, KEYPOINT_SUPPORT_MODELS
from det_keypoint_unite_infer import predict_with_given_det
from visualize import visualize_pose
from benchmark_utils import PaddleInferBenchmark
from utils import get_current_memory_mb
from keypoint_postprocess import translate_to_ori_images
36

W
wangguanzhong 已提交
37 38 39 40
# add python path
import sys
parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 2)))
sys.path.insert(0, parent_path)
G
George Ni 已提交
41

42
from pptracking.python.mot.visualize import plot_tracking, plot_tracking_dict
W
wangguanzhong 已提交
43
from pptracking.python.mot.utils import MOTTimer as FPSTimer
G
George Ni 已提交
44

45 46 47 48 49 50 51 52 53 54

def convert_mot_to_det(tlwhs, scores):
    results = {}
    num_mot = len(tlwhs)
    xyxys = copy.deepcopy(tlwhs)
    for xyxy in xyxys.copy():
        xyxy[2:] = xyxy[2:] + xyxy[:2]
    # support single class now
    results['boxes'] = np.vstack(
        [np.hstack([0, scores[i], xyxys[i]]) for i in range(num_mot)])
W
wangguanzhong 已提交
55
    results['boxes_num'] = np.array([num_mot])
56 57 58
    return results


W
wangguanzhong 已提交
59 60 61 62 63 64 65
def mot_topdown_unite_predict(mot_detector,
                              topdown_keypoint_detector,
                              image_list,
                              keypoint_batch_size=1,
                              save_res=False):
    det_timer = mot_detector.get_timer()
    store_res = []
G
George Ni 已提交
66
    image_list.sort()
W
wangguanzhong 已提交
67
    num_classes = mot_detector.num_classes
G
George Ni 已提交
68
    for i, img_file in enumerate(image_list):
W
wangguanzhong 已提交
69 70 71 72
        # Decode image in advance in mot + pose prediction
        det_timer.preprocess_time_s.start()
        image, _ = decode_image(img_file, {})
        det_timer.preprocess_time_s.end()
G
George Ni 已提交
73 74

        if FLAGS.run_benchmark:
W
wangguanzhong 已提交
75 76
            mot_results = mot_detector.predict_image(
                [image], run_benchmark=True, repeats=10)
77

W
wangguanzhong 已提交
78 79 80 81
            cm, gm, gu = get_current_memory_mb()
            mot_detector.cpu_mem += cm
            mot_detector.gpu_mem += gm
            mot_detector.gpu_util += gu
82
        else:
W
wangguanzhong 已提交
83 84 85 86 87 88 89 90 91 92 93 94
            mot_results = mot_detector.predict_image([image], visual=False)

        online_tlwhs, online_scores, online_ids = mot_results[
            0]  # only support bs=1 in MOT model
        results = convert_mot_to_det(
            online_tlwhs[0],
            online_scores[0])  # only support single class for mot + pose
        if results['boxes_num'] == 0:
            continue

        keypoint_res = predict_with_given_det(
            image, results, topdown_keypoint_detector, keypoint_batch_size,
95
            FLAGS.run_benchmark)
W
wangguanzhong 已提交
96 97

        if save_res:
J
JYChen 已提交
98
            save_name = img_file if isinstance(img_file, str) else i
W
wangguanzhong 已提交
99
            store_res.append([
J
JYChen 已提交
100
                save_name, keypoint_res['bbox'],
W
wangguanzhong 已提交
101 102
                [keypoint_res['keypoint'][0], keypoint_res['keypoint'][1]]
            ])
103
        if FLAGS.run_benchmark:
G
George Ni 已提交
104
            cm, gm, gu = get_current_memory_mb()
W
wangguanzhong 已提交
105 106 107
            topdown_keypoint_detector.cpu_mem += cm
            topdown_keypoint_detector.gpu_mem += gm
            topdown_keypoint_detector.gpu_util += gu
G
George Ni 已提交
108
        else:
W
wangguanzhong 已提交
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
            if not os.path.exists(FLAGS.output_dir):
                os.makedirs(FLAGS.output_dir)
            visualize_pose(
                img_file,
                keypoint_res,
                visual_thresh=FLAGS.keypoint_threshold,
                save_dir=FLAGS.output_dir)

    if save_res:
        """
        1) store_res: a list of image_data
        2) image_data: [imageid, rects, [keypoints, scores]]
        3) rects: list of rect [xmin, ymin, xmax, ymax]
        4) keypoints: 17(joint numbers)*[x, y, conf], total 51 data in list
        5) scores: mean of all joint conf
        """
        with open("det_keypoint_unite_image_results.json", 'w') as wf:
            json.dump(store_res, wf, indent=4)


def mot_topdown_unite_predict_video(mot_detector,
                                    topdown_keypoint_detector,
                                    camera_id,
                                    keypoint_batch_size=1,
                                    save_res=False):
    video_name = 'output.mp4'
135 136 137 138 139
    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]
140
    # Get Video info : resolution, fps, frame count
141 142
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
143 144 145 146
    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))

147 148 149
    if not os.path.exists(FLAGS.output_dir):
        os.makedirs(FLAGS.output_dir)
    out_path = os.path.join(FLAGS.output_dir, video_name)
150
    fourcc = cv2.VideoWriter_fourcc(* 'mp4v')
W
wangguanzhong 已提交
151
    writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
152
    frame_id = 0
W
wangguanzhong 已提交
153
    timer_mot, timer_kp, timer_mot_kp = FPSTimer(), FPSTimer(), FPSTimer()
154

W
wangguanzhong 已提交
155
    num_classes = mot_detector.num_classes
156 157 158
    assert num_classes == 1, 'Only one category mot model supported for uniting keypoint deploy.'
    data_type = 'mot'

159 160 161 162
    while (1):
        ret, frame = capture.read()
        if not ret:
            break
W
wangguanzhong 已提交
163 164 165
        if frame_id % 10 == 0:
            print('Tracking frame: %d' % (frame_id))
        frame_id += 1
166
        timer_mot_kp.tic()
W
wangguanzhong 已提交
167 168

        # mot model
169
        timer_mot.tic()
W
wangguanzhong 已提交
170
        mot_results = mot_detector.predict_image([frame], visual=False)
171
        timer_mot.toc()
W
wangguanzhong 已提交
172 173 174 175 176 177 178 179
        online_tlwhs, online_scores, online_ids = mot_results[0]
        results = convert_mot_to_det(
            online_tlwhs[0],
            online_scores[0])  # only support single class for mot + pose
        if results['boxes_num'] == 0:
            continue

        # keypoint model
180
        timer_kp.tic()
W
wangguanzhong 已提交
181 182
        keypoint_res = predict_with_given_det(
            frame, results, topdown_keypoint_detector, keypoint_batch_size,
183
            FLAGS.run_benchmark)
184 185 186
        timer_kp.toc()
        timer_mot_kp.toc()

W
wangguanzhong 已提交
187 188 189 190
        kp_fps = 1. / timer_kp.duration
        mot_kp_fps = 1. / timer_mot_kp.duration

        im = visualize_pose(
191
            frame,
W
wangguanzhong 已提交
192 193
            keypoint_res,
            visual_thresh=FLAGS.keypoint_threshold,
194
            returnimg=True,
W
wangguanzhong 已提交
195
            ids=online_ids[0])
196

W
wangguanzhong 已提交
197
        im = plot_tracking_dict(
198
            im,
199
            num_classes,
200 201 202 203 204 205
            online_tlwhs,
            online_ids,
            online_scores,
            frame_id=frame_id,
            fps=mot_kp_fps)

W
wangguanzhong 已提交
206
        writer.write(im)
207 208 209 210 211
        if camera_id != -1:
            cv2.imshow('Tracking and keypoint results', im)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

W
wangguanzhong 已提交
212 213
    writer.release()
    print('output_video saved to: {}'.format(out_path))
214 215


W
wangguanzhong 已提交
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
def main():
    deploy_file = os.path.join(FLAGS.mot_model_dir, 'infer_cfg.yml')
    with open(deploy_file) as f:
        yml_conf = yaml.safe_load(f)
    arch = yml_conf['arch']
    mot_detector_func = 'SDE_Detector'
    if arch in MOT_JDE_SUPPORT_MODELS:
        mot_detector_func = 'JDE_Detector'

    mot_detector = eval(mot_detector_func)(FLAGS.mot_model_dir,
                                           FLAGS.tracker_config,
                                           device=FLAGS.device,
                                           run_mode=FLAGS.run_mode,
                                           batch_size=1,
                                           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,
                                           threshold=FLAGS.mot_threshold,
                                           output_dir=FLAGS.output_dir)

    topdown_keypoint_detector = KeyPointDetector(
240 241 242
        FLAGS.keypoint_model_dir,
        device=FLAGS.device,
        run_mode=FLAGS.run_mode,
243
        batch_size=FLAGS.keypoint_batch_size,
244 245 246 247 248 249
        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,
W
wangguanzhong 已提交
250 251
        threshold=FLAGS.keypoint_threshold,
        output_dir=FLAGS.output_dir,
252
        use_dark=FLAGS.use_dark)
W
wangguanzhong 已提交
253 254 255
    keypoint_arch = topdown_keypoint_detector.pred_config.arch
    assert KEYPOINT_SUPPORT_MODELS[
        keypoint_arch] == 'keypoint_topdown', 'MOT-Keypoint unite inference only supports topdown models.'
256 257 258

    # predict from video file or camera video stream
    if FLAGS.video_file is not None or FLAGS.camera_id != -1:
W
wangguanzhong 已提交
259 260 261
        mot_topdown_unite_predict_video(
            mot_detector, topdown_keypoint_detector, FLAGS.camera_id,
            FLAGS.keypoint_batch_size, FLAGS.save_res)
262
    else:
G
George Ni 已提交
263 264
        # predict from image
        img_list = get_test_images(FLAGS.image_dir, FLAGS.image_file)
W
wangguanzhong 已提交
265 266 267
        mot_topdown_unite_predict(mot_detector, topdown_keypoint_detector,
                                  img_list, FLAGS.keypoint_batch_size,
                                  FLAGS.save_res)
G
George Ni 已提交
268
        if not FLAGS.run_benchmark:
W
wangguanzhong 已提交
269 270
            mot_detector.det_times.info(average=True)
            topdown_keypoint_detector.det_times.info(average=True)
G
George Ni 已提交
271 272 273 274 275 276 277
        else:
            mode = FLAGS.run_mode
            mot_model_dir = FLAGS.mot_model_dir
            mot_model_info = {
                'model_name': mot_model_dir.strip('/').split('/')[-1],
                'precision': mode.split('_')[-1]
            }
W
wangguanzhong 已提交
278
            bench_log(mot_detector, img_list, mot_model_info, name='MOT')
G
George Ni 已提交
279 280 281 282 283 284

            keypoint_model_dir = FLAGS.keypoint_model_dir
            keypoint_model_info = {
                'model_name': keypoint_model_dir.strip('/').split('/')[-1],
                'precision': mode.split('_')[-1]
            }
W
wangguanzhong 已提交
285 286
            bench_log(topdown_keypoint_detector, img_list, keypoint_model_info,
                      FLAGS.keypoint_batch_size, 'KeyPoint')
287 288 289 290 291 292 293 294 295 296 297 298


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