det_keypoint_unite_infer.py 13.7 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
16
import json
17
import cv2
W
wangguanzhong 已提交
18
import math
19 20
import numpy as np
import paddle
W
wangguanzhong 已提交
21
import yaml
22

23
from det_keypoint_unite_utils import argsparser
24
from preprocess import decode_image
W
wangguanzhong 已提交
25 26 27
from infer import Detector, DetectorPicoDet, PredictConfig, print_arguments, get_test_images, bench_log
from keypoint_infer import KeyPointDetector, PredictConfig_KeyPoint
from visualize import visualize_pose
W
wangguanzhong 已提交
28 29
from benchmark_utils import PaddleInferBenchmark
from utils import get_current_memory_mb
30 31 32 33 34 35
from keypoint_postprocess import translate_to_ori_images

KEYPOINT_SUPPORT_MODELS = {
    'HigherHRNet': 'keypoint_bottomup',
    'HRNet': 'keypoint_topdown'
}
36 37


38
def predict_with_given_det(image, det_res, keypoint_detector,
39
                           keypoint_batch_size, run_benchmark):
40
    rec_images, records, det_rects = keypoint_detector.get_person_from_rect(
41
        image, det_res)
42 43 44
    keypoint_vector = []
    score_vector = []

W
wangguanzhong 已提交
45 46 47 48 49
    rect_vector = det_rects
    keypoint_results = keypoint_detector.predict_image(
        rec_images, run_benchmark, repeats=10, visual=False)
    keypoint_vector, score_vector = translate_to_ori_images(keypoint_results,
                                                            np.array(records))
50 51
    keypoint_res = {}
    keypoint_res['keypoint'] = [
W
wangguanzhong 已提交
52
        keypoint_vector.tolist(), score_vector.tolist()
53 54 55
    ] if len(keypoint_vector) > 0 else [[], []]
    keypoint_res['bbox'] = rect_vector
    return keypoint_res
56 57


W
wangguanzhong 已提交
58 59 60
def topdown_unite_predict(detector,
                          topdown_keypoint_detector,
                          image_list,
61 62
                          keypoint_batch_size=1,
                          save_res=False):
W
wangguanzhong 已提交
63
    det_timer = detector.get_timer()
64
    store_res = []
65
    for i, img_file in enumerate(image_list):
W
wangguanzhong 已提交
66 67
        # Decode image in advance in det + pose prediction
        det_timer.preprocess_time_s.start()
68
        image, _ = decode_image(img_file, {})
W
wangguanzhong 已提交
69 70 71
        det_timer.preprocess_time_s.end()

        if FLAGS.run_benchmark:
W
wangguanzhong 已提交
72 73 74
            results = detector.predict_image(
                [image], run_benchmark=True, repeats=10)

W
wangguanzhong 已提交
75 76 77 78 79
            cm, gm, gu = get_current_memory_mb()
            detector.cpu_mem += cm
            detector.gpu_mem += gm
            detector.gpu_util += gu
        else:
W
wangguanzhong 已提交
80
            results = detector.predict_image([image], visual=False)
81 82 83 84 85 86 87
        results = detector.filter_box(results, FLAGS.det_threshold)
        if results['boxes_num'] > 0:
            keypoint_res = predict_with_given_det(
                image, results, topdown_keypoint_detector, keypoint_batch_size,
                FLAGS.run_benchmark)

            if save_res:
J
JYChen 已提交
88
                save_name = img_file if isinstance(img_file, str) else i
89
                store_res.append([
J
JYChen 已提交
90
                    save_name, keypoint_res['bbox'],
91 92 93 94 95
                    [keypoint_res['keypoint'][0], keypoint_res['keypoint'][1]]
                ])
        else:
            results["keypoint"] = [[], []]
            keypoint_res = results
W
wangguanzhong 已提交
96 97 98 99 100 101 102 103
        if FLAGS.run_benchmark:
            cm, gm, gu = get_current_memory_mb()
            topdown_keypoint_detector.cpu_mem += cm
            topdown_keypoint_detector.gpu_mem += gm
            topdown_keypoint_detector.gpu_util += gu
        else:
            if not os.path.exists(FLAGS.output_dir):
                os.makedirs(FLAGS.output_dir)
W
wangguanzhong 已提交
104
            visualize_pose(
W
wangguanzhong 已提交
105 106
                img_file,
                keypoint_res,
W
wangguanzhong 已提交
107
                visual_thresh=FLAGS.keypoint_threshold,
W
wangguanzhong 已提交
108
                save_dir=FLAGS.output_dir)
109 110 111 112 113 114 115 116 117 118
    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)
119 120


W
wangguanzhong 已提交
121 122 123
def topdown_unite_predict_video(detector,
                                topdown_keypoint_detector,
                                camera_id,
124 125
                                keypoint_batch_size=1,
                                save_res=False):
126
    video_name = 'output.mp4'
127 128 129 130
    if camera_id != -1:
        capture = cv2.VideoCapture(camera_id)
    else:
        capture = cv2.VideoCapture(FLAGS.video_file)
W
wangguanzhong 已提交
131
        video_name = os.path.split(FLAGS.video_file)[-1]
132
    # Get Video info : resolution, fps, frame count
133 134
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
135 136 137 138
    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))

139 140 141
    if not os.path.exists(FLAGS.output_dir):
        os.makedirs(FLAGS.output_dir)
    out_path = os.path.join(FLAGS.output_dir, video_name)
142
    fourcc = cv2.VideoWriter_fourcc(* 'mp4v')
143
    writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
144
    index = 0
145
    store_res = []
Z
zhiboniu 已提交
146 147
    keypoint_smoothing = KeypointSmoothing(
        width, height, filter_type=FLAGS.filter_type, beta=0.05)
148

149 150 151 152 153
    while (1):
        ret, frame = capture.read()
        if not ret:
            break
        index += 1
154
        print('detect frame: %d' % (index))
155 156

        frame2 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
W
wangguanzhong 已提交
157 158

        results = detector.predict_image([frame2], visual=False)
159 160 161 162
        results = detector.filter_box(results, FLAGS.det_threshold)
        if results['boxes_num'] == 0:
            writer.write(frame)
            continue
163 164 165

        keypoint_res = predict_with_given_det(
            frame2, results, topdown_keypoint_detector, keypoint_batch_size,
166
            FLAGS.run_benchmark)
Z
zhiboniu 已提交
167

168 169
        if FLAGS.smooth:
            current_keypoints = np.array(keypoint_res['keypoint'][0][0])
Z
zhiboniu 已提交
170 171
            smooth_keypoints = keypoint_smoothing.smooth_process(
                current_keypoints)
172 173

            keypoint_res['keypoint'][0][0] = smooth_keypoints.tolist()
174

W
wangguanzhong 已提交
175
        im = visualize_pose(
176 177
            frame,
            keypoint_res,
W
wangguanzhong 已提交
178
            visual_thresh=FLAGS.keypoint_threshold,
179
            returnimg=True)
180

181 182 183 184 185
        if save_res:
            store_res.append([
                index, keypoint_res['bbox'],
                [keypoint_res['keypoint'][0], keypoint_res['keypoint'][1]]
            ])
186 187 188 189 190 191 192

        writer.write(im)
        if camera_id != -1:
            cv2.imshow('Mask Detection', im)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    writer.release()
W
wangguanzhong 已提交
193
    print('output_video saved to: {}'.format(out_path))
194 195 196 197 198 199 200 201 202 203
    if save_res:
        """
        1) store_res: a list of frame_data
        2) frame_data: [frameid, 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_video_results.json", 'w') as wf:
            json.dump(store_res, wf, indent=4)
204 205


206 207
class KeypointSmoothing(object):
    # The following code are modified from:
Z
zhiboniu 已提交
208 209 210 211 212 213 214 215 216 217 218
    # https://github.com/jaantollander/OneEuroFilter

    def __init__(self,
                 width,
                 height,
                 filter_type,
                 alpha=0.5,
                 fc_d=0.1,
                 fc_min=0.1,
                 beta=0.1,
                 thres_mult=0.2):
219 220 221
        super(KeypointSmoothing, self).__init__()
        self.image_width = width
        self.image_height = height
Z
zhiboniu 已提交
222 223 224 225
        self.threshold = np.array([
            0.005, 0.005, 0.005, 0.005, 0.005, 0.01, 0.01, 0.01, 0.01, 0.01,
            0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01
        ]) * thres_mult
226 227 228 229 230 231 232
        self.filter_type = filter_type
        self.alpha = alpha
        self.dx_prev_hat = None
        self.x_prev_hat = None
        self.fc_d = fc_d
        self.fc_min = fc_min
        self.beta = beta
Z
zhiboniu 已提交
233

234 235 236 237 238 239 240
        if self.filter_type == 'one_euro':
            self.smooth_func = self.one_euro_filter
        elif self.filter_type == 'ema':
            self.smooth_func = self.exponential_smoothing
        else:
            raise ValueError('filter type must be one_euro or ema')

Z
zhiboniu 已提交
241 242 243 244 245
    def smooth_process(self, current_keypoints):
        if self.x_prev_hat is None:
            self.x_prev_hat = current_keypoints[:, :2]
            self.dx_prev_hat = np.zeros(current_keypoints[:, :2].shape)
            return current_keypoints
246
        else:
Z
zhiboniu 已提交
247
            result = current_keypoints
248 249
            num_keypoints = len(current_keypoints)
            for i in range(num_keypoints):
Z
zhiboniu 已提交
250 251 252 253 254 255 256 257 258
                result[i, :2] = self.smooth(current_keypoints[i, :2],
                                            self.threshold[i], i)
            return result

    def smooth(self, current_keypoint, threshold, index):
        distance = np.sqrt(
            np.square((current_keypoint[0] - self.x_prev_hat[index][0]) /
                      self.image_width) + np.square((current_keypoint[
                          1] - self.x_prev_hat[index][1]) / self.image_height))
259
        if distance < threshold:
Z
zhiboniu 已提交
260
            result = self.x_prev_hat[index]
261
        else:
Z
zhiboniu 已提交
262 263
            result = self.smooth_func(current_keypoint, self.x_prev_hat[index],
                                      index)
264 265
        return result

Z
zhiboniu 已提交
266
    def one_euro_filter(self, x_cur, x_pre, index):
267 268
        te = 1
        self.alpha = self.smoothing_factor(te, self.fc_d)
Z
zhiboniu 已提交
269 270 271
        dx_cur = (x_cur - x_pre) / te
        dx_cur_hat = self.exponential_smoothing(dx_cur, self.dx_prev_hat[index])

272 273
        fc = self.fc_min + self.beta * np.abs(dx_cur_hat)
        self.alpha = self.smoothing_factor(te, fc)
Z
zhiboniu 已提交
274 275 276
        x_cur_hat = self.exponential_smoothing(x_cur, x_pre)
        self.dx_prev_hat[index] = dx_cur_hat
        self.x_prev_hat[index] = x_cur_hat
277 278 279 280 281
        return x_cur_hat

    def smoothing_factor(self, te, fc):
        r = 2 * math.pi * fc * te
        return r / (r + 1)
Z
zhiboniu 已提交
282 283 284

    def exponential_smoothing(self, x_cur, x_pre, index=0):
        return self.alpha * x_cur + (1 - self.alpha) * x_pre
285 286


287
def main():
W
wangguanzhong 已提交
288 289 290 291
    deploy_file = os.path.join(FLAGS.det_model_dir, 'infer_cfg.yml')
    with open(deploy_file) as f:
        yml_conf = yaml.safe_load(f)
    arch = yml_conf['arch']
292
    detector_func = 'Detector'
W
wangguanzhong 已提交
293
    if arch == 'PicoDet':
294 295
        detector_func = 'DetectorPicoDet'

W
wangguanzhong 已提交
296
    detector = eval(detector_func)(FLAGS.det_model_dir,
297 298 299 300 301 302 303
                                   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,
W
wangguanzhong 已提交
304 305
                                   enable_mkldnn=FLAGS.enable_mkldnn,
                                   threshold=FLAGS.det_threshold)
306

W
wangguanzhong 已提交
307
    topdown_keypoint_detector = KeyPointDetector(
308
        FLAGS.keypoint_model_dir,
G
Guanghua Yu 已提交
309
        device=FLAGS.device,
310
        run_mode=FLAGS.run_mode,
311
        batch_size=FLAGS.keypoint_batch_size,
312 313 314 315 316
        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,
Z
zhiboniu 已提交
317 318
        enable_mkldnn=FLAGS.enable_mkldnn,
        use_dark=FLAGS.use_dark)
W
wangguanzhong 已提交
319 320 321
    keypoint_arch = topdown_keypoint_detector.pred_config.arch
    assert KEYPOINT_SUPPORT_MODELS[
        keypoint_arch] == 'keypoint_topdown', 'Detection-Keypoint unite inference only supports topdown models.'
322 323 324 325

    # predict from video file or camera video stream
    if FLAGS.video_file is not None or FLAGS.camera_id != -1:
        topdown_unite_predict_video(detector, topdown_keypoint_detector,
326 327
                                    FLAGS.camera_id, FLAGS.keypoint_batch_size,
                                    FLAGS.save_res)
328 329 330
    else:
        # predict from image
        img_list = get_test_images(FLAGS.image_dir, FLAGS.image_file)
W
wangguanzhong 已提交
331
        topdown_unite_predict(detector, topdown_keypoint_detector, img_list,
332
                              FLAGS.keypoint_batch_size, FLAGS.save_res)
W
wangguanzhong 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        if not FLAGS.run_benchmark:
            detector.det_times.info(average=True)
            topdown_keypoint_detector.det_times.info(average=True)
        else:
            mode = FLAGS.run_mode
            det_model_dir = FLAGS.det_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')
            keypoint_model_dir = FLAGS.keypoint_model_dir
            keypoint_model_info = {
                'model_name': keypoint_model_dir.strip('/').split('/')[-1],
                'precision': mode.split('_')[-1]
            }
            bench_log(topdown_keypoint_detector, img_list, keypoint_model_info,
                      FLAGS.keypoint_batch_size, 'KeyPoint')
351 352 353 354 355 356 357


if __name__ == '__main__':
    paddle.enable_static()
    parser = argsparser()
    FLAGS = parser.parse_args()
    print_arguments(FLAGS)
G
Guanghua Yu 已提交
358 359 360
    FLAGS.device = FLAGS.device.upper()
    assert FLAGS.device in ['CPU', 'GPU', 'XPU'
                            ], "device should be CPU, GPU or XPU"
361 362

    main()