inference.py 6.4 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
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import argparse
import json
import os

import cv2
import megengine as mge
import numpy as np
from megengine import jit
import math

from official.vision.keypoints.transforms import get_affine_transform
from official.vision.keypoints.config import Config as cfg

import official.vision.keypoints.models as M
23 24
import official.vision.detection.configs as Det
from official.vision.detection.tools.utils import DetEvaluator
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
from official.vision.keypoints.test import find_keypoints

logger = mge.get_logger(__name__)


def make_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-a",
        "--arch",
        default="simplebaseline_res50",
        type=str,
        choices=[
            "simplebaseline_res50",
            "simplebaseline_res101",
            "simplebaseline_res152",
G
greatlog 已提交
41
            "mspn_4stage",
42 43 44
        ],
    )
    parser.add_argument(
G
greatlog 已提交
45
        "-det", "--detector", default="retinanet_res50_coco_1x_800size", type=str,
46 47 48 49 50 51 52 53 54
    )

    parser.add_argument(
        "-m",
        "--model",
        default="/data/models/simplebaseline_res50_256x192/epoch_199.pkl",
        type=str,
    )
    parser.add_argument(
G
greatlog 已提交
55
        "-image", "--image", default="/data/test_keypoint.jpeg", type=str
56 57 58 59
    )
    return parser


G
greatlog 已提交
60 61
class KeypointEvaluator:
    def __init__(self, detect_model, det_func, keypoint_model, keypoint_func):
62

G
greatlog 已提交
63 64
        self.detector = detect_model
        self.det_func = det_func
65

G
greatlog 已提交
66 67
        self.keypoint_model = keypoint_model
        self.keypoint_func = keypoint_func
68

G
greatlog 已提交
69
    def detect_persons(self, image):
70

G
greatlog 已提交
71 72 73 74 75
        data, im_info = DetEvaluator.process_inputs(
            image.copy(),
            self.detector.cfg.test_image_short_size,
            self.detector.cfg.test_image_max_size,
        )
76

G
greatlog 已提交
77 78
        self.detector.inputs["im_info"].set_value(im_info)
        self.detector.inputs["image"].set_value(data.astype(np.float32))
79

G
greatlog 已提交
80 81
        evaluator = DetEvaluator(self.detector)
        det_res = evaluator.predict(self.det_func)
82

G
greatlog 已提交
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 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 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
        persons = []
        for d in det_res:
            cls_id = int(d[5] + 1)
            if cls_id == 1:
                bbox = d[:4]
                persons.append(bbox)
        return persons

    def predict_single_person(self, image, bbox):

        w = bbox[2] - bbox[0]
        h = bbox[3] - bbox[1]

        center_x = (bbox[0] + bbox[2]) / 2
        center_y = (bbox[1] + bbox[3]) / 2

        extend_w = w * (1 + cfg.test_x_ext)
        extend_h = h * (1 + cfg.test_y_ext)

        w_h_ratio = cfg.input_shape[1] / cfg.input_shape[0]
        if extend_w / extend_h > w_h_ratio:
            extend_h = extend_w / w_h_ratio
        else:
            extend_w = extend_h * w_h_ratio

        trans = get_affine_transform(
            np.array([center_x, center_y]),
            np.array([extend_h, extend_w]),
            1,
            0,
            cfg.input_shape,
        )

        croped_img = cv2.warpAffine(
            image,
            trans,
            (int(cfg.input_shape[1]), int(cfg.input_shape[0])),
            flags=cv2.INTER_LINEAR,
            borderValue=0,
        )

        fliped_img = croped_img[:, ::-1]
        keypoint_input = np.stack([croped_img, fliped_img], 0)
        keypoint_input = keypoint_input.transpose(0, 3, 1, 2)
        keypoint_input = np.ascontiguousarray(keypoint_input).astype(np.float32)

        self.keypoint_model.inputs["image"].set_value(keypoint_input)

        outs = self.keypoint_func()
        outs = outs.numpy()
        pred = outs[0]
        fliped_pred = outs[1][cfg.keypoint_flip_order][:, :, ::-1]
        pred = (pred + fliped_pred) / 2

        keypoints = find_keypoints(pred, bbox)

        return keypoints

    def predict(self, image, bboxes):
        normalized_img = (image - np.array(cfg.img_mean).reshape(1, 1, 3)) / np.array(
            cfg.img_std
        ).reshape(1, 1, 3)
        all_keypoints = []
        for bbox in bboxes:
            keypoints = self.predict_single_person(normalized_img, bbox)
            all_keypoints.append(keypoints)
        return all_keypoints

    @staticmethod
    def vis_skeletons(img, all_keypoints):
        canvas = img.copy()
        for keypoints in all_keypoints:
            for ind, skeleton in enumerate(cfg.vis_skeletons):
                jotint1 = skeleton[0]
                jotint2 = skeleton[1]

                X = np.array([keypoints[jotint1, 0], keypoints[jotint2, 0]])

                Y = np.array([keypoints[jotint1, 1], keypoints[jotint2, 1]])

                mX = np.mean(X)
                mY = np.mean(Y)
                length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5

                angle = math.degrees(math.atan2(Y[0] - Y[1], X[0] - X[1]))
                polygon = cv2.ellipse2Poly(
                    (int(mX), int(mY)), (int(length / 2), 4), int(angle), 0, 360, 1
                )

                cur_canvas = canvas.copy()
                cv2.fillConvexPoly(cur_canvas, polygon, cfg.vis_colors[ind])
                canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
        return canvas
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201


def main():

    parser = make_parser()
    args = parser.parse_args()

    detector = getattr(Det, args.detector)(pretrained=True)
    detector.eval()
    logger.info("Load Model : %s completed", args.detector)

    keypoint_model = getattr(M, args.arch)()
    keypoint_model.load_state_dict(mge.load(args.model)["state_dict"])
    keypoint_model.eval()
    logger.info("Load Model : %s completed", args.arch)

    @jit.trace(symbolic=True)
    def det_func():
        pred = detector(detector.inputs)
        return pred

    @jit.trace(symbolic=True)
    def keypoint_func():
        pred = keypoint_model.predict()
        return pred

G
greatlog 已提交
202
    evaluator = KeypointEvaluator(detector, det_func, keypoint_model, keypoint_func)
203

G
greatlog 已提交
204
    image = cv2.imread(args.image)
205

G
greatlog 已提交
206 207
    logger.info("Detecting Humans")
    person_boxes = evaluator.detect_persons(image)
208 209

    logger.info("Detecting Keypoints")
G
greatlog 已提交
210
    all_keypoints = evaluator.predict(image, person_boxes)
211 212

    logger.info("Visualizing")
G
greatlog 已提交
213
    canvas = evaluator.vis_skeletons(image, all_keypoints)
214 215 216 217 218
    cv2.imwrite("vis_skeleton.jpg", canvas)


if __name__ == "__main__":
    main()