keypoint_det_unite_infer.py 7.2 KB
Newer Older
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
# 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
from PIL import Image
import cv2
import numpy as np
import paddle

from topdown_unite_utils import argsparser
from preprocess import decode_image
from infer import Detector, PredictConfig, print_arguments, get_test_images
from keypoint_infer import KeyPoint_Detector, PredictConfig_KeyPoint
from keypoint_visualize import draw_pose


Z
zhiboniu 已提交
28
def expand_crop(images, rect, expand_ratio=0.3):
29
    imgh, imgw, c = images.shape
Z
zhiboniu 已提交
30
    label, conf, xmin, ymin, xmax, ymax = [int(x) for x in rect.tolist()]
31
    if label != 0:
Z
zhiboniu 已提交
32 33
        return None, None, None
    org_rect = [xmin, ymin, xmax, ymax]
34 35
    h_half = (ymax - ymin) * (1 + expand_ratio) / 2.
    w_half = (xmax - xmin) * (1 + expand_ratio) / 2.
Z
zhiboniu 已提交
36 37
    if h_half > w_half * 4 / 3:
        w_half = h_half * 0.75
38 39 40 41 42
    center = [(ymin + ymax) / 2., (xmin + xmax) / 2.]
    ymin = max(0, int(center[0] - h_half))
    ymax = min(imgh - 1, int(center[0] + h_half))
    xmin = max(0, int(center[1] - w_half))
    xmax = min(imgw - 1, int(center[1] + w_half))
Z
zhiboniu 已提交
43
    return images[ymin:ymax, xmin:xmax, :], [xmin, ymin, xmax, ymax], org_rect
44 45 46 47 48 49 50


def get_person_from_rect(images, results):
    det_results = results['boxes']
    mask = det_results[:, 1] > FLAGS.det_threshold
    valid_rects = det_results[mask]
    image_buff = []
Z
zhiboniu 已提交
51
    org_rects = []
52
    for rect in valid_rects:
Z
zhiboniu 已提交
53
        rect_image, new_rect, org_rect = expand_crop(images, rect)
54
        if rect_image is None or rect_image.size == 0:
55 56
            continue
        image_buff.append([rect_image, new_rect])
Z
zhiboniu 已提交
57 58
        org_rects.append(org_rect)
    return image_buff, org_rects
59 60 61 62 63 64 65 66 67 68 69 70 71


def affine_backto_orgimages(keypoint_result, batch_records):
    kpts, scores = keypoint_result['keypoint']
    kpts[..., 0] += batch_records[0]
    kpts[..., 1] += batch_records[1]
    return kpts, scores


def topdown_unite_predict(detector, topdown_keypoint_detector, image_list):
    for i, img_file in enumerate(image_list):
        image, _ = decode_image(img_file, {})
        results = detector.predict(image, FLAGS.det_threshold)
Z
zhiboniu 已提交
72
        batchs_images, det_rects = get_person_from_rect(image, results)
73 74
        keypoint_vector = []
        score_vector = []
Z
zhiboniu 已提交
75
        rect_vecotr = det_rects
76 77 78 79 80 81 82 83 84 85 86 87
        for batch_images, batch_records in batchs_images:
            keypoint_result = topdown_keypoint_detector.predict(
                batch_images, FLAGS.keypoint_threshold)
            orgkeypoints, scores = affine_backto_orgimages(keypoint_result,
                                                           batch_records)
            keypoint_vector.append(orgkeypoints)
            score_vector.append(scores)
        keypoint_res = {}
        keypoint_res['keypoint'] = [
            np.vstack(keypoint_vector), np.vstack(score_vector)
        ]
        keypoint_res['bbox'] = rect_vecotr
Z
zhiboniu 已提交
88 89
        if not os.path.exists(FLAGS.output_dir):
            os.makedirs(FLAGS.output_dir)
90
        draw_pose(
Z
zhiboniu 已提交
91 92 93 94
            img_file,
            keypoint_res,
            visual_thread=FLAGS.keypoint_threshold,
            save_dir=FLAGS.output_dir)
95 96 97 98 99 100 101 102


def topdown_unite_predict_video(detector, topdown_keypoint_detector, camera_id):
    if camera_id != -1:
        capture = cv2.VideoCapture(camera_id)
        video_name = 'output.mp4'
    else:
        capture = cv2.VideoCapture(FLAGS.video_file)
Z
zhiboniu 已提交
103 104
        video_name = os.path.splitext(os.path.basename(FLAGS.video_file))[
            0] + '.mp4'
105 106 107 108 109 110 111 112 113 114
    fps = 30
    width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
    # yapf: disable
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    # yapf: enable
    if not os.path.exists(FLAGS.output_dir):
        os.makedirs(FLAGS.output_dir)
    out_path = os.path.join(FLAGS.output_dir, video_name)
    writer = cv2.VideoWriter(out_path, fourcc, fps, (width, height))
115
    index = 0
116 117 118 119 120
    while (1):
        ret, frame = capture.read()
        if not ret:
            break
        index += 1
121
        print('detect frame:%d' % (index))
122 123 124

        frame2 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        results = detector.predict(frame2, FLAGS.det_threshold)
Z
zhiboniu 已提交
125
        batchs_images, rect_vecotr = get_person_from_rect(frame2, results)
126 127 128 129 130 131 132 133 134 135 136 137
        keypoint_vector = []
        score_vector = []
        for batch_images, batch_records in batchs_images:
            keypoint_result = topdown_keypoint_detector.predict(
                batch_images, FLAGS.keypoint_threshold)
            orgkeypoints, scores = affine_backto_orgimages(keypoint_result,
                                                           batch_records)
            keypoint_vector.append(orgkeypoints)
            score_vector.append(scores)
        keypoint_res = {}
        keypoint_res['keypoint'] = [
            np.vstack(keypoint_vector), np.vstack(score_vector)
138
        ] if len(keypoint_vector) > 0 else [[], []]
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
        keypoint_res['bbox'] = rect_vecotr
        im = draw_pose(
            frame,
            keypoint_res,
            visual_thread=FLAGS.keypoint_threshold,
            returnimg=True)

        writer.write(im)
        if camera_id != -1:
            cv2.imshow('Mask Detection', im)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
    writer.release()


def main():
    pred_config = PredictConfig(FLAGS.det_model_dir)
    detector = Detector(
        pred_config,
        FLAGS.det_model_dir,
        use_gpu=FLAGS.use_gpu,
        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)

    pred_config = PredictConfig_KeyPoint(FLAGS.keypoint_model_dir)
    topdown_keypoint_detector = KeyPoint_Detector(
        pred_config,
        FLAGS.keypoint_model_dir,
        use_gpu=FLAGS.use_gpu,
        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:
        topdown_unite_predict_video(detector, topdown_keypoint_detector,
                                    FLAGS.camera_id)
    else:
        # predict from image
        img_list = get_test_images(FLAGS.image_dir, FLAGS.image_file)
        topdown_unite_predict(detector, topdown_keypoint_detector, img_list)


if __name__ == '__main__':
    paddle.enable_static()
    parser = argsparser()
    FLAGS = parser.parse_args()
    print_arguments(FLAGS)

    main()