From 7cb5bd47f5fd1994e9b429aab9f0fb18ebd88519 Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 12 May 2021 15:08:17 +0800 Subject: [PATCH 01/98] paf detector --- mmpose/core/evaluation/__init__.py | 7 +- mmpose/core/evaluation/bottom_up_eval.py | 210 +++++++++ .../datasets/bottom_up/bottom_up_coco.py | 20 +- mmpose/models/detectors/paf.py | 418 ++++++++++++++++++ 4 files changed, 646 insertions(+), 9 deletions(-) create mode 100644 mmpose/models/detectors/paf.py diff --git a/mmpose/core/evaluation/__init__.py b/mmpose/core/evaluation/__init__.py index f22953ab84..2ffd13f643 100644 --- a/mmpose/core/evaluation/__init__.py +++ b/mmpose/core/evaluation/__init__.py @@ -1,5 +1,6 @@ -from .bottom_up_eval import (aggregate_results, get_group_preds, - get_multi_stage_outputs) +from .bottom_up_eval import (aggregate_results, aggregate_results_paf, + get_group_preds, get_multi_stage_outputs, + get_multi_stage_outputs_paf) from .eval_hooks import DistEvalHook, EvalHook from .mesh_eval import compute_similarity_transform from .pose3d_eval import keypoint_mpjpe @@ -13,6 +14,8 @@ 'EvalHook', 'DistEvalHook', 'pose_pck_accuracy', 'keypoints_from_heatmaps', 'keypoints_from_regression', 'keypoint_pck_accuracy', 'keypoint_auc', 'keypoint_epe', 'get_group_preds', 'get_multi_stage_outputs', + 'get_multi_stage_outputs_paf', + 'aggregate_results_paf', 'aggregate_results', 'compute_similarity_transform', 'post_dark_udp', 'keypoint_mpjpe', 'keypoints_from_heatmaps3d', 'multilabel_classification_accuracy' diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 5d90027044..422ff40821 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -120,6 +120,156 @@ def get_multi_stage_outputs(outputs, return outputs, heatmaps, tags +def get_multi_stage_outputs_paf(outputs, + outputs_flip, + with_heatmaps, + with_pafs, + flip_index=None, + flip_index_paf=None, + project2image=True, + size_projected=None, + align_corners=False): + """Inference the model to get multi-stage outputs (heatmaps & pafs), and + resize them to base sizes. + + Args: + outputs (list(torch.Tensor)): Outputs of network + outputs_flip (list(torch.Tensor)): Flip outputs of network + with_heatmaps (list[bool]): Option to output + heatmaps for different stages. + with_pafs (list[bool]): Option to output + pafs for different stages. + flip_index (list[int]): Keypoint flip index. + flip_index_paf (list[int]): PAF flip index. + project2image (bool): Option to resize to base scale. + size_projected ([w, h]): Base size of heatmaps. + align_corners (bool): Align corners when performing interpolation. + + Returns: + tuple: A tuple containing multi-stage outputs. + + - outputs (list(torch.Tensor)): List of simple outputs and + flip outputs. + - heatmaps (torch.Tensor): Multi-stage heatmaps that are resized to + the base size. + - pafs (torch.Tensor): Multi-stage pafs that are resized to + the base size. + """ + + heatmaps = [] + pafs = [] + + flip_test = outputs_flip is not None + + # aggregate heatmaps from different stages + heatmaps_avg = 0 + num_heatmaps = 0 + + for i, output in enumerate(outputs['heatmaps']): + if i != len(outputs['heatmaps']) - 1: + output = torch.nn.functional.interpolate( + output, + size=(outputs['heatmaps'][-1].size(2), + outputs['heatmaps'][-1].size(3)), + mode='bilinear', + align_corners=align_corners) + + if with_heatmaps[i]: + heatmaps_avg += output + num_heatmaps += 1 + + if num_heatmaps > 0: + heatmaps.append(heatmaps_avg / num_heatmaps) + + # aggregate pafs from different stages + pafs_avg = 0 + num_pafs = 0 + + for i, output in enumerate(outputs['pafs']): + if i != len(outputs['pafs']) - 1: + output = torch.nn.functional.interpolate( + output, + size=(outputs['pafs'][-1].size(2), + outputs['pafs'][-1].size(3)), + mode='bilinear', + align_corners=align_corners) + + if with_pafs[i]: + pafs_avg += output + num_pafs += 1 + + if num_pafs > 0: + pafs.append(pafs_avg / num_pafs) + + if flip_test: + if flip_index: + # perform flip testing for heatmaps + heatmaps_avg = 0 + num_heatmaps = 0 + + for i, output in enumerate(outputs_flip['heatmaps']): + if i != len(outputs_flip['heatmaps']) - 1: + output = torch.nn.functional.interpolate( + output, + size=(outputs_flip['heatmaps'][-1].size(2), + outputs_flip['heatmaps'][-1].size(3)), + mode='bilinear', + align_corners=align_corners) + output = torch.flip(output, [3]) + outputs['heatmaps'].append(output) + + if with_heatmaps[i]: + heatmaps_avg += output[:, flip_index, :, :] + num_heatmaps += 1 + + heatmaps.append(heatmaps_avg / num_heatmaps) + + if flip_index_paf: + # perform flip testing for pafs + pafs_avg = 0 + num_pafs = 0 + + for i, output in enumerate(outputs_flip['pafs']): + if i != len(outputs_flip['pafs']) - 1: + output = torch.nn.functional.interpolate( + output, + size=(outputs_flip['pafs'][-1].size(2), + outputs_flip['pafs'][-1].size(3)), + mode='bilinear', + align_corners=align_corners) + output = torch.flip(output, [3]) + outputs['pafs'].append(output) + + if with_pafs[i]: + pafs_avg[:, ::2, :, :] -= output[:, + flip_index_paf[::2], :, :] + pafs_avg[:, + 1::2, :, :] += output[:, + flip_index_paf[1::2], :, :] + num_pafs += 1 + + pafs.append(pafs_avg / num_pafs) + + if project2image and size_projected: + heatmaps = [ + torch.nn.functional.interpolate( + hms, + size=(size_projected[1], size_projected[0]), + mode='bilinear', + align_corners=align_corners) for hms in heatmaps + ] + + pafs = [ + torch.nn.functional.interpolate( + pms, + size=(size_projected[1], size_projected[0]), + mode='bilinear', + align_corners=align_corners) for pms in pafs + ] + + return outputs, heatmaps, pafs + + def aggregate_results(scale, aggregated_heatmaps, tags_list, @@ -184,6 +334,66 @@ def aggregate_results(scale, return aggregated_heatmaps, tags_list +def aggregate_results_paf(aggregated_heatmaps, + aggregated_pafs, + heatmaps, + pafs, + project2image, + flip_test, + align_corners=False): + """Aggregate multi-scale outputs. + + Note: + batch size: N + keypoints num : K + paf maps num: P + heatmap width: W + heatmap height: H + + Args: + aggregated_heatmaps (torch.Tensor | None): Aggregated heatmaps. + aggregated_pafs (torch.Tensor | None): Aggregated pafs. + heatmaps (List(torch.Tensor[NxKxWxH])): A batch of heatmaps. + pafs (List(torch.Tensor[NxPxWxH])): A batch of paf maps. + project2image (bool): Option to resize to base scale. + flip_test (bool): Option to use flip test. + align_corners (bool): Align corners when performing interpolation. + + Return: + tuple: a tuple containing aggregated results. + + - aggregated_heatmaps (torch.Tensor): Heatmaps with multi scale. + - aggregated_pafs (torch.Tensor): PAF maps of multi scale. + """ + + heatmaps_avg = (heatmaps[0] + + heatmaps[1]) / 2.0 if flip_test else heatmaps[0] + if aggregated_heatmaps is None: + aggregated_heatmaps = heatmaps_avg + elif project2image: + aggregated_heatmaps += heatmaps_avg + else: + aggregated_heatmaps += torch.nn.functional.interpolate( + heatmaps_avg, + size=(aggregated_heatmaps.size(2), aggregated_heatmaps.size(3)), + mode='bilinear', + align_corners=align_corners) + + pafs_avg = (pafs[0] + pafs[1]) / 2.0 if flip_test else pafs[0] + if aggregated_pafs is None: + aggregated_pafs = pafs_avg + elif project2image: + aggregated_pafs += pafs_avg + else: + aggregated_pafs += torch.nn.functional.interpolate( + pafs_avg, + size=(aggregated_pafs.size(2), aggregated_pafs.size(3)), + mode='bilinear', + align_corners=align_corners) + + return aggregated_heatmaps, aggregated_pafs + + def get_group_preds(grouped_joints, center, scale, diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index 02fe73a816..a063719763 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -61,6 +61,19 @@ def __init__(self, 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15 ] + # joint index starts from 1 + self.ann_info['skeleton'] = [[16, 14], [14, 12], [17, 15], [15, 13], + [12, 13], [6, 12], [7, 13], [6, 7], + [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], + [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], + [5, 7]] + + self.ann_info['flip_index_paf'] = [ + 4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 12, 13, 10, 11, 14, 15, 18, 19, 16, + 17, 22, 23, 20, 21, 24, 25, 28, 29, 26, 27, 32, 33, 30, 31, 36, 37, + 34, 35 + ] + self.ann_info['use_different_joint_weights'] = False self.ann_info['joint_weights'] = np.array( [ @@ -69,13 +82,6 @@ def __init__(self, ], dtype=np.float32).reshape((self.ann_info['num_joints'], 1)) - # joint index starts from 1 - self.ann_info['skeleton'] = [[16, 14], [14, 12], [17, 15], [15, 13], - [12, 13], [6, 12], [7, 13], [6, 7], - [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], - [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], - [5, 7]] - # 'https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/' # 'pycocotools/cocoeval.py#L523' self.sigmas = np.array([ diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py new file mode 100644 index 0000000000..dd2bcdb2c2 --- /dev/null +++ b/mmpose/models/detectors/paf.py @@ -0,0 +1,418 @@ +import math +import warnings + +import cv2 +import mmcv +import numpy as np +import torch +from mmcv.image import imwrite +from mmcv.visualization.image import imshow + +from mmpose.core.evaluation import (aggregate_results_paf, get_group_preds, + get_multi_stage_outputs_paf) +from mmpose.core.post_processing.group import HeatmapParser +from .. import builder +from ..registry import POSENETS +from .base import BasePose + + +@POSENETS.register_module() +class BottomUp(BasePose): + """Bottom-up pose detectors. + + Args: + backbone (dict): Backbone modules to extract feature. + keypoint_head (dict): Keypoint head to process feature. + train_cfg (dict): Config for training. Default: None. + test_cfg (dict): Config for testing. Default: None. + pretrained (str): Path to the pretrained models. + loss_pose (None): Deprecated arguments. Please use + `loss_keypoint` for heads instead. + """ + + def __init__(self, + backbone, + keypoint_head=None, + train_cfg=None, + test_cfg=None, + pretrained=None, + loss_pose=None): + super().__init__() + + self.backbone = builder.build_backbone(backbone) + + if keypoint_head is not None: + + if 'loss_keypoint' not in keypoint_head and loss_pose is not None: + warnings.warn( + '`loss_pose` for BottomUp is deprecated, ' + 'use `loss_keypoint` for heads instead. See ' + 'https://github.com/open-mmlab/mmpose/pull/382' + ' for more information.', DeprecationWarning) + keypoint_head['loss_keypoint'] = loss_pose + + self.keypoint_head = builder.build_head(keypoint_head) + + self.train_cfg = train_cfg + self.test_cfg = test_cfg + self.use_udp = test_cfg.get('use_udp', False) + self.parser = HeatmapParser(self.test_cfg) + self.init_weights(pretrained=pretrained) + + @property + def with_keypoint(self): + """Check if has keypoint_head.""" + return hasattr(self, 'keypoint_head') + + def init_weights(self, pretrained=None): + """Weight initialization for model.""" + self.backbone.init_weights(pretrained) + if self.with_keypoint: + self.keypoint_head.init_weights() + + def forward(self, + img=None, + targets=None, + masks=None, + joints=None, + img_metas=None, + return_loss=True, + return_heatmap=False, + **kwargs): + """Calls either forward_train or forward_test depending on whether + return_loss is True. + Note: + batch_size: N + num_keypoints: K + num_img_channel: C + img_width: imgW + img_height: imgH + heatmaps weight: W + heatmaps height: H + max_num_people: M + Args: + img(torch.Tensor[NxCximgHximgW]): Input image. + targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target + heatmaps + joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target + heatmaps for ae loss + img_metas(dict):Information about val&test + By default this includes: + - "image_file": image path + - "aug_data": input + - "test_scale_factor": test scale factor + - "base_size": base size of input + - "center": center of image + - "scale": scale of image + - "flip_index": flip index of keypoints + + return loss(bool): Option to 'return_loss'. 'return_loss=True' for + training, 'return_loss=False' for validation & test + return_heatmap (bool) : Option to return heatmap. + + Returns: + dict|tuple: if 'return_loss' is true, then return losses. + Otherwise, return predicted poses, scores, image + paths and heatmaps. + """ + + if return_loss: + return self.forward_train(img, targets, masks, joints, img_metas, + **kwargs) + return self.forward_test( + img, img_metas, return_heatmap=return_heatmap, **kwargs) + + def forward_train(self, img, targets, masks, joints, img_metas, **kwargs): + """Forward the bottom-up model and calculate the loss. + + Note: + batch_size: N + num_keypoints: K + num_img_channel: C + img_width: imgW + img_height: imgH + heatmaps weight: W + heatmaps height: H + max_num_people: M + + Args: + img(torch.Tensor[NxCximgHximgW]): Input image. + targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target + heatmaps + joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target + heatmaps for ae loss + img_metas(dict):Information about val&test + By default this includes: + - "image_file": image path + - "aug_data": input + - "test_scale_factor": test scale factor + - "base_size": base size of input + - "center": center of image + - "scale": scale of image + - "flip_index": flip index of keypoints + + Returns: + dict: The total loss for bottom-up + """ + + output = self.backbone(img) + + if self.with_keypoint: + output = self.keypoint_head(output) + + # if return loss + losses = dict() + if self.with_keypoint: + keypoint_losses = self.keypoint_head.get_loss( + output, targets, masks, joints) + losses.update(keypoint_losses) + + return losses + + def forward_dummy(self, img): + """Used for computing network FLOPs. + + See ``tools/get_flops.py``. + + Args: + img (torch.Tensor): Input image. + + Returns: + Tensor: Outputs. + """ + output = self.backbone(img) + if self.with_keypoint: + output = self.keypoint_head(output) + return output + + def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): + """Inference the bottom-up model. + + Note: + Batchsize = N (currently support batchsize = 1) + num_img_channel: C + img_width: imgW + img_height: imgH + + Args: + flip_index (List(int)): + aug_data (List(Tensor[NxCximgHximgW])): Multi-scale image + test_scale_factor (List(float)): Multi-scale factor + base_size (Tuple(int)): Base size of image when scale is 1 + center (np.ndarray): center of image + scale (np.ndarray): the scale of image + """ + assert img.size(0) == 1 + assert len(img_metas) == 1 + + img_metas = img_metas[0] + + aug_data = img_metas['aug_data'] + + test_scale_factor = img_metas['test_scale_factor'] + base_size = img_metas['base_size'] + center = img_metas['center'] + scale = img_metas['scale'] + + result = {} + + aggregated_heatmaps = None + aggregated_pafs = None + for idx, s in enumerate(sorted(test_scale_factor, reverse=True)): + image_resized = aug_data[idx].to(img.device) + + features = self.backbone(image_resized) + if self.with_keypoint: + outputs = self.keypoint_head(features) + + if self.test_cfg.get('flip_test', True): + # use flip test + features_flipped = self.backbone( + torch.flip(image_resized, [3])) + if self.with_keypoint: + outputs_flipped = self.keypoint_head(features_flipped) + else: + outputs_flipped = None + + _, heatmaps, pafs = get_multi_stage_outputs_paf( + outputs, + outputs_flipped, + self.test_cfg['with_heatmaps'], + self.test_cfg['with_ae'], + img_metas['flip_index'], + img_metas['flip_index_paf'], + self.test_cfg['project2image'], + base_size, + align_corners=self.use_udp) + + aggregated_heatmaps, aggregated_pafs = aggregate_results_paf( + aggregated_heatmaps, + aggregated_pafs, + heatmaps, + pafs, + self.test_cfg['project2image'], + self.test_cfg.get('flip_test', True), + align_corners=self.use_udp) + + # average heatmaps of different scales + aggregated_heatmaps = aggregated_heatmaps / float( + len(test_scale_factor)) + tags = torch.cat(pafs, dim=4) + + # perform grouping + grouped, scores = self.parser.parse(aggregated_heatmaps, tags, + self.test_cfg['adjust'], + self.test_cfg['refine']) + + preds = get_group_preds( + grouped, + center, + scale, [aggregated_heatmaps.size(3), + aggregated_heatmaps.size(2)], + use_udp=self.use_udp) + + image_paths = [] + image_paths.append(img_metas['image_file']) + + if return_heatmap: + output_heatmap = aggregated_heatmaps.detach().cpu().numpy() + else: + output_heatmap = None + + result['preds'] = preds + result['scores'] = scores + result['image_paths'] = image_paths + result['output_heatmap'] = output_heatmap + + return result + + def show_result(self, + img, + result, + skeleton=None, + kpt_score_thr=0.3, + pose_kpt_color=None, + pose_limb_color=None, + radius=4, + thickness=1, + font_scale=0.5, + win_name='', + show=False, + show_keypoint_weight=False, + wait_time=0, + out_file=None): + """Draw `result` over `img`. + + Args: + img (str or Tensor): The image to be displayed. + result (list[dict]): The results to draw over `img` + (bbox_result, pose_result). + kpt_score_thr (float, optional): Minimum score of keypoints + to be shown. Default: 0.3. + pose_kpt_color (np.array[Nx3]`): Color of N keypoints. + If None, do not draw keypoints. + pose_limb_color (np.array[Mx3]): Color of M limbs. + If None, do not draw limbs. + thickness (int): Thickness of lines. + font_scale (float): Font scales of texts. + win_name (str): The window name. + wait_time (int): Value of waitKey param. + Default: 0. + out_file (str or None): The filename to write the image. + Default: None. + + Returns: + Tensor: Visualized image only if not `show` or `out_file` + """ + + img = mmcv.imread(img) + img = img.copy() + img_h, img_w, _ = img.shape + + pose_result = [] + for res in result: + pose_result.append(res['keypoints']) + + for _, kpts in enumerate(pose_result): + # draw each point on image + if pose_kpt_color is not None: + assert len(pose_kpt_color) == len(kpts) + for kid, kpt in enumerate(kpts): + x_coord, y_coord, kpt_score = int(kpt[0]), int( + kpt[1]), kpt[2] + if kpt_score > kpt_score_thr: + if show_keypoint_weight: + img_copy = img.copy() + r, g, b = pose_kpt_color[kid] + cv2.circle(img_copy, (int(x_coord), int(y_coord)), + radius, (int(r), int(g), int(b)), -1) + transparency = max(0, min(1, kpt_score)) + cv2.addWeighted( + img_copy, + transparency, + img, + 1 - transparency, + 0, + dst=img) + else: + r, g, b = pose_kpt_color[kid] + cv2.circle(img, (int(x_coord), int(y_coord)), + radius, (int(r), int(g), int(b)), -1) + + # draw limbs + if skeleton is not None and pose_limb_color is not None: + assert len(pose_limb_color) == len(skeleton) + for sk_id, sk in enumerate(skeleton): + pos1 = (int(kpts[sk[0] - 1, 0]), int(kpts[sk[0] - 1, 1])) + pos2 = (int(kpts[sk[1] - 1, 0]), int(kpts[sk[1] - 1, 1])) + if (pos1[0] > 0 and pos1[0] < img_w and pos1[1] > 0 + and pos1[1] < img_h and pos2[0] > 0 + and pos2[0] < img_w and pos2[1] > 0 + and pos2[1] < img_h + and kpts[sk[0] - 1, 2] > kpt_score_thr + and kpts[sk[1] - 1, 2] > kpt_score_thr): + r, g, b = pose_limb_color[sk_id] + if show_keypoint_weight: + img_copy = img.copy() + X = (pos1[0], pos2[0]) + Y = (pos1[1], pos2[1]) + mX = np.mean(X) + mY = np.mean(Y) + length = ((Y[0] - Y[1])**2 + (X[0] - X[1])**2)**0.5 + angle = math.degrees( + math.atan2(Y[0] - Y[1], X[0] - X[1])) + stickwidth = 2 + polygon = cv2.ellipse2Poly( + (int(mX), int(mY)), + (int(length / 2), int(stickwidth)), int(angle), + 0, 360, 1) + cv2.fillConvexPoly(img_copy, polygon, + (int(r), int(g), int(b))) + transparency = max( + 0, + min( + 1, 0.5 * + (kpts[sk[0] - 1, 2] + kpts[sk[1] - 1, 2]))) + cv2.addWeighted( + img_copy, + transparency, + img, + 1 - transparency, + 0, + dst=img) + else: + cv2.line( + img, + pos1, + pos2, (int(r), int(g), int(b)), + thickness=thickness) + + if show: + imshow(img, win_name, wait_time) + + if out_file is not None: + imwrite(img, out_file) + + return img From 970005686746a24ce232ab8312ded9556d375df2 Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 18 May 2021 23:49:36 +0800 Subject: [PATCH 02/98] add paf detector & head & loss --- mmpose/core/evaluation/bottom_up_eval.py | 5 +- mmpose/core/post_processing/group.py | 269 ++++++++++++++++++ mmpose/models/detectors/paf.py | 33 +-- .../models/heads/ae_higher_resolution_head.py | 16 +- mmpose/models/heads/ae_simple_head.py | 10 +- mmpose/models/keypoint_heads/__init__.py | 7 + mmpose/models/keypoint_heads/paf_head.py | 108 +++++++ .../models/keypoint_heads/paf_simple_head.py | 171 +++++++++++ mmpose/models/losses/mse_loss.py | 28 ++ 9 files changed, 614 insertions(+), 33 deletions(-) create mode 100644 mmpose/models/keypoint_heads/__init__.py create mode 100644 mmpose/models/keypoint_heads/paf_head.py create mode 100644 mmpose/models/keypoint_heads/paf_simple_head.py diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 422ff40821..fb37a3373b 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -133,8 +133,9 @@ def get_multi_stage_outputs_paf(outputs, resize them to base sizes. Args: - outputs (list(torch.Tensor)): Outputs of network - outputs_flip (list(torch.Tensor)): Flip outputs of network + outputs (dict): Outputs of network, including heatmaps and pafs. + outputs_flip (dict): Flip outputs of network, including + heatmaps and pafs. with_heatmaps (list[bool]): Option to output heatmaps for different stages. with_pafs (list[bool]): Option to output diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 9a870d6ce3..7063c6ee64 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -404,3 +404,272 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): ans = [ans] return ans, scores + + +class PAFParser: + """The paf parser for post processing.""" + + def __init__(self, cfg): + self.params = _Params(cfg) + self.tag_per_joint = cfg['tag_per_joint'] + self.pool = torch.nn.MaxPool2d(cfg['nms_kernel'], 1, + cfg['nms_padding']) + self.use_udp = cfg.get('use_udp', False) + + # def nms(self, heatmaps): + # """Non-Maximum Suppression for heatmaps. + # + # Args: + # heatmap(torch.Tensor): Heatmaps before nms. + # + # Returns: + # torch.Tensor: Heatmaps after nms. + # """ + # + # maxm = self.pool(heatmaps) + # maxm = torch.eq(maxm, heatmaps).float() + # heatmaps = heatmaps * maxm + # + # return heatmaps + # + # def match(self, tag_k, loc_k, val_k): + # """Group keypoints to human poses in a batch. + # + # Args: + # tag_k (np.ndarray[NxKxMxL]): tag corresponding to the + # top k values of feature map per keypoint. + # loc_k (np.ndarray[NxKxMx2]): top k locations of the + # feature maps for keypoint. + # val_k (np.ndarray[NxKxM]): top k value of the + # feature maps per keypoint. + # + # Returns: + # list + # """ + # + # def _match(x): + # return _match_by_tag(x, self.params) + # + # return list(map(_match, zip(tag_k, loc_k, val_k))) + # + # def top_k(self, heatmaps, tags): + # """Find top_k values in an image. + # + # Note: + # batch size: N + # number of keypoints: K + # heatmap height: H + # heatmap width: W + # max number of people: M + # dim of tags: L + # If use flip testing, L=2; else L=1. + # + # Args: + # heatmaps (torch.Tensor[NxKxHxW]) + # tags (torch.Tensor[NxKxHxWxL]) + # + # Return: + # dict: A dict containing top_k values. + # + # - tag_k (np.ndarray[NxKxMxL]): + # tag corresponding to the top k values of + # feature map per keypoint. + # - loc_k (np.ndarray[NxKxMx2]): + # top k location of feature map per keypoint. + # - val_k (np.ndarray[NxKxM]): + # top k value of feature map per keypoint. + # """ + # heatmaps = self.nms(heatmaps) + # N, K, H, W = heatmaps.size() + # heatmaps = heatmaps.view(N, K, -1) + # val_k, ind = heatmaps.topk(self.params.max_num_people, dim=2) + # + # tags = tags.view(tags.size(0), tags.size(1), W * H, -1) + # if not self.tag_per_joint: + # tags = tags.expand(-1, self.params.num_joints, -1, -1) + # + # tag_k = torch.stack( + # [torch.gather(tags[..., i], 2, ind) for i in + # range(tags.size(3))], + # dim=3) + # + # x = ind % W + # y = ind // W + # + # ind_k = torch.stack((x, y), dim=3) + # + # ans = { + # 'tag_k': tag_k.cpu().numpy(), + # 'loc_k': ind_k.cpu().numpy(), + # 'val_k': val_k.cpu().numpy() + # } + # + # return ans + # + # @staticmethod + # def adjust(ans, heatmaps): + # """Adjust the coordinates for better accuracy. + # + # Note: + # batch size: N + # number of keypoints: K + # heatmap height: H + # heatmap width: W + # + # Args: + # ans (list(np.ndarray)): Keypoint predictions. + # heatmaps (torch.Tensor[NxKxHxW]): Heatmaps. + # """ + # _, _, H, W = heatmaps.shape + # for batch_id, people in enumerate(ans): + # for people_id, people_i in enumerate(people): + # for joint_id, joint in enumerate(people_i): + # if joint[2] > 0: + # x, y = joint[0:2] + # xx, yy = int(x), int(y) + # tmp = heatmaps[batch_id][joint_id] + # if tmp[min(H - 1, yy + 1), xx] > tmp[max(0, yy - 1), + # xx]: + # y += 0.25 + # else: + # y -= 0.25 + # + # if tmp[yy, min(W - 1, xx + 1)] > tmp[yy, + # max(0, xx - 1)]: + # x += 0.25 + # else: + # x -= 0.25 + # ans[batch_id][people_id, joint_id, + # 0:2] = (x + 0.5, y + 0.5) + # return ans + # + # @staticmethod + # def refine(heatmap, tag, keypoints, use_udp=False): + # """Given initial keypoint predictions, we identify missing joints. + # + # Note: + # number of keypoints: K + # heatmap height: H + # heatmap width: W + # dim of tags: L + # If use flip testing, L=2; else L=1. + # + # Args: + # heatmap: np.ndarray(K, H, W). + # tag: np.ndarray(K, H, W) | np.ndarray(K, H, W, L) + # keypoints: np.ndarray of size (K, 3 + L) + # last dim is (x, y, score, tag). + # use_udp: bool-unbiased data processing + # + # Returns: + # np.ndarray: The refined keypoints. + # """ + # + # K, H, W = heatmap.shape + # if len(tag.shape) == 3: + # tag = tag[..., None] + # + # tags = [] + # for i in range(K): + # if keypoints[i, 2] > 0: + # # save tag value of detected keypoint + # x, y = keypoints[i][:2].astype(int) + # x = np.clip(x, 0, W - 1) + # y = np.clip(y, 0, H - 1) + # tags.append(tag[i, y, x]) + # + # # mean tag of current detected people + # prev_tag = np.mean(tags, axis=0) + # ans = [] + # + # for _heatmap, _tag in zip(heatmap, tag): + # # distance of all tag values with mean tag of + # # current detected people + # distance_tag = (((_tag - + # prev_tag[None, None, :])**2).sum(axis=2)**0.5) + # norm_heatmap = _heatmap - np.round(distance_tag) + # + # # find maximum position + # y, x = np.unravel_index(np.argmax(norm_heatmap), _heatmap.shape) + # xx = x.copy() + # yy = y.copy() + # # detection score at maximum position + # val = _heatmap[y, x] + # if not use_udp: + # # offset by 0.5 + # x += 0.5 + # y += 0.5 + # + # # add a quarter offset + # if _heatmap[yy, min(W - 1, xx + 1)] > _ + # heatmap[yy, max(0, xx - 1)]: + # x += 0.25 + # else: + # x -= 0.25 + # + # if _heatmap[min(H - 1, yy + 1), xx] > _ + # heatmap[max(0, yy - 1), xx]: + # y += 0.25 + # else: + # y -= 0.25 + # + # ans.append((x, y, val)) + # ans = np.array(ans) + # + # if ans is not None: + # for i in range(K): + # # add keypoint if it is not detected + # if ans[i, 2] > 0 and keypoints[i, 2] == 0: + # keypoints[i, :3] = ans[i, :3] + # + # return keypoints + + def parse(self, heatmaps, pafs, adjust=True, refine=True): + """Group keypoints into poses given heatmap and paf. + + Note: + batch size: N + number of keypoints: K + number of paf maps: P + heatmap height: H + heatmap width: W + + Args: + heatmaps (torch.Tensor[NxKxHxW]): model output heatmaps. + pafs (torch.Tensor[NxPxHxW]): model output pafs. + + Returns: + tuple: A tuple containing keypoint grouping results. + + - ans (list(np.ndarray)): Pose results. + - scores (list): Score of people. + """ + + assert 0, 'The post-process of paf have not been completed.' + # ans = self.match(**self.top_k(heatmaps, pafs)) + # + # if adjust: + # if self.use_udp: + # for i in range(len(ans)): + # if ans[i].shape[0] > 0: + # ans[i][..., :2] = post_dark_udp( + # ans[i][..., :2].copy(), heatmaps[i:i + 1, :]) + # else: + # ans = self.adjust(ans, heatmaps) + # + # scores = [i[:, 2].mean() for i in ans[0]] + # + # if refine: + # ans = ans[0] + # # for every detected person + # for i in range(len(ans)): + # heatmap_numpy = heatmaps[0].cpu().numpy() + # tag_numpy = tags[0].cpu().numpy() + # if not self.tag_per_joint: + # tag_numpy = np.tile(tag_numpy, + # (self.params.num_joints, 1, 1, 1)) + # ans[i] = self.refine( + # heatmap_numpy, tag_numpy, ans[i], use_udp=self.use_udp) + # ans = [ans] + # + # return ans, scores diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index dd2bcdb2c2..74518766f5 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -10,7 +10,7 @@ from mmpose.core.evaluation import (aggregate_results_paf, get_group_preds, get_multi_stage_outputs_paf) -from mmpose.core.post_processing.group import HeatmapParser +from mmpose.core.post_processing.group import PAFParser from .. import builder from ..registry import POSENETS from .base import BasePose @@ -56,7 +56,7 @@ def __init__(self, self.train_cfg = train_cfg self.test_cfg = test_cfg self.use_udp = test_cfg.get('use_udp', False) - self.parser = HeatmapParser(self.test_cfg) + self.parser = PAFParser(self.test_cfg) self.init_weights(pretrained=pretrained) @property @@ -74,7 +74,6 @@ def forward(self, img=None, targets=None, masks=None, - joints=None, img_metas=None, return_loss=True, return_heatmap=False, @@ -92,11 +91,10 @@ def forward(self, max_num_people: M Args: img(torch.Tensor[NxCximgHximgW]): Input image. - targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + targets (list(list)): List of heatmaps and pafs, each of which + multi-scale targets. masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps - joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target - heatmaps for ae loss + heatmaps. img_metas(dict):Information about val&test By default this includes: - "image_file": image path @@ -118,12 +116,11 @@ def forward(self, """ if return_loss: - return self.forward_train(img, targets, masks, joints, img_metas, - **kwargs) + return self.forward_train(img, targets, masks, img_metas, **kwargs) return self.forward_test( img, img_metas, return_heatmap=return_heatmap, **kwargs) - def forward_train(self, img, targets, masks, joints, img_metas, **kwargs): + def forward_train(self, img, targets, masks, img_metas, **kwargs): """Forward the bottom-up model and calculate the loss. Note: @@ -138,11 +135,10 @@ def forward_train(self, img, targets, masks, joints, img_metas, **kwargs): Args: img(torch.Tensor[NxCximgHximgW]): Input image. - targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + targets (list(list)): List of heatmaps and pafs, each of which + multi-scale targets. masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps - joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target - heatmaps for ae loss + heatmaps. img_metas(dict):Information about val&test By default this includes: - "image_file": image path @@ -166,7 +162,7 @@ def forward_train(self, img, targets, masks, joints, img_metas, **kwargs): losses = dict() if self.with_keypoint: keypoint_losses = self.keypoint_head.get_loss( - output, targets, masks, joints) + output, targets, masks) losses.update(keypoint_losses) return losses @@ -240,7 +236,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): outputs, outputs_flipped, self.test_cfg['with_heatmaps'], - self.test_cfg['with_ae'], + self.test_cfg['with_pafs'], img_metas['flip_index'], img_metas['flip_index_paf'], self.test_cfg['project2image'], @@ -259,10 +255,11 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): # average heatmaps of different scales aggregated_heatmaps = aggregated_heatmaps / float( len(test_scale_factor)) - tags = torch.cat(pafs, dim=4) + aggregated_pafs = aggregated_pafs / float(len(test_scale_factor)) # perform grouping - grouped, scores = self.parser.parse(aggregated_heatmaps, tags, + grouped, scores = self.parser.parse(aggregated_heatmaps, + aggregated_pafs, self.test_cfg['adjust'], self.test_cfg['refine']) diff --git a/mmpose/models/heads/ae_higher_resolution_head.py b/mmpose/models/heads/ae_higher_resolution_head.py index a4c7a55036..3db493e138 100644 --- a/mmpose/models/heads/ae_higher_resolution_head.py +++ b/mmpose/models/heads/ae_higher_resolution_head.py @@ -171,7 +171,7 @@ def _get_deconv_cfg(deconv_kernel): return deconv_kernel, padding, output_padding - def get_loss(self, output, targets, masks, joints): + def get_loss(self, outputs, targets, masks, joints): """Calculate bottom-up keypoint loss. Note: @@ -182,18 +182,18 @@ def get_loss(self, output, targets, masks, joints): heatmaps weight: W Args: - output (torch.Tensor[NxKxHxW]): Output heatmaps. - targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. - masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps - joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target - heatmaps for ae loss + outputs (List(torch.Tensor[NxKxHxW])): Multi-scale output heatmaps. + targets (List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + masks (List(torch.Tensor[NxHxW])): Masks of multi-scale target + heatmaps + joints (List(torch.Tensor[NxMxKx2])): Joints of multi-scale target + heatmaps for ae loss """ losses = dict() heatmaps_losses, push_losses, pull_losses = self.loss( - output, targets, masks, joints) + outputs, targets, masks, joints) for idx in range(len(targets)): if heatmaps_losses[idx] is not None: diff --git a/mmpose/models/heads/ae_simple_head.py b/mmpose/models/heads/ae_simple_head.py index 6b90eecd3e..6d56c48a58 100644 --- a/mmpose/models/heads/ae_simple_head.py +++ b/mmpose/models/heads/ae_simple_head.py @@ -85,7 +85,7 @@ def __init__(self, stride=1, padding=padding) - def get_loss(self, output, targets, masks, joints): + def get_loss(self, outputs, targets, masks, joints): """Calculate bottom-up keypoint loss. Note: @@ -96,9 +96,9 @@ def get_loss(self, output, targets, masks, joints): heatmaps weight: W Args: - output (torch.Tensor[NxKxHxW]): Output heatmaps. - targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. - masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target + outputs (list(torch.Tensor[NxKxHxW])): Multi-scale output heatmaps. + targets (List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + masks (List(torch.Tensor[NxHxW])): Masks of multi-scale target heatmaps joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target heatmaps for ae loss @@ -107,7 +107,7 @@ def get_loss(self, output, targets, masks, joints): losses = dict() heatmaps_losses, push_losses, pull_losses = self.loss( - output, targets, masks, joints) + outputs, targets, masks, joints) for idx in range(len(targets)): if heatmaps_losses[idx] is not None: diff --git a/mmpose/models/keypoint_heads/__init__.py b/mmpose/models/keypoint_heads/__init__.py new file mode 100644 index 0000000000..c752b8a9fa --- /dev/null +++ b/mmpose/models/keypoint_heads/__init__.py @@ -0,0 +1,7 @@ +from .paf_head import PAFHead +from .paf_simple_head import PAFSimpleHead + +__all__ = [ + 'PAFHead', + 'PAFSimpleHead' +] diff --git a/mmpose/models/keypoint_heads/paf_head.py b/mmpose/models/keypoint_heads/paf_head.py new file mode 100644 index 0000000000..1cb32189be --- /dev/null +++ b/mmpose/models/keypoint_heads/paf_head.py @@ -0,0 +1,108 @@ +import torch.nn as nn + +from mmpose.models.builder import build_head +from ..registry import HEADS + + +@HEADS.register_module() +class PAFHead(nn.Module): + """Bottom-up PAF head. + + Args: + heatmap_heads_cfg (list(dict)): Configs of heatmap heads. + paf_heads_cfg (list(dict)): Configs of paf heads. + heatmap_index (list(int)): The correspondence between heatmap heads + and input features. + paf_index (list(int)): The correspondence between paf heads + and input features. + """ + + def __init__(self, heatmap_heads_cfg, paf_heads_cfg, heatmap_index, + paf_index): + super().__init__() + + assert len(heatmap_heads_cfg) == len(heatmap_index) + assert len(paf_heads_cfg) == len(paf_index) + + # build heatmap heads + self.heatmap_heads_list = [] + for head_cfg in heatmap_heads_cfg: + self.heatmap_heads_list.append(build_head(head_cfg)) + + # build paf heads + self.paf_heads_list = [] + for head_cfg in paf_heads_cfg: + self.paf_heads_list.append(build_head(head_cfg)) + + self.heatmap_index = heatmap_index + self.paf_index = paf_index + + def get_loss(self, outputs, targets, masks): + """Calculate heatmap and paf loss. + + Note: + batch_size: N + num_channels: C + heatmaps height: H + heatmaps weight: W + + Args: + outputs (dict): Outputs of network, including heatmaps and pafs. + targets (list(list)): List of heatmaps and pafs, each of which + multi-scale targets. + masks (list(torch.Tensor[NxHxW])): Masks of multi-scale target + heatmaps and pafs. + """ + + losses = dict() + + heatmap_outputs = outputs['heatmaps'] + heatmap_targets = targets[:len(self.heatmap_heads_list)] + for idx, head in enumerate(self.heatmap_heads_list): + heatmap_losses = head.get_loss(heatmap_outputs[idx], + heatmap_targets[idx], masks) + if 'heatmap_loss' not in losses: + losses['heatmap_loss'] = heatmap_losses['loss'] + else: + losses['heatmap_loss'] += heatmap_losses['loss'] + + paf_outputs = outputs['pafs'] + paf_targets = targets[len(self.heatmap_heads_list):] + for idx, head in enumerate(self.paf_heads_list): + paf_losses = head.get_loss(paf_outputs[idx], paf_targets[idx], + masks) + if 'paf_loss' not in losses: + losses['paf_loss'] = paf_losses['loss'] + else: + losses['paf_loss'] += paf_losses['loss'] + + return losses + + def forward(self, x): + """Forward function.""" + if not isinstance(x, list): + x = [x] + + assert max(self.heatmap_index) < len(x) + assert max(self.paf_index) < len(x) + + final_outputs = {'heatmaps': [], 'pafs': []} + + for idx, head in enumerate(self.heatmap_heads_list): + features = x[self.heatmap_index[idx]] + output = head(features) + final_outputs['heatmaps'].append(output) + + for idx, head in enumerate(self.paf_heads_list): + features = x[self.paf_index[idx]] + output = head(features) + final_outputs['pafs'].append(output) + + return final_outputs + + def init_weights(self): + for head in self.heatmap_heads_list: + head.init_weights() + + for head in self.paf_heads_list: + head.init_weights() diff --git a/mmpose/models/keypoint_heads/paf_simple_head.py b/mmpose/models/keypoint_heads/paf_simple_head.py new file mode 100644 index 0000000000..b78af28bfc --- /dev/null +++ b/mmpose/models/keypoint_heads/paf_simple_head.py @@ -0,0 +1,171 @@ +import torch.nn as nn +from mmcv.cnn import (build_conv_layer, build_upsample_layer, constant_init, + normal_init) + +from mmpose.models.builder import build_loss +from ..registry import HEADS + + +@HEADS.register_module() +class PAFSimpleHead(nn.Module): + """Bottom-up simple head. + + Args: + in_channels (int): Number of input channels. + num_joints (int): Number of joints. + num_deconv_layers (int): Number of deconv layers. + num_deconv_layers should >= 0. Note that 0 means + no deconv layers. + num_deconv_filters (list|tuple): Number of filters. + If num_deconv_layers > 0, the length of + num_deconv_kernels (list|tuple): Kernel sizes. + loss_keypoint (dict): Config for loss. Default: None. + """ + + def __init__(self, + in_channels, + num_joints, + num_deconv_layers=3, + num_deconv_filters=(256, 256, 256), + num_deconv_kernels=(4, 4, 4), + extra=None, + loss_keypoint=None): + super().__init__() + + self.loss = build_loss(loss_keypoint) + + self.in_channels = in_channels + out_channels = num_joints + + if extra is not None and not isinstance(extra, dict): + raise TypeError('extra should be dict or None.') + + if num_deconv_layers > 0: + self.deconv_layers = self._make_deconv_layer( + num_deconv_layers, + num_deconv_filters, + num_deconv_kernels, + ) + elif num_deconv_layers == 0: + self.deconv_layers = nn.Identity() + else: + raise ValueError( + f'num_deconv_layers ({num_deconv_layers}) should >= 0.') + + if extra is not None and 'final_conv_kernel' in extra: + assert extra['final_conv_kernel'] in [1, 3] + if extra['final_conv_kernel'] == 3: + padding = 1 + else: + padding = 0 + kernel_size = extra['final_conv_kernel'] + else: + kernel_size = 1 + padding = 0 + + self.final_layer = build_conv_layer( + cfg=dict(type='Conv2d'), + in_channels=num_deconv_filters[-1] + if num_deconv_layers > 0 else in_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1, + padding=padding) + + def get_loss(self, outputs, targets, masks): + """Calculate bottom-up masked mse loss. + + Note: + batch_size: N + num_channels: C + heatmaps height: H + heatmaps weight: W + + Args: + outputs (List(torch.Tensor[NxCxHxW])): Multi-scale outputs. + targets (List(torch.Tensor[NxCxHxW])): Multi-scale targets. + masks (List(torch.Tensor[NxHxW])): Masks of multi-scale targets. + """ + + losses = dict() + + for idx in range(len(targets)): + if 'loss' not in losses: + losses['loss'] = self.loss(outputs[idx], targets[idx], + masks[idx]) + else: + losses['loss'] += self.loss(outputs[idx], targets[idx], + masks[idx]) + + return losses + + def forward(self, x): + """Forward function.""" + if isinstance(x, list): + x = x[0] + final_outputs = [] + x = self.deconv_layers(x) + y = self.final_layer(x) + final_outputs.append(y) + return final_outputs + + def _make_deconv_layer(self, num_layers, num_filters, num_kernels): + """Make deconv layers.""" + if num_layers != len(num_filters): + error_msg = f'num_layers({num_layers}) ' \ + f'!= length of num_filters({len(num_filters)})' + raise ValueError(error_msg) + if num_layers != len(num_kernels): + error_msg = f'num_layers({num_layers}) ' \ + f'!= length of num_kernels({len(num_kernels)})' + raise ValueError(error_msg) + + layers = [] + for i in range(num_layers): + kernel, padding, output_padding = \ + self._get_deconv_cfg(num_kernels[i]) + + planes = num_filters[i] + layers.append( + build_upsample_layer( + dict(type='deconv'), + in_channels=self.in_channels, + out_channels=planes, + kernel_size=kernel, + stride=2, + padding=padding, + output_padding=output_padding, + bias=False)) + layers.append(nn.BatchNorm2d(planes)) + layers.append(nn.ReLU(inplace=True)) + self.in_channels = planes + + return nn.Sequential(*layers) + + @staticmethod + def _get_deconv_cfg(deconv_kernel): + """Get configurations for deconv layers.""" + if deconv_kernel == 4: + padding = 1 + output_padding = 0 + elif deconv_kernel == 3: + padding = 1 + output_padding = 1 + elif deconv_kernel == 2: + padding = 0 + output_padding = 0 + else: + raise ValueError(f'Not supported num_kernels ({deconv_kernel}).') + + return deconv_kernel, padding, output_padding + + def init_weights(self): + """Initialize model weights.""" + for _, m in self.deconv_layers.named_modules(): + if isinstance(m, nn.ConvTranspose2d): + normal_init(m, std=0.001) + elif isinstance(m, nn.BatchNorm2d): + constant_init(m, 1) + for m in self.final_layer.modules(): + if isinstance(m, nn.Conv2d): + normal_init(m, std=0.001, bias=0) diff --git a/mmpose/models/losses/mse_loss.py b/mmpose/models/losses/mse_loss.py index 4232d13590..693c723237 100644 --- a/mmpose/models/losses/mse_loss.py +++ b/mmpose/models/losses/mse_loss.py @@ -150,3 +150,31 @@ def forward(self, output, target, target_weight): losses = torch.cat(losses, dim=1) return self._ohkm(losses) * self.loss_weight + + +@LOSSES.register_module() +class MaskedMSELoss(nn.Module): + """MSE loss for the bottom-up outputs with mask. + + Args: + use_mask (bool): Option to use mask of target. Default: True. + loss_weight (float): Weight of the loss. Default: 1.0. + """ + + def __init__(self, use_mask=True, loss_weight=1.): + super().__init__() + self.criterion = nn.MSELoss() + self.use_mask = use_mask + self.loss_weight = loss_weight + + def forward(self, output, target, mask): + """Forward function.""" + assert output.size() == target.size() + + if self.use_mask: + loss = self.criterion( + output, target) * mask[:, None, :, :].expand_as(output) + else: + loss = self.criterion(output, target) + + return loss * self.loss_weight From cb1d9673cdbbd5e45d3380f7c27cfad903f91bfb Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 14:41:16 +0800 Subject: [PATCH 03/98] rename to PartAffinityField --- mmpose/models/detectors/__init__.py | 4 +++- mmpose/models/detectors/paf.py | 2 +- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/mmpose/models/detectors/__init__.py b/mmpose/models/detectors/__init__.py index 5420dfd1c6..588d98a038 100644 --- a/mmpose/models/detectors/__init__.py +++ b/mmpose/models/detectors/__init__.py @@ -2,10 +2,12 @@ from .interhand_3d import Interhand3D from .mesh import ParametricMesh from .multi_task import MultiTask +from .paf import PartAffinityField from .pose_lifter import PoseLifter from .top_down import TopDown __all__ = [ 'TopDown', 'AssociativeEmbedding', 'ParametricMesh', 'MultiTask', - 'PoseLifter', 'Interhand3D' + 'PoseLifter', 'Interhand3D', + 'PartAffinityField' ] diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 74518766f5..3ca9bba4d5 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -17,7 +17,7 @@ @POSENETS.register_module() -class BottomUp(BasePose): +class PartAffinityField(BasePose): """Bottom-up pose detectors. Args: From 1629b70e9610c71c32cd091f5bd6fa5428803791 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 19:10:13 +0800 Subject: [PATCH 04/98] rebase master --- mmpose/core/evaluation/__init__.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/mmpose/core/evaluation/__init__.py b/mmpose/core/evaluation/__init__.py index 2ffd13f643..7ee250465e 100644 --- a/mmpose/core/evaluation/__init__.py +++ b/mmpose/core/evaluation/__init__.py @@ -14,8 +14,7 @@ 'EvalHook', 'DistEvalHook', 'pose_pck_accuracy', 'keypoints_from_heatmaps', 'keypoints_from_regression', 'keypoint_pck_accuracy', 'keypoint_auc', 'keypoint_epe', 'get_group_preds', 'get_multi_stage_outputs', - 'get_multi_stage_outputs_paf', - 'aggregate_results_paf', + 'get_multi_stage_outputs_paf', 'aggregate_results_paf', 'aggregate_results', 'compute_similarity_transform', 'post_dark_udp', 'keypoint_mpjpe', 'keypoints_from_heatmaps3d', 'multilabel_classification_accuracy' From d6f36b909a91ee5c1aeb0cd7c52e8e7798bcc426 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 19:30:07 +0800 Subject: [PATCH 05/98] add paper ref --- mmpose/core/post_processing/group.py | 6 +++++- mmpose/models/keypoint_heads/paf_head.py | 3 +++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 7063c6ee64..01e11e410e 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -407,7 +407,11 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): class PAFParser: - """The paf parser for post processing.""" + """The paf parser for post processing. + + Paper ref: Cao, Zhe, et al. "OpenPose: realtime multi-person 2D pose + estimation using Part Affinity Fields." (TPAMI'2019) + """ def __init__(self, cfg): self.params = _Params(cfg) diff --git a/mmpose/models/keypoint_heads/paf_head.py b/mmpose/models/keypoint_heads/paf_head.py index 1cb32189be..2973965795 100644 --- a/mmpose/models/keypoint_heads/paf_head.py +++ b/mmpose/models/keypoint_heads/paf_head.py @@ -8,6 +8,9 @@ class PAFHead(nn.Module): """Bottom-up PAF head. + Paper ref: Cao, Zhe, et al. "OpenPose: realtime multi-person + 2D pose estimation using Part Affinity Fields." (TPAMI'2019) + Args: heatmap_heads_cfg (list(dict)): Configs of heatmap heads. paf_heads_cfg (list(dict)): Configs of paf heads. From bb41c491cf86792bacaae0c218c6f54fc330e1f5 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 19:39:49 +0800 Subject: [PATCH 06/98] fix tab indent --- mmpose/models/heads/ae_higher_resolution_head.py | 4 ++-- mmpose/models/heads/ae_simple_head.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/mmpose/models/heads/ae_higher_resolution_head.py b/mmpose/models/heads/ae_higher_resolution_head.py index 3db493e138..fc510f9f86 100644 --- a/mmpose/models/heads/ae_higher_resolution_head.py +++ b/mmpose/models/heads/ae_higher_resolution_head.py @@ -185,9 +185,9 @@ def get_loss(self, outputs, targets, masks, joints): outputs (List(torch.Tensor[NxKxHxW])): Multi-scale output heatmaps. targets (List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. masks (List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps + heatmaps joints (List(torch.Tensor[NxMxKx2])): Joints of multi-scale target - heatmaps for ae loss + heatmaps for ae loss """ losses = dict() diff --git a/mmpose/models/heads/ae_simple_head.py b/mmpose/models/heads/ae_simple_head.py index 6d56c48a58..90ebad96f8 100644 --- a/mmpose/models/heads/ae_simple_head.py +++ b/mmpose/models/heads/ae_simple_head.py @@ -99,9 +99,9 @@ def get_loss(self, outputs, targets, masks, joints): outputs (list(torch.Tensor[NxKxHxW])): Multi-scale output heatmaps. targets (List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. masks (List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps + heatmaps joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target - heatmaps for ae loss + heatmaps for ae loss """ losses = dict() From 4eca2477a67b9b53cefb09b9b199111b5d8479b9 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 19:51:22 +0800 Subject: [PATCH 07/98] update show --- mmpose/models/detectors/paf.py | 85 ++++------------------------------ 1 file changed, 9 insertions(+), 76 deletions(-) diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 3ca9bba4d5..4d1283cb77 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -1,9 +1,6 @@ -import math import warnings -import cv2 import mmcv -import numpy as np import torch from mmcv.image import imwrite from mmcv.visualization.image import imshow @@ -11,6 +8,7 @@ from mmpose.core.evaluation import (aggregate_results_paf, get_group_preds, get_multi_stage_outputs_paf) from mmpose.core.post_processing.group import PAFParser +from mmpose.core.visualization import imshow_keypoints from .. import builder from ..registry import POSENETS from .base import BasePose @@ -290,6 +288,7 @@ def show_result(self, result, skeleton=None, kpt_score_thr=0.3, + bbox_color=None, pose_kpt_color=None, pose_limb_color=None, radius=4, @@ -306,15 +305,20 @@ def show_result(self, img (str or Tensor): The image to be displayed. result (list[dict]): The results to draw over `img` (bbox_result, pose_result). + skeleton (list[list]): The connection of keypoints. kpt_score_thr (float, optional): Minimum score of keypoints to be shown. Default: 0.3. pose_kpt_color (np.array[Nx3]`): Color of N keypoints. If None, do not draw keypoints. pose_limb_color (np.array[Mx3]): Color of M limbs. If None, do not draw limbs. + radius (int): Radius of circles. thickness (int): Thickness of lines. font_scale (float): Font scales of texts. win_name (str): The window name. + show (bool): Whether to show the image. Default: False. + show_keypoint_weight (bool): Whether to change the transparency + using the predicted confidence scores of keypoints. wait_time (int): Value of waitKey param. Default: 0. out_file (str or None): The filename to write the image. @@ -332,79 +336,8 @@ def show_result(self, for res in result: pose_result.append(res['keypoints']) - for _, kpts in enumerate(pose_result): - # draw each point on image - if pose_kpt_color is not None: - assert len(pose_kpt_color) == len(kpts) - for kid, kpt in enumerate(kpts): - x_coord, y_coord, kpt_score = int(kpt[0]), int( - kpt[1]), kpt[2] - if kpt_score > kpt_score_thr: - if show_keypoint_weight: - img_copy = img.copy() - r, g, b = pose_kpt_color[kid] - cv2.circle(img_copy, (int(x_coord), int(y_coord)), - radius, (int(r), int(g), int(b)), -1) - transparency = max(0, min(1, kpt_score)) - cv2.addWeighted( - img_copy, - transparency, - img, - 1 - transparency, - 0, - dst=img) - else: - r, g, b = pose_kpt_color[kid] - cv2.circle(img, (int(x_coord), int(y_coord)), - radius, (int(r), int(g), int(b)), -1) - - # draw limbs - if skeleton is not None and pose_limb_color is not None: - assert len(pose_limb_color) == len(skeleton) - for sk_id, sk in enumerate(skeleton): - pos1 = (int(kpts[sk[0] - 1, 0]), int(kpts[sk[0] - 1, 1])) - pos2 = (int(kpts[sk[1] - 1, 0]), int(kpts[sk[1] - 1, 1])) - if (pos1[0] > 0 and pos1[0] < img_w and pos1[1] > 0 - and pos1[1] < img_h and pos2[0] > 0 - and pos2[0] < img_w and pos2[1] > 0 - and pos2[1] < img_h - and kpts[sk[0] - 1, 2] > kpt_score_thr - and kpts[sk[1] - 1, 2] > kpt_score_thr): - r, g, b = pose_limb_color[sk_id] - if show_keypoint_weight: - img_copy = img.copy() - X = (pos1[0], pos2[0]) - Y = (pos1[1], pos2[1]) - mX = np.mean(X) - mY = np.mean(Y) - length = ((Y[0] - Y[1])**2 + (X[0] - X[1])**2)**0.5 - angle = math.degrees( - math.atan2(Y[0] - Y[1], X[0] - X[1])) - stickwidth = 2 - polygon = cv2.ellipse2Poly( - (int(mX), int(mY)), - (int(length / 2), int(stickwidth)), int(angle), - 0, 360, 1) - cv2.fillConvexPoly(img_copy, polygon, - (int(r), int(g), int(b))) - transparency = max( - 0, - min( - 1, 0.5 * - (kpts[sk[0] - 1, 2] + kpts[sk[1] - 1, 2]))) - cv2.addWeighted( - img_copy, - transparency, - img, - 1 - transparency, - 0, - dst=img) - else: - cv2.line( - img, - pos1, - pos2, (int(r), int(g), int(b)), - thickness=thickness) + imshow_keypoints(img, pose_result, skeleton, kpt_score_thr, + pose_kpt_color, pose_limb_color, radius, thickness) if show: imshow(img, win_name, wait_time) From 77289f2741333b3362767334cd4516b79967cc0d Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 20:51:24 +0800 Subject: [PATCH 08/98] update heads --- mmpose/models/heads/ae_simple_head.py | 121 ++---------------- .../{paf_simple_head.py => deconv_head.py} | 85 ++++++------ 2 files changed, 51 insertions(+), 155 deletions(-) rename mmpose/models/keypoint_heads/{paf_simple_head.py => deconv_head.py} (96%) diff --git a/mmpose/models/heads/ae_simple_head.py b/mmpose/models/heads/ae_simple_head.py index 90ebad96f8..2a14767d10 100644 --- a/mmpose/models/heads/ae_simple_head.py +++ b/mmpose/models/heads/ae_simple_head.py @@ -4,10 +4,10 @@ from mmpose.models.builder import build_loss from ..builder import HEADS - +from .deconv_head import DeconvHead @HEADS.register_module() -class AESimpleHead(nn.Module): +class AESimpleHead(DeconvHead): """Associative embedding simple head. paper ref: Alejandro Newell et al. "Associative Embedding: End-to-end Learning for Joint Detection @@ -39,51 +39,21 @@ def __init__(self, with_ae_loss=None, extra=None, loss_keypoint=None): - super().__init__() - - self.loss = build_loss(loss_keypoint) - self.in_channels = in_channels dim_tag = num_joints if tag_per_joint else 1 if with_ae_loss[0]: out_channels = num_joints + dim_tag else: out_channels = num_joints - if extra is not None and not isinstance(extra, dict): - raise TypeError('extra should be dict or None.') - - if num_deconv_layers > 0: - self.deconv_layers = self._make_deconv_layer( - num_deconv_layers, - num_deconv_filters, - num_deconv_kernels, - ) - elif num_deconv_layers == 0: - self.deconv_layers = nn.Identity() - else: - raise ValueError( - f'num_deconv_layers ({num_deconv_layers}) should >= 0.') - - if extra is not None and 'final_conv_kernel' in extra: - assert extra['final_conv_kernel'] in [1, 3] - if extra['final_conv_kernel'] == 3: - padding = 1 - else: - padding = 0 - kernel_size = extra['final_conv_kernel'] - else: - kernel_size = 1 - padding = 0 - - self.final_layer = build_conv_layer( - cfg=dict(type='Conv2d'), - in_channels=num_deconv_filters[-1] - if num_deconv_layers > 0 else in_channels, - out_channels=out_channels, - kernel_size=kernel_size, - stride=1, - padding=padding) + super().__init__( + in_channels, + out_channels, + num_deconv_layers=num_deconv_layers, + num_deconv_filters=num_deconv_filters, + num_deconv_kernels=num_deconv_kernels, + extra=extra, + loss_keypoint=loss_keypoint) def get_loss(self, outputs, targets, masks, joints): """Calculate bottom-up keypoint loss. @@ -130,74 +100,3 @@ def get_loss(self, outputs, targets, masks, joints): losses['pull_loss'] += pull_loss return losses - - def forward(self, x): - """Forward function.""" - if isinstance(x, list): - x = x[0] - final_outputs = [] - x = self.deconv_layers(x) - y = self.final_layer(x) - final_outputs.append(y) - return final_outputs - - def _make_deconv_layer(self, num_layers, num_filters, num_kernels): - """Make deconv layers.""" - if num_layers != len(num_filters): - error_msg = f'num_layers({num_layers}) ' \ - f'!= length of num_filters({len(num_filters)})' - raise ValueError(error_msg) - if num_layers != len(num_kernels): - error_msg = f'num_layers({num_layers}) ' \ - f'!= length of num_kernels({len(num_kernels)})' - raise ValueError(error_msg) - - layers = [] - for i in range(num_layers): - kernel, padding, output_padding = \ - self._get_deconv_cfg(num_kernels[i]) - - planes = num_filters[i] - layers.append( - build_upsample_layer( - dict(type='deconv'), - in_channels=self.in_channels, - out_channels=planes, - kernel_size=kernel, - stride=2, - padding=padding, - output_padding=output_padding, - bias=False)) - layers.append(nn.BatchNorm2d(planes)) - layers.append(nn.ReLU(inplace=True)) - self.in_channels = planes - - return nn.Sequential(*layers) - - @staticmethod - def _get_deconv_cfg(deconv_kernel): - """Get configurations for deconv layers.""" - if deconv_kernel == 4: - padding = 1 - output_padding = 0 - elif deconv_kernel == 3: - padding = 1 - output_padding = 1 - elif deconv_kernel == 2: - padding = 0 - output_padding = 0 - else: - raise ValueError(f'Not supported num_kernels ({deconv_kernel}).') - - return deconv_kernel, padding, output_padding - - def init_weights(self): - """Initialize model weights.""" - for _, m in self.deconv_layers.named_modules(): - if isinstance(m, nn.ConvTranspose2d): - normal_init(m, std=0.001) - elif isinstance(m, nn.BatchNorm2d): - constant_init(m, 1) - for m in self.final_layer.modules(): - if isinstance(m, nn.Conv2d): - normal_init(m, std=0.001, bias=0) diff --git a/mmpose/models/keypoint_heads/paf_simple_head.py b/mmpose/models/keypoint_heads/deconv_head.py similarity index 96% rename from mmpose/models/keypoint_heads/paf_simple_head.py rename to mmpose/models/keypoint_heads/deconv_head.py index b78af28bfc..cf1df6ce68 100644 --- a/mmpose/models/keypoint_heads/paf_simple_head.py +++ b/mmpose/models/keypoint_heads/deconv_head.py @@ -3,16 +3,14 @@ normal_init) from mmpose.models.builder import build_loss -from ..registry import HEADS -@HEADS.register_module() -class PAFSimpleHead(nn.Module): - """Bottom-up simple head. +class DeconvHead(nn.Module): + """Simple deconv head. Args: in_channels (int): Number of input channels. - num_joints (int): Number of joints. + out_channels (int): Number of output channels. num_deconv_layers (int): Number of deconv layers. num_deconv_layers should >= 0. Note that 0 means no deconv layers. @@ -24,7 +22,7 @@ class PAFSimpleHead(nn.Module): def __init__(self, in_channels, - num_joints, + out_channels, num_deconv_layers=3, num_deconv_filters=(256, 256, 256), num_deconv_kernels=(4, 4, 4), @@ -35,7 +33,6 @@ def __init__(self, self.loss = build_loss(loss_keypoint) self.in_channels = in_channels - out_channels = num_joints if extra is not None and not isinstance(extra, dict): raise TypeError('extra should be dict or None.') @@ -72,43 +69,6 @@ def __init__(self, stride=1, padding=padding) - def get_loss(self, outputs, targets, masks): - """Calculate bottom-up masked mse loss. - - Note: - batch_size: N - num_channels: C - heatmaps height: H - heatmaps weight: W - - Args: - outputs (List(torch.Tensor[NxCxHxW])): Multi-scale outputs. - targets (List(torch.Tensor[NxCxHxW])): Multi-scale targets. - masks (List(torch.Tensor[NxHxW])): Masks of multi-scale targets. - """ - - losses = dict() - - for idx in range(len(targets)): - if 'loss' not in losses: - losses['loss'] = self.loss(outputs[idx], targets[idx], - masks[idx]) - else: - losses['loss'] += self.loss(outputs[idx], targets[idx], - masks[idx]) - - return losses - - def forward(self, x): - """Forward function.""" - if isinstance(x, list): - x = x[0] - final_outputs = [] - x = self.deconv_layers(x) - y = self.final_layer(x) - final_outputs.append(y) - return final_outputs - def _make_deconv_layer(self, num_layers, num_filters, num_kernels): """Make deconv layers.""" if num_layers != len(num_filters): @@ -159,6 +119,43 @@ def _get_deconv_cfg(deconv_kernel): return deconv_kernel, padding, output_padding + def get_loss(self, outputs, targets, masks): + """Calculate bottom-up masked mse loss. + + Note: + batch_size: N + num_channels: C + heatmaps height: H + heatmaps weight: W + + Args: + outputs (List(torch.Tensor[NxCxHxW])): Multi-scale outputs. + targets (List(torch.Tensor[NxCxHxW])): Multi-scale targets. + masks (List(torch.Tensor[NxHxW])): Masks of multi-scale targets. + """ + + losses = dict() + + for idx in range(len(targets)): + if 'loss' not in losses: + losses['loss'] = self.loss(outputs[idx], targets[idx], + masks[idx]) + else: + losses['loss'] += self.loss(outputs[idx], targets[idx], + masks[idx]) + + return losses + + def forward(self, x): + """Forward function.""" + if isinstance(x, list): + x = x[0] + final_outputs = [] + x = self.deconv_layers(x) + y = self.final_layer(x) + final_outputs.append(y) + return final_outputs + def init_weights(self): """Initialize model weights.""" for _, m in self.deconv_layers.named_modules(): From 0effb705ea294a83cc300268e78b65bfbe2ccf00 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 26 May 2021 21:24:19 +0800 Subject: [PATCH 09/98] update heads --- mmpose/models/keypoint_heads/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/mmpose/models/keypoint_heads/__init__.py b/mmpose/models/keypoint_heads/__init__.py index c752b8a9fa..fde4d7efbe 100644 --- a/mmpose/models/keypoint_heads/__init__.py +++ b/mmpose/models/keypoint_heads/__init__.py @@ -1,7 +1,5 @@ from .paf_head import PAFHead -from .paf_simple_head import PAFSimpleHead __all__ = [ - 'PAFHead', - 'PAFSimpleHead' + 'PAFHead' ] From fee1c17a2bbc13d3b02f2367d89d06545e420de2 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 7 Jun 2021 11:31:58 +0800 Subject: [PATCH 10/98] update paf head --- mmpose/models/detectors/__init__.py | 3 +-- mmpose/models/detectors/paf.py | 2 +- mmpose/models/heads/ae_simple_head.py | 6 +----- mmpose/models/{keypoint_heads => heads}/deconv_head.py | 0 mmpose/models/{keypoint_heads => heads}/paf_head.py | 5 ++--- mmpose/models/keypoint_heads/__init__.py | 5 ----- 6 files changed, 5 insertions(+), 16 deletions(-) rename mmpose/models/{keypoint_heads => heads}/deconv_head.py (100%) rename mmpose/models/{keypoint_heads => heads}/paf_head.py (97%) delete mode 100644 mmpose/models/keypoint_heads/__init__.py diff --git a/mmpose/models/detectors/__init__.py b/mmpose/models/detectors/__init__.py index 588d98a038..cfa964e181 100644 --- a/mmpose/models/detectors/__init__.py +++ b/mmpose/models/detectors/__init__.py @@ -8,6 +8,5 @@ __all__ = [ 'TopDown', 'AssociativeEmbedding', 'ParametricMesh', 'MultiTask', - 'PoseLifter', 'Interhand3D', - 'PartAffinityField' + 'PoseLifter', 'Interhand3D', 'PartAffinityField' ] diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 4d1283cb77..175d279846 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -10,7 +10,7 @@ from mmpose.core.post_processing.group import PAFParser from mmpose.core.visualization import imshow_keypoints from .. import builder -from ..registry import POSENETS +from ..builder import POSENETS from .base import BasePose diff --git a/mmpose/models/heads/ae_simple_head.py b/mmpose/models/heads/ae_simple_head.py index 2a14767d10..058e2303e6 100644 --- a/mmpose/models/heads/ae_simple_head.py +++ b/mmpose/models/heads/ae_simple_head.py @@ -1,11 +1,7 @@ -import torch.nn as nn -from mmcv.cnn import (build_conv_layer, build_upsample_layer, constant_init, - normal_init) - -from mmpose.models.builder import build_loss from ..builder import HEADS from .deconv_head import DeconvHead + @HEADS.register_module() class AESimpleHead(DeconvHead): """Associative embedding simple head. diff --git a/mmpose/models/keypoint_heads/deconv_head.py b/mmpose/models/heads/deconv_head.py similarity index 100% rename from mmpose/models/keypoint_heads/deconv_head.py rename to mmpose/models/heads/deconv_head.py diff --git a/mmpose/models/keypoint_heads/paf_head.py b/mmpose/models/heads/paf_head.py similarity index 97% rename from mmpose/models/keypoint_heads/paf_head.py rename to mmpose/models/heads/paf_head.py index 2973965795..bd1c52c6fd 100644 --- a/mmpose/models/keypoint_heads/paf_head.py +++ b/mmpose/models/heads/paf_head.py @@ -1,12 +1,11 @@ import torch.nn as nn -from mmpose.models.builder import build_head -from ..registry import HEADS +from mmpose.models.builder import HEADS, build_head @HEADS.register_module() class PAFHead(nn.Module): - """Bottom-up PAF head. + """Bottom-up PAF (Part Affinity Fields) head. Paper ref: Cao, Zhe, et al. "OpenPose: realtime multi-person 2D pose estimation using Part Affinity Fields." (TPAMI'2019) diff --git a/mmpose/models/keypoint_heads/__init__.py b/mmpose/models/keypoint_heads/__init__.py deleted file mode 100644 index fde4d7efbe..0000000000 --- a/mmpose/models/keypoint_heads/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -from .paf_head import PAFHead - -__all__ = [ - 'PAFHead' -] From 12607024a18de41e7340336c70390ce5e0fc5a40 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 7 Jun 2021 12:55:31 +0800 Subject: [PATCH 11/98] update docstring --- mmpose/models/detectors/paf.py | 6 ++++-- tests/test_model/test_bottom_up_forward.py | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 175d279846..54431a30f7 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -16,7 +16,10 @@ @POSENETS.register_module() class PartAffinityField(BasePose): - """Bottom-up pose detectors. + """Bottom-up PAF (part affinity field) pose detectors. + + Paper ref: Cao, Zhe, et al. "OpenPose: realtime multi-person + 2D pose estimation using Part Affinity Fields." (TPAMI'2019) Args: backbone (dict): Backbone modules to extract feature. @@ -40,7 +43,6 @@ def __init__(self, self.backbone = builder.build_backbone(backbone) if keypoint_head is not None: - if 'loss_keypoint' not in keypoint_head and loss_pose is not None: warnings.warn( '`loss_pose` for BottomUp is deprecated, ' diff --git a/tests/test_model/test_bottom_up_forward.py b/tests/test_model/test_bottom_up_forward.py index c72bf8601a..a8ffe4617c 100644 --- a/tests/test_model/test_bottom_up_forward.py +++ b/tests/test_model/test_bottom_up_forward.py @@ -4,7 +4,7 @@ from mmpose.models.detectors import AssociativeEmbedding -def test_bottomup_forward(): +def test_ae_forward(): model_cfg = dict( type='AssociativeEmbedding', pretrained=None, From 371dd669c6992ee43127879be62ea4cc95f88dbf Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 9 Jun 2021 21:58:42 +0800 Subject: [PATCH 12/98] integrate get_multi_stage_outputs function for ae and paf --- mmpose/core/evaluation/bottom_up_eval.py | 324 ++++++++++++----------- 1 file changed, 176 insertions(+), 148 deletions(-) diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index fb37a3373b..24b1f75fdb 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -5,48 +5,43 @@ warp_affine_joints) -def get_multi_stage_outputs(outputs, - outputs_flip, - num_joints, - with_heatmaps, - with_ae, - tag_per_joint=True, - flip_index=None, - project2image=True, - size_projected=None, - align_corners=False): +def _get_multi_stage_heatmaps(outputs, + outputs_flip, + with_heatmaps, + flip_index=None, + project2image=True, + size_projected=None, + align_corners=False, + num_joints=None, + flip_paf=False): """Inference the model to get multi-stage outputs (heatmaps & tags), and resize them to base sizes. Args: - outputs (list(torch.Tensor)): Outputs of network - outputs_flip (list(torch.Tensor)): Flip outputs of network - num_joints (int): Number of joints + outputs (list(torch.Tensor)): Outputs of network. + outputs_flip (list(torch.Tensor)): Flip outputs of network. with_heatmaps (list[bool]): Option to output heatmaps for different stages. - with_ae (list[bool]): Option to output - ae tags for different stages. - tag_per_joint (bool): Option to use one tag map per joint. flip_index (list[int]): Keypoint flip index. project2image (bool): Option to resize to base scale. size_projected ([w, h]): Base size of heatmaps. align_corners (bool): Align corners when performing interpolation. + num_joints (int): Number of joints. + flip_paf (bool): Whether to flip for paf maps. Returns: tuple: A tuple containing multi-stage outputs. - - outputs (list(torch.Tensor)): List of simple outputs and - flip outputs. + - outputs_with_flipped (list(torch.Tensor)): List of simple outputs + and flip outputs. - heatmaps (torch.Tensor): Multi-stage heatmaps that are resized to the base size. - - tags (torch.Tensor): Multi-stage tags that are resized to - the base size. """ + outputs_with_flipped = outputs heatmaps_avg = 0 num_heatmaps = 0 heatmaps = [] - tags = [] flip_test = outputs_flip is not None @@ -59,16 +54,13 @@ def get_multi_stage_outputs(outputs, mode='bilinear', align_corners=align_corners) - # staring index of the associative embeddings - offset_feat = num_joints if with_heatmaps[i] else 0 - if with_heatmaps[i]: - heatmaps_avg += output[:, :num_joints] + if num_joints is not None: + heatmaps_avg += output[:, :num_joints] + else: + heatmaps_avg += output num_heatmaps += 1 - if with_ae[i]: - tags.append(output[:, offset_feat:]) - if num_heatmaps > 0: heatmaps.append(heatmaps_avg / num_heatmaps) @@ -85,19 +77,23 @@ def get_multi_stage_outputs(outputs, mode='bilinear', align_corners=align_corners) output = torch.flip(output, [3]) - outputs.append(output) - - offset_feat = num_joints if with_heatmaps[i] else 0 + outputs_with_flipped.append(output) if with_heatmaps[i]: - heatmaps_avg += output[:, :num_joints][:, flip_index, :, :] + if flip_paf: + heatmaps_avg[:, ::2, :, :] -= output[:, + flip_index[::2], :, :] + heatmaps_avg[:, + 1::2, :, :] += output[:, + flip_index[1::2], :, :] + else: + if num_joints is not None: + heatmaps_avg += output[:, : + num_joints][:, flip_index, :, :] + else: + heatmaps_avg += output[:, flip_index, :, :] num_heatmaps += 1 - if with_ae[i]: - tags.append(output[:, offset_feat:]) - if tag_per_joint: - tags[-1] = tags[-1][:, flip_index, :, :] - heatmaps.append(heatmaps_avg / num_heatmaps) if project2image and size_projected: @@ -109,6 +105,80 @@ def get_multi_stage_outputs(outputs, align_corners=align_corners) for hms in heatmaps ] + return outputs_with_flipped, heatmaps + + +def _get_multi_stage_tags(outputs, + outputs_flip, + with_heatmaps, + with_ae, + tag_per_joint=True, + flip_index=None, + project2image=True, + size_projected=None, + align_corners=False, + num_joints=None): + """Inference the model to get multi-stage outputs (heatmaps & tags), and + resize them to base sizes. + + Args: + outputs (list(torch.Tensor)): Outputs of network. + outputs_flip (list(torch.Tensor)): Flip outputs of network. + with_heatmaps (list[bool]): Option to output + heatmaps for different stages. + with_ae (list[bool]): Option to output + ae tags for different stages. + tag_per_joint (bool): Option to use one tag map per joint. + flip_index (list[int]): Keypoint flip index. + project2image (bool): Option to resize to base scale. + size_projected ([w, h]): Base size of heatmaps. + align_corners (bool): Align corners when performing interpolation. + num_joints (int): Number of joints. + + Returns: + tags (torch.Tensor): Multi-stage tags that are resized to + the base size. + """ + + tags = [] + + flip_test = outputs_flip is not None + + # aggregate tags from different stages + for i, output in enumerate(outputs): + if i != len(outputs) - 1: + output = torch.nn.functional.interpolate( + output, + size=(outputs[-1].size(2), outputs[-1].size(3)), + mode='bilinear', + align_corners=align_corners) + + # staring index of the associative embeddings + offset_feat = num_joints if with_heatmaps[i] else 0 + + if with_ae[i]: + tags.append(output[:, offset_feat:]) + + if flip_test and flip_index: + # perform flip testing + + for i, output in enumerate(outputs_flip): + if i != len(outputs_flip) - 1: + output = torch.nn.functional.interpolate( + output, + size=(outputs_flip[-1].size(2), outputs_flip[-1].size(3)), + mode='bilinear', + align_corners=align_corners) + output = torch.flip(output, [3]) + + offset_feat = num_joints if with_heatmaps[i] else 0 + + if with_ae[i]: + tags.append(output[:, offset_feat:]) + if tag_per_joint: + tags[-1] = tags[-1][:, flip_index, :, :] + + if project2image and size_projected: tags = [ torch.nn.functional.interpolate( tms, @@ -117,7 +187,56 @@ def get_multi_stage_outputs(outputs, align_corners=align_corners) for tms in tags ] - return outputs, heatmaps, tags + return tags + + +def get_multi_stage_outputs(outputs, + outputs_flip, + num_joints, + with_heatmaps, + with_ae, + tag_per_joint=True, + flip_index=None, + project2image=True, + size_projected=None, + align_corners=False): + """Inference the model to get multi-stage outputs (heatmaps & tags), and + resize them to base sizes. + + Args: + outputs (list(torch.Tensor)): Outputs of network + outputs_flip (list(torch.Tensor)): Flip outputs of network + num_joints (int): Number of joints + with_heatmaps (list[bool]): Option to output + heatmaps for different stages. + with_ae (list[bool]): Option to output + ae tags for different stages. + tag_per_joint (bool): Option to use one tag map per joint. + flip_index (list[int]): Keypoint flip index. + project2image (bool): Option to resize to base scale. + size_projected ([w, h]): Base size of heatmaps. + align_corners (bool): Align corners when performing interpolation. + + Returns: + tuple: A tuple containing multi-stage outputs. + + - outputs (list(torch.Tensor)): List of simple outputs and + flip outputs. + - heatmaps (torch.Tensor): Multi-stage heatmaps that are resized to + the base size. + - tags (torch.Tensor): Multi-stage tags that are resized to + the base size. + """ + outputs_with_flipped, heatmaps = _get_multi_stage_heatmaps( + outputs, outputs_flip, num_joints, with_heatmaps, flip_index, + project2image, size_projected, align_corners) + + tags = _get_multi_stage_tags(outputs, outputs_flip, num_joints, + with_heatmaps, with_ae, tag_per_joint, + flip_index, project2image, size_projected, + align_corners) + + return outputs_with_flipped, heatmaps, tags def get_multi_stage_outputs_paf(outputs, @@ -157,116 +276,25 @@ def get_multi_stage_outputs_paf(outputs, the base size. """ - heatmaps = [] - pafs = [] - - flip_test = outputs_flip is not None - - # aggregate heatmaps from different stages - heatmaps_avg = 0 - num_heatmaps = 0 - - for i, output in enumerate(outputs['heatmaps']): - if i != len(outputs['heatmaps']) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs['heatmaps'][-1].size(2), - outputs['heatmaps'][-1].size(3)), - mode='bilinear', - align_corners=align_corners) - - if with_heatmaps[i]: - heatmaps_avg += output - num_heatmaps += 1 - - if num_heatmaps > 0: - heatmaps.append(heatmaps_avg / num_heatmaps) - - # aggregate pafs from different stages - pafs_avg = 0 - num_pafs = 0 - - for i, output in enumerate(outputs['pafs']): - if i != len(outputs['pafs']) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs['pafs'][-1].size(2), - outputs['pafs'][-1].size(3)), - mode='bilinear', - align_corners=align_corners) - - if with_pafs[i]: - pafs_avg += output - num_pafs += 1 - - if num_pafs > 0: - pafs.append(pafs_avg / num_pafs) - - if flip_test: - if flip_index: - # perform flip testing for heatmaps - heatmaps_avg = 0 - num_heatmaps = 0 - - for i, output in enumerate(outputs_flip['heatmaps']): - if i != len(outputs_flip['heatmaps']) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs_flip['heatmaps'][-1].size(2), - outputs_flip['heatmaps'][-1].size(3)), - mode='bilinear', - align_corners=align_corners) - output = torch.flip(output, [3]) - outputs['heatmaps'].append(output) - - if with_heatmaps[i]: - heatmaps_avg += output[:, flip_index, :, :] - num_heatmaps += 1 - - heatmaps.append(heatmaps_avg / num_heatmaps) - - if flip_index_paf: - # perform flip testing for pafs - pafs_avg = 0 - num_pafs = 0 - - for i, output in enumerate(outputs_flip['pafs']): - if i != len(outputs_flip['pafs']) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs_flip['pafs'][-1].size(2), - outputs_flip['pafs'][-1].size(3)), - mode='bilinear', - align_corners=align_corners) - output = torch.flip(output, [3]) - outputs['pafs'].append(output) - - if with_pafs[i]: - pafs_avg[:, ::2, :, :] -= output[:, - flip_index_paf[::2], :, :] - pafs_avg[:, - 1::2, :, :] += output[:, - flip_index_paf[1::2], :, :] - num_pafs += 1 - - pafs.append(pafs_avg / num_pafs) - - if project2image and size_projected: - heatmaps = [ - torch.nn.functional.interpolate( - hms, - size=(size_projected[1], size_projected[0]), - mode='bilinear', - align_corners=align_corners) for hms in heatmaps - ] - - pafs = [ - torch.nn.functional.interpolate( - pms, - size=(size_projected[1], size_projected[0]), - mode='bilinear', - align_corners=align_corners) for pms in pafs - ] + outputs['heatmaps'], heatmaps = _get_multi_stage_heatmaps( + outputs['heatmaps'], + outputs_flip['heatmaps'], + with_heatmaps, + flip_index, + project2image, + size_projected, + align_corners, + flip_paf=True) + + outputs['pafs'], pafs = _get_multi_stage_heatmaps( + outputs['pafs'], + outputs_flip['pafs'], + with_heatmaps, + flip_index, + project2image, + size_projected, + align_corners, + flip_paf=True) return outputs, heatmaps, pafs From 82c9f52b731e505c764881d291b638f8df69ece6 Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 9 Jun 2021 22:09:07 +0800 Subject: [PATCH 13/98] delete PAFParser --- mmpose/core/post_processing/group.py | 242 +-------------------------- 1 file changed, 2 insertions(+), 240 deletions(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 01e11e410e..aeb17cfef1 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -406,6 +406,7 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): return ans, scores +# TODO class PAFParser: """The paf parser for post processing. @@ -415,218 +416,6 @@ class PAFParser: def __init__(self, cfg): self.params = _Params(cfg) - self.tag_per_joint = cfg['tag_per_joint'] - self.pool = torch.nn.MaxPool2d(cfg['nms_kernel'], 1, - cfg['nms_padding']) - self.use_udp = cfg.get('use_udp', False) - - # def nms(self, heatmaps): - # """Non-Maximum Suppression for heatmaps. - # - # Args: - # heatmap(torch.Tensor): Heatmaps before nms. - # - # Returns: - # torch.Tensor: Heatmaps after nms. - # """ - # - # maxm = self.pool(heatmaps) - # maxm = torch.eq(maxm, heatmaps).float() - # heatmaps = heatmaps * maxm - # - # return heatmaps - # - # def match(self, tag_k, loc_k, val_k): - # """Group keypoints to human poses in a batch. - # - # Args: - # tag_k (np.ndarray[NxKxMxL]): tag corresponding to the - # top k values of feature map per keypoint. - # loc_k (np.ndarray[NxKxMx2]): top k locations of the - # feature maps for keypoint. - # val_k (np.ndarray[NxKxM]): top k value of the - # feature maps per keypoint. - # - # Returns: - # list - # """ - # - # def _match(x): - # return _match_by_tag(x, self.params) - # - # return list(map(_match, zip(tag_k, loc_k, val_k))) - # - # def top_k(self, heatmaps, tags): - # """Find top_k values in an image. - # - # Note: - # batch size: N - # number of keypoints: K - # heatmap height: H - # heatmap width: W - # max number of people: M - # dim of tags: L - # If use flip testing, L=2; else L=1. - # - # Args: - # heatmaps (torch.Tensor[NxKxHxW]) - # tags (torch.Tensor[NxKxHxWxL]) - # - # Return: - # dict: A dict containing top_k values. - # - # - tag_k (np.ndarray[NxKxMxL]): - # tag corresponding to the top k values of - # feature map per keypoint. - # - loc_k (np.ndarray[NxKxMx2]): - # top k location of feature map per keypoint. - # - val_k (np.ndarray[NxKxM]): - # top k value of feature map per keypoint. - # """ - # heatmaps = self.nms(heatmaps) - # N, K, H, W = heatmaps.size() - # heatmaps = heatmaps.view(N, K, -1) - # val_k, ind = heatmaps.topk(self.params.max_num_people, dim=2) - # - # tags = tags.view(tags.size(0), tags.size(1), W * H, -1) - # if not self.tag_per_joint: - # tags = tags.expand(-1, self.params.num_joints, -1, -1) - # - # tag_k = torch.stack( - # [torch.gather(tags[..., i], 2, ind) for i in - # range(tags.size(3))], - # dim=3) - # - # x = ind % W - # y = ind // W - # - # ind_k = torch.stack((x, y), dim=3) - # - # ans = { - # 'tag_k': tag_k.cpu().numpy(), - # 'loc_k': ind_k.cpu().numpy(), - # 'val_k': val_k.cpu().numpy() - # } - # - # return ans - # - # @staticmethod - # def adjust(ans, heatmaps): - # """Adjust the coordinates for better accuracy. - # - # Note: - # batch size: N - # number of keypoints: K - # heatmap height: H - # heatmap width: W - # - # Args: - # ans (list(np.ndarray)): Keypoint predictions. - # heatmaps (torch.Tensor[NxKxHxW]): Heatmaps. - # """ - # _, _, H, W = heatmaps.shape - # for batch_id, people in enumerate(ans): - # for people_id, people_i in enumerate(people): - # for joint_id, joint in enumerate(people_i): - # if joint[2] > 0: - # x, y = joint[0:2] - # xx, yy = int(x), int(y) - # tmp = heatmaps[batch_id][joint_id] - # if tmp[min(H - 1, yy + 1), xx] > tmp[max(0, yy - 1), - # xx]: - # y += 0.25 - # else: - # y -= 0.25 - # - # if tmp[yy, min(W - 1, xx + 1)] > tmp[yy, - # max(0, xx - 1)]: - # x += 0.25 - # else: - # x -= 0.25 - # ans[batch_id][people_id, joint_id, - # 0:2] = (x + 0.5, y + 0.5) - # return ans - # - # @staticmethod - # def refine(heatmap, tag, keypoints, use_udp=False): - # """Given initial keypoint predictions, we identify missing joints. - # - # Note: - # number of keypoints: K - # heatmap height: H - # heatmap width: W - # dim of tags: L - # If use flip testing, L=2; else L=1. - # - # Args: - # heatmap: np.ndarray(K, H, W). - # tag: np.ndarray(K, H, W) | np.ndarray(K, H, W, L) - # keypoints: np.ndarray of size (K, 3 + L) - # last dim is (x, y, score, tag). - # use_udp: bool-unbiased data processing - # - # Returns: - # np.ndarray: The refined keypoints. - # """ - # - # K, H, W = heatmap.shape - # if len(tag.shape) == 3: - # tag = tag[..., None] - # - # tags = [] - # for i in range(K): - # if keypoints[i, 2] > 0: - # # save tag value of detected keypoint - # x, y = keypoints[i][:2].astype(int) - # x = np.clip(x, 0, W - 1) - # y = np.clip(y, 0, H - 1) - # tags.append(tag[i, y, x]) - # - # # mean tag of current detected people - # prev_tag = np.mean(tags, axis=0) - # ans = [] - # - # for _heatmap, _tag in zip(heatmap, tag): - # # distance of all tag values with mean tag of - # # current detected people - # distance_tag = (((_tag - - # prev_tag[None, None, :])**2).sum(axis=2)**0.5) - # norm_heatmap = _heatmap - np.round(distance_tag) - # - # # find maximum position - # y, x = np.unravel_index(np.argmax(norm_heatmap), _heatmap.shape) - # xx = x.copy() - # yy = y.copy() - # # detection score at maximum position - # val = _heatmap[y, x] - # if not use_udp: - # # offset by 0.5 - # x += 0.5 - # y += 0.5 - # - # # add a quarter offset - # if _heatmap[yy, min(W - 1, xx + 1)] > _ - # heatmap[yy, max(0, xx - 1)]: - # x += 0.25 - # else: - # x -= 0.25 - # - # if _heatmap[min(H - 1, yy + 1), xx] > _ - # heatmap[max(0, yy - 1), xx]: - # y += 0.25 - # else: - # y -= 0.25 - # - # ans.append((x, y, val)) - # ans = np.array(ans) - # - # if ans is not None: - # for i in range(K): - # # add keypoint if it is not detected - # if ans[i, 2] > 0 and keypoints[i, 2] == 0: - # keypoints[i, :3] = ans[i, :3] - # - # return keypoints def parse(self, heatmaps, pafs, adjust=True, refine=True): """Group keypoints into poses given heatmap and paf. @@ -649,31 +438,4 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): - scores (list): Score of people. """ - assert 0, 'The post-process of paf have not been completed.' - # ans = self.match(**self.top_k(heatmaps, pafs)) - # - # if adjust: - # if self.use_udp: - # for i in range(len(ans)): - # if ans[i].shape[0] > 0: - # ans[i][..., :2] = post_dark_udp( - # ans[i][..., :2].copy(), heatmaps[i:i + 1, :]) - # else: - # ans = self.adjust(ans, heatmaps) - # - # scores = [i[:, 2].mean() for i in ans[0]] - # - # if refine: - # ans = ans[0] - # # for every detected person - # for i in range(len(ans)): - # heatmap_numpy = heatmaps[0].cpu().numpy() - # tag_numpy = tags[0].cpu().numpy() - # if not self.tag_per_joint: - # tag_numpy = np.tile(tag_numpy, - # (self.params.num_joints, 1, 1, 1)) - # ans[i] = self.refine( - # heatmap_numpy, tag_numpy, ans[i], use_udp=self.use_udp) - # ans = [ans] - # - # return ans, scores + return [], [] From 036237d0299a5e6ff68c4c8ff2beff4e30c76cbe Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 16 Jun 2021 15:56:19 +0800 Subject: [PATCH 14/98] refactor ae --- mmpose/core/evaluation/__init__.py | 13 +- mmpose/core/evaluation/bottom_up_eval.py | 566 +++++++----------- .../models/detectors/associative_embedding.py | 101 +++- mmpose/models/detectors/paf.py | 90 ++- .../heads/topdown_heatmap_simple_head.py | 4 +- tests/test_evaluation/test_bottom_up_eval.py | 185 +++--- 6 files changed, 438 insertions(+), 521 deletions(-) diff --git a/mmpose/core/evaluation/__init__.py b/mmpose/core/evaluation/__init__.py index 7ee250465e..de0503e62b 100644 --- a/mmpose/core/evaluation/__init__.py +++ b/mmpose/core/evaluation/__init__.py @@ -1,6 +1,6 @@ -from .bottom_up_eval import (aggregate_results, aggregate_results_paf, - get_group_preds, get_multi_stage_outputs, - get_multi_stage_outputs_paf) +from .bottom_up_eval import (aggregate_scale, aggregate_stage_flip, + flip_feature_maps, get_group_preds, + split_ae_outputs) from .eval_hooks import DistEvalHook, EvalHook from .mesh_eval import compute_similarity_transform from .pose3d_eval import keypoint_mpjpe @@ -13,9 +13,8 @@ __all__ = [ 'EvalHook', 'DistEvalHook', 'pose_pck_accuracy', 'keypoints_from_heatmaps', 'keypoints_from_regression', 'keypoint_pck_accuracy', 'keypoint_auc', - 'keypoint_epe', 'get_group_preds', 'get_multi_stage_outputs', - 'get_multi_stage_outputs_paf', 'aggregate_results_paf', - 'aggregate_results', 'compute_similarity_transform', 'post_dark_udp', - 'keypoint_mpjpe', 'keypoints_from_heatmaps3d', + 'keypoint_epe', 'get_group_preds', 'split_ae_outputs', 'flip_feature_maps', + 'aggregate_stage_flip', 'aggregate_scale', 'compute_similarity_transform', + 'post_dark_udp', 'keypoint_mpjpe', 'keypoints_from_heatmaps3d', 'multilabel_classification_accuracy' ] diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 24b1f75fdb..a2b883da8a 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -5,422 +5,282 @@ warp_affine_joints) -def _get_multi_stage_heatmaps(outputs, - outputs_flip, - with_heatmaps, - flip_index=None, - project2image=True, - size_projected=None, - align_corners=False, - num_joints=None, - flip_paf=False): - """Inference the model to get multi-stage outputs (heatmaps & tags), and - resize them to base sizes. +def split_ae_outputs(outputs, num_joints, with_heatmaps, with_ae): + """Split multi-stage outputs into heatmaps & tags. Args: - outputs (list(torch.Tensor)): Outputs of network. - outputs_flip (list(torch.Tensor)): Flip outputs of network. + outputs (list(torch.Tensor)): Outputs of network + num_joints (int): Number of joints with_heatmaps (list[bool]): Option to output heatmaps for different stages. - flip_index (list[int]): Keypoint flip index. - project2image (bool): Option to resize to base scale. - size_projected ([w, h]): Base size of heatmaps. - align_corners (bool): Align corners when performing interpolation. - num_joints (int): Number of joints. - flip_paf (bool): Whether to flip for paf maps. - + with_ae (list[bool]): Option to output + ae tags for different stages. Returns: tuple: A tuple containing multi-stage outputs. - - - outputs_with_flipped (list(torch.Tensor)): List of simple outputs - and flip outputs. - - heatmaps (torch.Tensor): Multi-stage heatmaps that are resized to - the base size. + - heatmaps (list(torch.Tensor)): multi-stage heatmaps. + - tags (list(torch.Tensor)): multi-stage tags. """ - outputs_with_flipped = outputs - heatmaps_avg = 0 - num_heatmaps = 0 heatmaps = [] - - flip_test = outputs_flip is not None + tags = [] # aggregate heatmaps from different stages for i, output in enumerate(outputs): - if i != len(outputs) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs[-1].size(2), outputs[-1].size(3)), - mode='bilinear', - align_corners=align_corners) - + # staring index of the associative embeddings + offset_feat = num_joints if with_heatmaps[i] else 0 if with_heatmaps[i]: - if num_joints is not None: - heatmaps_avg += output[:, :num_joints] - else: - heatmaps_avg += output - num_heatmaps += 1 - - if num_heatmaps > 0: - heatmaps.append(heatmaps_avg / num_heatmaps) - - if flip_test and flip_index: - # perform flip testing - heatmaps_avg = 0 - num_heatmaps = 0 - - for i, output in enumerate(outputs_flip): - if i != len(outputs_flip) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs_flip[-1].size(2), outputs_flip[-1].size(3)), - mode='bilinear', - align_corners=align_corners) - output = torch.flip(output, [3]) - outputs_with_flipped.append(output) - - if with_heatmaps[i]: - if flip_paf: - heatmaps_avg[:, ::2, :, :] -= output[:, - flip_index[::2], :, :] - heatmaps_avg[:, - 1::2, :, :] += output[:, - flip_index[1::2], :, :] - else: - if num_joints is not None: - heatmaps_avg += output[:, : - num_joints][:, flip_index, :, :] - else: - heatmaps_avg += output[:, flip_index, :, :] - num_heatmaps += 1 - - heatmaps.append(heatmaps_avg / num_heatmaps) + heatmaps.append(output[:, :num_joints]) + if with_ae[i]: + tags.append(output[:, offset_feat:]) + return heatmaps, tags - if project2image and size_projected: - heatmaps = [ - torch.nn.functional.interpolate( - hms, - size=(size_projected[1], size_projected[0]), - mode='bilinear', - align_corners=align_corners) for hms in heatmaps - ] - - return outputs_with_flipped, heatmaps - - -def _get_multi_stage_tags(outputs, - outputs_flip, - with_heatmaps, - with_ae, - tag_per_joint=True, - flip_index=None, - project2image=True, - size_projected=None, - align_corners=False, - num_joints=None): - """Inference the model to get multi-stage outputs (heatmaps & tags), and - resize them to base sizes. - Args: - outputs (list(torch.Tensor)): Outputs of network. - outputs_flip (list(torch.Tensor)): Flip outputs of network. - with_heatmaps (list[bool]): Option to output - heatmaps for different stages. - with_ae (list[bool]): Option to output - ae tags for different stages. - tag_per_joint (bool): Option to use one tag map per joint. - flip_index (list[int]): Keypoint flip index. - project2image (bool): Option to resize to base scale. - size_projected ([w, h]): Base size of heatmaps. - align_corners (bool): Align corners when performing interpolation. - num_joints (int): Number of joints. +def flip_feature_maps(feature_maps, flip_index=None, flip_output=False): + """Flip the feature maps and swap the channels. + Args: + feature_maps (list(torch.Tensor)): Feature maps. + flip_index (list(int) | None): Channel-flip indexes. If None, + do not flip channels. + flip_output (bool): Whether to perform horizontal-flip. Returns: - tags (torch.Tensor): Multi-stage tags that are resized to - the base size. + flipped_feature_maps (list(torch.Tensor)): Flipped feature_maps. """ + flipped_feature_maps = [] + for feature_map in feature_maps: + if flip_output: + feature_map = torch.flip(feature_map, [3]) + if flip_index is not None: + flipped_feature_maps.append(feature_map[:, flip_index, :, :]) + else: + flipped_feature_maps.append(feature_map) - tags = [] + return flipped_feature_maps - flip_test = outputs_flip is not None - # aggregate tags from different stages - for i, output in enumerate(outputs): - if i != len(outputs) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs[-1].size(2), outputs[-1].size(3)), - mode='bilinear', - align_corners=align_corners) +def _resize_average(feature_maps, align_corners, index=-1, resize_size=None): + """Resize the feature maps and compute the average. - # staring index of the associative embeddings - offset_feat = num_joints if with_heatmaps[i] else 0 - - if with_ae[i]: - tags.append(output[:, offset_feat:]) + Args: + feature_maps (list(torch.Tensor)): Feature maps. + align_corners (bool): Align corners when performing interpolation. + index (int): If `resize_size' is None, the target size is the size + of the indexed feature maps. + resize_size ([w, h]): The target size. + Returns: + feature_maps_avg (list(torch.Tensor)): Averaged feature_maps. + """ - if flip_test and flip_index: - # perform flip testing + if feature_maps is None: + return None + feature_maps_avg = 0 - for i, output in enumerate(outputs_flip): - if i != len(outputs_flip) - 1: - output = torch.nn.functional.interpolate( - output, - size=(outputs_flip[-1].size(2), outputs_flip[-1].size(3)), - mode='bilinear', - align_corners=align_corners) - output = torch.flip(output, [3]) + feature_map_list = _resize_concate( + feature_maps, align_corners, index=index, resize_size=resize_size) + for feature_map in feature_map_list: + feature_maps_avg += feature_map - offset_feat = num_joints if with_heatmaps[i] else 0 + feature_maps_avg /= len(feature_map_list) + return [feature_maps_avg] - if with_ae[i]: - tags.append(output[:, offset_feat:]) - if tag_per_joint: - tags[-1] = tags[-1][:, flip_index, :, :] - if project2image and size_projected: - tags = [ - torch.nn.functional.interpolate( - tms, - size=(size_projected[1], size_projected[0]), - mode='bilinear', - align_corners=align_corners) for tms in tags - ] - - return tags - - -def get_multi_stage_outputs(outputs, - outputs_flip, - num_joints, - with_heatmaps, - with_ae, - tag_per_joint=True, - flip_index=None, - project2image=True, - size_projected=None, - align_corners=False): - """Inference the model to get multi-stage outputs (heatmaps & tags), and - resize them to base sizes. +def _resize_unsqueeze_concat(feature_maps, + align_corners, + index=-1, + resize_size=None): + """Resize, unsqueeze and concatenate the feature_maps. - Args: - outputs (list(torch.Tensor)): Outputs of network - outputs_flip (list(torch.Tensor)): Flip outputs of network - num_joints (int): Number of joints - with_heatmaps (list[bool]): Option to output - heatmaps for different stages. - with_ae (list[bool]): Option to output - ae tags for different stages. - tag_per_joint (bool): Option to use one tag map per joint. - flip_index (list[int]): Keypoint flip index. - project2image (bool): Option to resize to base scale. - size_projected ([w, h]): Base size of heatmaps. + Args: + feature_maps (list(torch.Tensor)): Feature maps. align_corners (bool): Align corners when performing interpolation. - + index (int): If `resize_size' is None, the target size is the size + of the indexed feature maps. + resize_size ([w, h]): The target size. Returns: - tuple: A tuple containing multi-stage outputs. + output_feature_maps (list(torch.Tensor)): Averaged feature_maps. + """ + if feature_maps is None: + return None + feature_map_list = _resize_concate( + feature_maps, align_corners, index=index, resize_size=resize_size) + + feat_dim = len(feature_map_list[0].shape) - 1 + output_feature_maps = torch.cat( + [torch.unsqueeze(fmap, dim=feat_dim + 1) for fmap in feature_map_list], + dim=feat_dim + 1) + return output_feature_maps + + +def _resize_concate(feature_maps, align_corners, index=-1, resize_size=None): + """Resize and concatenate the feature_maps. - - outputs (list(torch.Tensor)): List of simple outputs and - flip outputs. - - heatmaps (torch.Tensor): Multi-stage heatmaps that are resized to - the base size. - - tags (torch.Tensor): Multi-stage tags that are resized to - the base size. + Args: + feature_maps (list(torch.Tensor)): Feature maps. + align_corners (bool): Align corners when performing interpolation. + index (int): If `resize_size' is None, the target size is the size + of the indexed feature maps. + resize_size ([w, h]): The target size. + Returns: + feature_map_list (list(torch.Tensor)): Averaged feature_maps. """ - outputs_with_flipped, heatmaps = _get_multi_stage_heatmaps( - outputs, outputs_flip, num_joints, with_heatmaps, flip_index, - project2image, size_projected, align_corners) - - tags = _get_multi_stage_tags(outputs, outputs_flip, num_joints, - with_heatmaps, with_ae, tag_per_joint, - flip_index, project2image, size_projected, - align_corners) - - return outputs_with_flipped, heatmaps, tags - - -def get_multi_stage_outputs_paf(outputs, - outputs_flip, - with_heatmaps, - with_pafs, - flip_index=None, - flip_index_paf=None, - project2image=True, - size_projected=None, - align_corners=False): - """Inference the model to get multi-stage outputs (heatmaps & pafs), and + if feature_maps is None: + return None + + feature_map_list = [] + + if index < 0: + index += len(feature_maps) + + if resize_size is None: + resize_size = (feature_maps[index].size(2), + feature_maps[index].size(3)) + + for feature_map in feature_maps: + ori_size = (feature_map.size(2), feature_map.size(3)) + if ori_size != resize_size: + feature_map = torch.nn.functional.interpolate( + feature_map, + size=resize_size, + mode='bilinear', + align_corners=align_corners) + + feature_map_list.append(feature_map) + + return feature_map_list + + +def aggregate_stage_flip(feature_maps, + feature_maps_flip, + index=-1, + project2image=True, + size_projected=None, + align_corners=False, + aggregate_stage='concat', + aggregate_flip='average'): + """Inference the model to get multi-stage outputs (heatmaps & tags), and resize them to base sizes. Args: - outputs (dict): Outputs of network, including heatmaps and pafs. - outputs_flip (dict): Flip outputs of network, including - heatmaps and pafs. - with_heatmaps (list[bool]): Option to output - heatmaps for different stages. - with_pafs (list[bool]): Option to output - pafs for different stages. - flip_index (list[int]): Keypoint flip index. - flip_index_paf (list[int]): PAF flip index. + feature_maps (list(torch.Tensor)): feature_maps can be heatmaps, + tags, and pafs. + feature_maps_flip (list(torch.Tensor) | None): flipped feature_maps. + feature maps can be heatmaps, tags, and pafs. project2image (bool): Option to resize to base scale. size_projected ([w, h]): Base size of heatmaps. align_corners (bool): Align corners when performing interpolation. + aggregate_stage (str): Methods to aggregate multi-stage feature maps. + Options: 'concat', 'average'. + 'concat': Concatenate the original and the flipped feature maps. + 'average': Get the average of the original and the flipped + feature maps.. + Default: 'concat. + aggregate_flip (str): Methods to aggregate the original and + the flipped feature maps. + Options: 'concat', 'average', 'none'. + 'concat': Concatenate the original and the flipped feature maps. + 'average': Get the average of the original and the flipped + feature maps.. + 'none': no flipped feature maps. + Default: 'average. Returns: - tuple: A tuple containing multi-stage outputs. - - - outputs (list(torch.Tensor)): List of simple outputs and - flip outputs. - - heatmaps (torch.Tensor): Multi-stage heatmaps that are resized to - the base size. - - pafs (torch.Tensor): Multi-stage pafs that are resized to - the base size. + - output_feature_maps (List(torch.Tensor[NxKxWxH])): + Aggregated feature maps. """ - outputs['heatmaps'], heatmaps = _get_multi_stage_heatmaps( - outputs['heatmaps'], - outputs_flip['heatmaps'], - with_heatmaps, - flip_index, - project2image, - size_projected, - align_corners, - flip_paf=True) - - outputs['pafs'], pafs = _get_multi_stage_heatmaps( - outputs['pafs'], - outputs_flip['pafs'], - with_heatmaps, - flip_index, - project2image, - size_projected, - align_corners, - flip_paf=True) - - return outputs, heatmaps, pafs - - -def aggregate_results(scale, - aggregated_heatmaps, - tags_list, - heatmaps, - tags, - test_scale_factor, - project2image, - flip_test, - align_corners=False): - """Aggregate multi-scale outputs. + output_feature_maps = [] - Note: - batch size: N - keypoints num : K - heatmap width: W - heatmap height: H + if aggregate_stage == 'average': + _aggregate_stage_func = _resize_average + elif aggregate_stage == 'concat': + _aggregate_stage_func = _resize_concate + else: + NotImplementedError() - Args: - scale (int): current scale - aggregated_heatmaps (torch.Tensor | None): Aggregated heatmaps. - tags_list (list(torch.Tensor)): Tags list of previous scale. - heatmaps (List(torch.Tensor[NxKxWxH])): A batch of heatmaps. - tags (List(torch.Tensor[NxKxWxH])): A batch of tag maps. - test_scale_factor (List(int)): Multi-scale factor for testing. - project2image (bool): Option to resize to base scale. - flip_test (bool): Option to use flip test. - align_corners (bool): Align corners when performing interpolation. + if project2image and size_projected: + _origin = _aggregate_stage_func( + feature_maps, + align_corners, + index=index, + resize_size=(size_projected[1], size_projected[0])) + + _flipped = _aggregate_stage_func( + feature_maps_flip, + align_corners, + index=index, + resize_size=(size_projected[1], size_projected[0])) + else: + _origin = _aggregate_stage_func( + feature_maps, align_corners, index=index, resize_size=None) + _flipped = _aggregate_stage_func( + feature_maps_flip, align_corners, index=index, resize_size=None) + + if aggregate_flip == 'average': + assert feature_maps_flip is not None + for _ori, _fli in zip(_origin, _flipped): + output_feature_maps.append((_ori + _fli) / 2.0) + + elif aggregate_flip == 'concat': + assert feature_maps_flip is not None + output_feature_maps.append(*_origin) + output_feature_maps.append(*_flipped) + + elif aggregate_flip == 'none': + if isinstance(_origin, list): + output_feature_maps.append(*_origin) + else: + output_feature_maps.append(_origin) + else: + NotImplementedError() - Return: - tuple: a tuple containing aggregated results. + return output_feature_maps - - aggregated_heatmaps (torch.Tensor): Heatmaps with multi scale. - - tags_list (list(torch.Tensor)): Tag list of multi scale. - """ - if scale == 1 or len(test_scale_factor) == 1: - if aggregated_heatmaps is not None and not project2image: - tags = [ - torch.nn.functional.interpolate( - tms, - size=(aggregated_heatmaps.size(2), - aggregated_heatmaps.size(3)), - mode='bilinear', - align_corners=align_corners) for tms in tags - ] - for tms in tags: - tags_list.append(torch.unsqueeze(tms, dim=4)) - - heatmaps_avg = (heatmaps[0] + - heatmaps[1]) / 2.0 if flip_test else heatmaps[0] - - if aggregated_heatmaps is None: - aggregated_heatmaps = heatmaps_avg - elif project2image: - aggregated_heatmaps += heatmaps_avg - else: - aggregated_heatmaps += torch.nn.functional.interpolate( - heatmaps_avg, - size=(aggregated_heatmaps.size(2), aggregated_heatmaps.size(3)), - mode='bilinear', - align_corners=align_corners) - - return aggregated_heatmaps, tags_list - - -def aggregate_results_paf(aggregated_heatmaps, - aggregated_pafs, - heatmaps, - pafs, - project2image, - flip_test, - align_corners=False): + +def aggregate_scale(feature_maps_list, + project2image, + align_corners=False, + aggregate_scale='average'): """Aggregate multi-scale outputs. Note: batch size: N keypoints num : K - paf maps num: P heatmap width: W heatmap height: H Args: - aggregated_heatmaps (torch.Tensor | None): Aggregated heatmaps. - aggregated_pafs (torch.Tensor | None): Aggregated pafs. - heatmaps (List(torch.Tensor[NxKxWxH])): A batch of heatmaps. - pafs (List(torch.Tensor[NxPxWxH])): A batch of paf maps. + feature_maps_list (list(torch.Tensor)): Aggregated feature maps. project2image (bool): Option to resize to base scale. - flip_test (bool): Option to use flip test. align_corners (bool): Align corners when performing interpolation. + aggregate_scale (str): Methods to aggregate multi-scale feature maps. + Options: 'average', 'unsqueeze_concat'. + 'average': Get the average of the feature maps. + 'unsqueeze_concat': Concatenate the feature maps along new axis. + Default: 'average. Return: - tuple: a tuple containing aggregated results. - - - aggregated_heatmaps (torch.Tensor): Heatmaps with multi scale. - - aggregated_pafs (torch.Tensor): PAF maps of multi scale. + - output_feature_maps (torch.Tensor): Aggregated feature maps. """ - heatmaps_avg = (heatmaps[0] + - heatmaps[1]) / 2.0 if flip_test else heatmaps[0] - if aggregated_heatmaps is None: - aggregated_heatmaps = heatmaps_avg - elif project2image: - aggregated_heatmaps += heatmaps_avg - else: - aggregated_heatmaps += torch.nn.functional.interpolate( - heatmaps_avg, - size=(aggregated_heatmaps.size(2), aggregated_heatmaps.size(3)), - mode='bilinear', - align_corners=align_corners) - - pafs_avg = (pafs[0] + pafs[1]) / 2.0 if flip_test else pafs[0] - if aggregated_pafs is None: - aggregated_pafs = pafs_avg - elif project2image: - aggregated_pafs += pafs_avg + if aggregate_scale == 'average': + if project2image: + # already resized to the base size + output_feature_maps = 0 + for feature_map in feature_maps_list: + output_feature_maps += feature_map + output_feature_maps /= len(feature_maps_list) + + else: + output_feature_maps = _resize_average( + feature_maps_list, align_corners, index=0, resize_size=None) + + elif aggregate_scale == 'unsqueeze_concat': + output_feature_maps = _resize_unsqueeze_concat( + feature_maps_list, align_corners, index=0, resize_size=None) else: - aggregated_pafs += torch.nn.functional.interpolate( - pafs_avg, - size=(aggregated_pafs.size(2), aggregated_pafs.size(3)), - mode='bilinear', - align_corners=align_corners) + NotImplementedError() - return aggregated_heatmaps, aggregated_pafs + return output_feature_maps def get_group_preds(grouped_joints, diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index 30c07a66f4..26bd4a515e 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -5,8 +5,9 @@ from mmcv.image import imwrite from mmcv.visualization.image import imshow -from mmpose.core.evaluation import (aggregate_results, get_group_preds, - get_multi_stage_outputs) +from mmpose.core.evaluation import (aggregate_scale, aggregate_stage_flip, + flip_feature_maps, get_group_preds, + split_ae_outputs) from mmpose.core.post_processing.group import HeatmapParser from mmpose.core.visualization import imshow_keypoints from .. import builder @@ -48,7 +49,6 @@ def __init__(self, self.backbone = builder.build_backbone(backbone) if keypoint_head is not None: - if 'loss_keypoint' not in keypoint_head and loss_pose is not None: warnings.warn( '`loss_pose` for BottomUp is deprecated, ' @@ -225,8 +225,9 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): result = {} - aggregated_heatmaps = None - tags_list = [] + scale_heatmaps_list = [] + scale_tags_list = [] + for idx, s in enumerate(sorted(test_scale_factor, reverse=True)): image_resized = aug_data[idx].to(img.device) @@ -234,45 +235,85 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): if self.with_keypoint: outputs = self.keypoint_head(features) + heatmaps, tags = split_ae_outputs(outputs, + self.test_cfg['num_joints'], + self.test_cfg['with_heatmaps'], + self.test_cfg['with_ae']) + if self.test_cfg.get('flip_test', True): # use flip test features_flipped = self.backbone( torch.flip(image_resized, [3])) if self.with_keypoint: outputs_flipped = self.keypoint_head(features_flipped) + + heatmaps_flipped, tags_flipped = split_ae_outputs( + outputs_flipped, self.test_cfg['num_joints'], + self.test_cfg['with_heatmaps'], self.test_cfg['with_ae']) + + heatmaps_flipped = flip_feature_maps( + heatmaps_flipped, + flip_index=img_metas['flip_index'], + flip_output=True) + if self.test_cfg['tag_per_joint']: + tags_flipped = flip_feature_maps( + tags_flipped, + flip_index=img_metas['flip_index'], + flip_output=True) + else: + tags_flipped = flip_feature_maps( + tags_flipped, flip_index=None, flip_output=True) + else: outputs_flipped = None - _, heatmaps, tags = get_multi_stage_outputs( - outputs, - outputs_flipped, - self.test_cfg['num_joints'], - self.test_cfg['with_heatmaps'], - self.test_cfg['with_ae'], - self.test_cfg['tag_per_joint'], - img_metas['flip_index'], - self.test_cfg['project2image'], - base_size, - align_corners=self.use_udp) - - aggregated_heatmaps, tags_list = aggregate_results( - s, - aggregated_heatmaps, - tags_list, + # TODO: move `align_corners' to test_cfg + aggregated_heatmaps = aggregate_stage_flip( heatmaps, + heatmaps_flipped, + index=-1, + project2image=self.test_cfg['project2image'], + size_projected=base_size, + align_corners=self.use_udp, + aggregate_stage='average', + aggregate_flip='average') + + aggregated_tags = aggregate_stage_flip( tags, - test_scale_factor, - self.test_cfg['project2image'], - self.test_cfg.get('flip_test', True), - align_corners=self.use_udp) + tags_flipped, + index=-1, + project2image=self.test_cfg['project2image'], + size_projected=base_size, + align_corners=self.use_udp, + aggregate_stage='concat', + aggregate_flip='concat') + + if s == 1 or len(test_scale_factor) == 1: + if isinstance(aggregated_tags, list): + scale_tags_list.extend(aggregated_tags) + else: + scale_tags_list.append(aggregated_tags) + + if isinstance(aggregated_heatmaps, list): + scale_heatmaps_list.extend(aggregated_heatmaps) + else: + scale_heatmaps_list.append(aggregated_heatmaps) + + aggregated_heatmaps = aggregate_scale( + scale_heatmaps_list, + self.test_cfg['project2image'], + aggregate_scale='average', + align_corners=self.use_udp) - # average heatmaps of different scales - aggregated_heatmaps = aggregated_heatmaps / float( - len(test_scale_factor)) - tags = torch.cat(tags_list, dim=4) + aggregated_tags = aggregate_scale( + scale_tags_list, + self.test_cfg['project2image'], + aggregate_scale='unsqueeze_concat', + align_corners=self.use_udp) # perform grouping - grouped, scores = self.parser.parse(aggregated_heatmaps, tags, + grouped, scores = self.parser.parse(aggregated_heatmaps, + aggregated_tags, self.test_cfg['adjust'], self.test_cfg['refine']) diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 54431a30f7..17063a6bb6 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -5,14 +5,21 @@ from mmcv.image import imwrite from mmcv.visualization.image import imshow -from mmpose.core.evaluation import (aggregate_results_paf, get_group_preds, - get_multi_stage_outputs_paf) +from mmpose.core.evaluation import (aggregate_scale, aggregate_stage_flip, + flip_feature_maps, get_group_preds) from mmpose.core.post_processing.group import PAFParser from mmpose.core.visualization import imshow_keypoints from .. import builder from ..builder import POSENETS from .base import BasePose +try: + from mmcv.runner import auto_fp16 +except ImportError: + warnings.warn('auto_fp16 from mmpose will be deprecated from v0.15.0' + 'Please install mmcv>=1.1.4') + from mmpose.core import auto_fp16 + @POSENETS.register_module() class PartAffinityField(BasePose): @@ -39,6 +46,7 @@ def __init__(self, pretrained=None, loss_pose=None): super().__init__() + self.fp16_enabled = False self.backbone = builder.build_backbone(backbone) @@ -70,6 +78,7 @@ def init_weights(self, pretrained=None): if self.with_keypoint: self.keypoint_head.init_weights() + @auto_fp16(apply_to=('img', )) def forward(self, img=None, targets=None, @@ -214,6 +223,9 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): result = {} + scale_heatmaps_list = [] + scale_pafs_list = [] + aggregated_heatmaps = None aggregated_pafs = None for idx, s in enumerate(sorted(test_scale_factor, reverse=True)): @@ -222,6 +234,8 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): features = self.backbone(image_resized) if self.with_keypoint: outputs = self.keypoint_head(features) + heatmaps = outputs['heatmaps'] + pafs = outputs['pafs'] if self.test_cfg.get('flip_test', True): # use flip test @@ -229,33 +243,65 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): torch.flip(image_resized, [3])) if self.with_keypoint: outputs_flipped = self.keypoint_head(features_flipped) + + heatmaps_flipped = outputs_flipped['heatmaps'] + pafs_flipped = outputs_flipped['pafs'] + + heatmaps_flipped = flip_feature_maps( + heatmaps_flipped, + flip_index=img_metas['flip_index'], + flip_output=True) + pafs_flipped = flip_feature_maps( + pafs_flipped, + img_metas['flip_index_paf'], + flip_output=True) + else: outputs_flipped = None - _, heatmaps, pafs = get_multi_stage_outputs_paf( - outputs, - outputs_flipped, - self.test_cfg['with_heatmaps'], - self.test_cfg['with_pafs'], - img_metas['flip_index'], - img_metas['flip_index_paf'], - self.test_cfg['project2image'], - base_size, - align_corners=self.use_udp) - - aggregated_heatmaps, aggregated_pafs = aggregate_results_paf( - aggregated_heatmaps, - aggregated_pafs, + # TODO: move `align_corners' to test_cfg + aggregated_heatmaps = aggregate_stage_flip( heatmaps, + heatmaps_flipped, + index=-1, + project2image=self.test_cfg['project2image'], + size_projected=base_size, + align_corners=self.use_udp, + aggregate_stage='average', + aggregate_flip='average') + + aggregated_pafs = aggregate_stage_flip( pafs, - self.test_cfg['project2image'], - self.test_cfg.get('flip_test', True), - align_corners=self.use_udp) + pafs_flipped, + index=-1, + project2image=self.test_cfg['project2image'], + size_projected=base_size, + align_corners=self.use_udp, + aggregate_stage='average', + aggregate_flip='average') + + if isinstance(aggregated_pafs, list): + scale_pafs_list.extend(aggregated_pafs) + else: + scale_pafs_list.append(aggregated_pafs) + + if isinstance(aggregated_heatmaps, list): + scale_heatmaps_list.extend(aggregated_heatmaps) + else: + scale_heatmaps_list.append(aggregated_heatmaps) # average heatmaps of different scales - aggregated_heatmaps = aggregated_heatmaps / float( - len(test_scale_factor)) - aggregated_pafs = aggregated_pafs / float(len(test_scale_factor)) + aggregated_heatmaps = aggregate_scale( + scale_heatmaps_list, + self.test_cfg['project2image'], + aggregate_scale='average', + align_corners=self.use_udp) + + aggregated_pafs = aggregate_scale( + scale_pafs_list, + self.test_cfg['project2image'], + aggregate_scale='average', + align_corners=self.use_udp) # perform grouping grouped, scores = self.parser.parse(aggregated_heatmaps, diff --git a/mmpose/models/heads/topdown_heatmap_simple_head.py b/mmpose/models/heads/topdown_heatmap_simple_head.py index 6f253fede8..7a3499e167 100644 --- a/mmpose/models/heads/topdown_heatmap_simple_head.py +++ b/mmpose/models/heads/topdown_heatmap_simple_head.py @@ -31,8 +31,8 @@ class TopdownHeatmapSimpleHead(TopdownHeatmapBaseHead): in_index (int|Sequence[int]): Input feature index. Default: -1 input_transform (str|None): Transformation type of input features. Options: 'resize_concat', 'multiple_select', None. - 'resize_concat': Multiple feature maps will be resize to the - same size as first one and than concat together. + 'resize_concat': Multiple feature maps will be resized to the + same size as the first one and then concat together. Usually used in FCN head of HRNet. 'multiple_select': Multiple feature maps will be bundle into a list and passed into decode head. diff --git a/tests/test_evaluation/test_bottom_up_eval.py b/tests/test_evaluation/test_bottom_up_eval.py index bcb3788ade..dd9f6ee045 100644 --- a/tests/test_evaluation/test_bottom_up_eval.py +++ b/tests/test_evaluation/test_bottom_up_eval.py @@ -1,117 +1,88 @@ -import copy - import numpy as np import torch -from mmpose.core import (aggregate_results, get_group_preds, - get_multi_stage_outputs) +from mmpose.core import (aggregate_scale, aggregate_stage_flip, + flip_feature_maps, get_group_preds, split_ae_outputs) + + +def test_split_ae_outputs(): + fake_outputs = [torch.zeros((1, 4, 2, 2))] + heatmaps, tags = split_ae_outputs( + fake_outputs, num_joints=4, with_heatmaps=[False], with_ae=[True]) + + +def test_flip_feature_maps(): + fake_outputs = [torch.zeros((1, 4, 2, 2))] + _ = flip_feature_maps(fake_outputs, None, False) + _ = flip_feature_maps(fake_outputs, flip_index=[1, 0], flip_output=True) -def test_get_multi_stage_outputs(): +def test_aggregate_stage_flip(): fake_outputs = [torch.zeros((1, 4, 2, 2))] fake_flip_outputs = [torch.ones((1, 4, 2, 2))] - # outputs_flip - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=None, - num_joints=4, with_heatmaps=[False], - with_ae=[True]) - assert heatmaps == [] - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=None, - num_joints=2, with_heatmaps=[True], - with_ae=[True]) - assert len(heatmaps) == 1 - flip_index = [1, 0] - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=fake_flip_outputs, - num_joints=2, with_heatmaps=[True], - with_ae=[True], flip_index=flip_index) - assert len(heatmaps) == 2 - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - tag_per_joint=False, - outputs_flip=fake_flip_outputs, - num_joints=2, with_heatmaps=[True], - with_ae=[True], flip_index=flip_index) - assert len(heatmaps) == 2 - # with heatmaps & with ae - fake_outputs = [torch.zeros((1, 4, 2, 2)), torch.ones((1, 2, 4, 4))] - fake_flip_outputs = [torch.ones((1, 4, 2, 2)), torch.ones((1, 2, 4, 4))] - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=None, - num_joints=2, with_heatmaps=[True, False], - with_ae=[True, True]) - assert torch.allclose(heatmaps[0], torch.tensor(0.)) - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=fake_flip_outputs, - num_joints=2, with_heatmaps=[True, True], - with_ae=[True, False]) - assert torch.allclose(heatmaps[0], torch.tensor(0.5)) - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=fake_flip_outputs, - num_joints=2, with_heatmaps=[True, False], - with_ae=[True, False], flip_index=flip_index) - assert torch.allclose(heatmaps[0], torch.tensor(0.)) - # size_projected - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=None, - num_joints=2, with_heatmaps=[True, True], - with_ae=[True, False], - size_projected=(8, 8)) - assert heatmaps[0].shape == torch.Size([1, 2, 8, 8]) - outputs, heatmaps, tags = \ - get_multi_stage_outputs(outputs=copy.deepcopy(fake_outputs), - outputs_flip=fake_flip_outputs, - num_joints=2, with_heatmaps=[True, True], - with_ae=[True, False], - align_corners=True) - assert torch.allclose(heatmaps[0], torch.tensor(0.5)) - - -def test_aggregate_results(): - fake_heatmaps = [torch.zeros((1, 2, 2, 2))] - fake_tags = [torch.zeros((1, 2, 2, 2))] - aggregated_heatmaps, tags_list = \ - aggregate_results(scale=1, aggregated_heatmaps=None, tags_list=[], - heatmaps=fake_heatmaps, tags=fake_tags, - test_scale_factor=[1], project2image=True, - flip_test=False) - assert torch.allclose(aggregated_heatmaps, torch.tensor(0.)) - fake_aggr_heatmaps = torch.ones(1, 2, 2, 2) - aggregated_heatmaps, tags_list = \ - aggregate_results(scale=1, aggregated_heatmaps=fake_aggr_heatmaps, - tags_list=[], heatmaps=fake_heatmaps, - tags=fake_tags, test_scale_factor=[1], - project2image=True, flip_test=False) - assert torch.allclose(aggregated_heatmaps, torch.tensor(1.)) - aggregated_heatmaps, tags_list = \ - aggregate_results(scale=1, aggregated_heatmaps=fake_aggr_heatmaps, - tags_list=[], heatmaps=fake_heatmaps, - tags=fake_tags, test_scale_factor=[1], - project2image=True, flip_test=False, - align_corners=True) - assert torch.allclose(aggregated_heatmaps, torch.tensor(1.)) - fake_heatmaps = [torch.zeros((1, 2, 2, 2)), torch.ones((1, 2, 2, 2))] - fake_aggr_heatmaps = torch.ones(1, 2, 4, 4) - aggregated_heatmaps, tags_list = \ - aggregate_results(scale=1, aggregated_heatmaps=fake_aggr_heatmaps, - tags_list=[], heatmaps=fake_heatmaps, - tags=fake_tags, test_scale_factor=[1], - project2image=False, flip_test=True) - assert aggregated_heatmaps.shape == torch.Size((1, 2, 4, 4)) - aggregated_heatmaps, tags_list = \ - aggregate_results(scale=2, aggregated_heatmaps=fake_aggr_heatmaps, - tags_list=[], heatmaps=fake_heatmaps, - tags=fake_tags, test_scale_factor=[1, 2], - project2image=False, flip_test=True) - assert aggregated_heatmaps.shape == torch.Size((1, 2, 4, 4)) + output = aggregate_stage_flip( + fake_outputs, + fake_flip_outputs, + index=-1, + project2image=True, + size_projected=(4, 4), + align_corners=False, + aggregate_stage='concat', + aggregate_flip='average') + assert isinstance(output, list) + + output = aggregate_stage_flip( + fake_outputs, + fake_flip_outputs, + index=-1, + project2image=True, + size_projected=(4, 4), + align_corners=False, + aggregate_stage='average', + aggregate_flip='average') + assert isinstance(output, list) + + output = aggregate_stage_flip( + fake_outputs, + fake_flip_outputs, + index=-1, + project2image=True, + size_projected=(4, 4), + align_corners=False, + aggregate_stage='average', + aggregate_flip='concat') + assert isinstance(output, list) + + output = aggregate_stage_flip( + fake_outputs, + fake_flip_outputs, + index=-1, + project2image=True, + size_projected=(4, 4), + align_corners=False, + aggregate_stage='concat', + aggregate_flip='concat') + assert isinstance(output, list) + + +def test_aggregate_scale(): + fake_outputs = [torch.zeros((1, 4, 2, 2)), torch.zeros((1, 4, 2, 2))] + output = aggregate_scale( + fake_outputs, + project2image=True, + align_corners=False, + aggregate_scale='average') + assert isinstance(output, torch.Tensor) + assert output.shape == fake_outputs[0].shape + + output = aggregate_scale( + fake_outputs, + project2image=True, + align_corners=False, + aggregate_scale='unsqueeze_concat') + + assert isinstance(output, torch.Tensor) + assert len(output.shape) == len(fake_outputs[0].shape) + 1 def test_get_group_preds(): From 1ddd4257e2bb62a5db4d5f2edc5285f63ed99ee0 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 16 Jun 2021 16:19:21 +0800 Subject: [PATCH 15/98] rm project2image in aggregate_scale --- mmpose/core/evaluation/bottom_up_eval.py | 17 ++++------------- .../models/detectors/associative_embedding.py | 10 ++++------ mmpose/models/detectors/paf.py | 2 -- tests/test_evaluation/test_bottom_up_eval.py | 10 ++-------- 4 files changed, 10 insertions(+), 29 deletions(-) diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index a2b883da8a..3a97084bd3 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -108,7 +108,7 @@ def _resize_unsqueeze_concat(feature_maps, output_feature_maps = torch.cat( [torch.unsqueeze(fmap, dim=feat_dim + 1) for fmap in feature_map_list], dim=feat_dim + 1) - return output_feature_maps + return [output_feature_maps] def _resize_concate(feature_maps, align_corners, index=-1, resize_size=None): @@ -237,7 +237,6 @@ def aggregate_stage_flip(feature_maps, def aggregate_scale(feature_maps_list, - project2image, align_corners=False, aggregate_scale='average'): """Aggregate multi-scale outputs. @@ -263,16 +262,8 @@ def aggregate_scale(feature_maps_list, """ if aggregate_scale == 'average': - if project2image: - # already resized to the base size - output_feature_maps = 0 - for feature_map in feature_maps_list: - output_feature_maps += feature_map - output_feature_maps /= len(feature_maps_list) - - else: - output_feature_maps = _resize_average( - feature_maps_list, align_corners, index=0, resize_size=None) + output_feature_maps = _resize_average( + feature_maps_list, align_corners, index=0, resize_size=None) elif aggregate_scale == 'unsqueeze_concat': output_feature_maps = _resize_unsqueeze_concat( @@ -280,7 +271,7 @@ def aggregate_scale(feature_maps_list, else: NotImplementedError() - return output_feature_maps + return output_feature_maps[0] def get_group_preds(grouped_joints, diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index 26bd4a515e..85eb8bcd21 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -301,15 +301,13 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): aggregated_heatmaps = aggregate_scale( scale_heatmaps_list, - self.test_cfg['project2image'], - aggregate_scale='average', - align_corners=self.use_udp) + align_corners=self.use_udp, + aggregate_scale='average') aggregated_tags = aggregate_scale( scale_tags_list, - self.test_cfg['project2image'], - aggregate_scale='unsqueeze_concat', - align_corners=self.use_udp) + align_corners=self.use_udp, + aggregate_scale='unsqueeze_concat') # perform grouping grouped, scores = self.parser.parse(aggregated_heatmaps, diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 17063a6bb6..41617145e5 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -293,13 +293,11 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): # average heatmaps of different scales aggregated_heatmaps = aggregate_scale( scale_heatmaps_list, - self.test_cfg['project2image'], aggregate_scale='average', align_corners=self.use_udp) aggregated_pafs = aggregate_scale( scale_pafs_list, - self.test_cfg['project2image'], aggregate_scale='average', align_corners=self.use_udp) diff --git a/tests/test_evaluation/test_bottom_up_eval.py b/tests/test_evaluation/test_bottom_up_eval.py index dd9f6ee045..f4e8622a67 100644 --- a/tests/test_evaluation/test_bottom_up_eval.py +++ b/tests/test_evaluation/test_bottom_up_eval.py @@ -68,18 +68,12 @@ def test_aggregate_stage_flip(): def test_aggregate_scale(): fake_outputs = [torch.zeros((1, 4, 2, 2)), torch.zeros((1, 4, 2, 2))] output = aggregate_scale( - fake_outputs, - project2image=True, - align_corners=False, - aggregate_scale='average') + fake_outputs, align_corners=False, aggregate_scale='average') assert isinstance(output, torch.Tensor) assert output.shape == fake_outputs[0].shape output = aggregate_scale( - fake_outputs, - project2image=True, - align_corners=False, - aggregate_scale='unsqueeze_concat') + fake_outputs, align_corners=False, aggregate_scale='unsqueeze_concat') assert isinstance(output, torch.Tensor) assert len(output.shape) == len(fake_outputs[0].shape) + 1 From 2eaad8471dd299ebfc8dbb71ed2c4f81ef8592ae Mon Sep 17 00:00:00 2001 From: jinsheng Date: Thu, 17 Jun 2021 12:17:22 +0800 Subject: [PATCH 16/98] update head/init --- mmpose/models/heads/__init__.py | 5 ++++- mmpose/models/heads/deconv_head.py | 3 ++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/mmpose/models/heads/__init__.py b/mmpose/models/heads/__init__.py index 5f4da4484b..fa9727dae2 100644 --- a/mmpose/models/heads/__init__.py +++ b/mmpose/models/heads/__init__.py @@ -1,8 +1,10 @@ from .ae_higher_resolution_head import AEHigherResolutionHead from .ae_simple_head import AESimpleHead +from .deconv_head import DeconvHead from .deeppose_regression_head import DeepposeRegressionHead from .hmr_head import HMRMeshHead from .interhand_3d_head import Interhand3DHead +from .paf_head import PAFHead from .temporal_regression_head import TemporalRegressionHead from .topdown_heatmap_base_head import TopdownHeatmapBaseHead from .topdown_heatmap_multi_stage_head import (TopdownHeatmapMSMUHead, @@ -13,5 +15,6 @@ 'TopdownHeatmapSimpleHead', 'TopdownHeatmapMultiStageHead', 'TopdownHeatmapMSMUHead', 'TopdownHeatmapBaseHead', 'AEHigherResolutionHead', 'AESimpleHead', 'DeepposeRegressionHead', - 'TemporalRegressionHead', 'Interhand3DHead', 'HMRMeshHead' + 'TemporalRegressionHead', 'Interhand3DHead', 'HMRMeshHead', 'PAFHead', + 'DeconvHead' ] diff --git a/mmpose/models/heads/deconv_head.py b/mmpose/models/heads/deconv_head.py index cf1df6ce68..8550f505c2 100644 --- a/mmpose/models/heads/deconv_head.py +++ b/mmpose/models/heads/deconv_head.py @@ -2,9 +2,10 @@ from mmcv.cnn import (build_conv_layer, build_upsample_layer, constant_init, normal_init) -from mmpose.models.builder import build_loss +from mmpose.models.builder import HEADS, build_loss +@HEADS.register_module() class DeconvHead(nn.Module): """Simple deconv head. From 6c2423091ed3431f0ece10e0f4c638c0c1b424c3 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Thu, 17 Jun 2021 15:55:01 +0800 Subject: [PATCH 17/98] update paf post-processing --- .../coco/hrnet_w32_coco_512x512.py | 204 +++++ mmpose/core/evaluation/bottom_up_eval.py | 3 + mmpose/core/post_processing/group.py | 716 ++++++++++++++++-- .../datasets/bottom_up/bottom_up_coco.py | 12 +- .../datasets/pipelines/bottom_up_transform.py | 40 +- mmpose/datasets/pipelines/shared_transform.py | 34 +- .../models/detectors/associative_embedding.py | 18 +- mmpose/models/detectors/paf.py | 32 +- mmpose/models/heads/paf_head.py | 19 +- 9 files changed, 939 insertions(+), 139 deletions(-) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py new file mode 100644 index 0000000000..68cc1ee3b0 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -0,0 +1,204 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=512, + base_size=256, + base_sigma=2, + heatmap_size=[128], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='https://download.openmmlab.com/mmpose/' + 'pretrain_models/hrnet_w32-36af842e.pth', + backbone=dict( + type='HRNet', + in_channels=3, + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + ), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=17, + num_deconv_layers=0, + extra=dict(final_conv_kernel=1, ), + loss_keypoint=dict(type='MaskedMSELoss', )), + ], + paf_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=38, + num_deconv_layers=0, + extra=dict(final_conv_kernel=1, ), + loss_keypoint=dict(type='MaskedMSELoss', )), + ], + heatmap_index=[0], + paf_index=[0], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0, 1], + keys=['targets', 'masks']), + dict( + type='Collect', + keys=['img', 'joints', 'targets', 'masks'], + meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'flip_index_paf' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 3a97084bd3..4761fa2fcd 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -294,6 +294,9 @@ def get_group_preds(grouped_joints, Returns: list: List of the pose result for each person. """ + if len(grouped_joints) == 0: + return [] + if use_udp: if grouped_joints[0].shape[0] > 0: heatmap_size_t = np.array(heatmap_size, dtype=np.float32) - 1.0 diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index aeb17cfef1..09ed3fa40b 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -3,9 +3,14 @@ # Original licence: Copyright (c) 2017, umich-vl, under BSD 3-Clause License. # ------------------------------------------------------------------------------ +from abc import ABCMeta, abstractmethod + +import cv2 import numpy as np import torch from munkres import Munkres +from scipy.ndimage.filters import maximum_filter +from scipy.ndimage.morphology import generate_binary_structure from mmpose.core.evaluation import post_dark_udp @@ -117,7 +122,7 @@ def _match_by_tag(inp, params): class _Params: - """A class of parameter. + """A class of parameters for keypoint grouping. Args: cfg(Config): config. @@ -126,10 +131,7 @@ class _Params: def __init__(self, cfg): self.num_joints = cfg['num_joints'] self.max_num_people = cfg['max_num_people'] - self.detection_threshold = cfg['detection_threshold'] - self.tag_threshold = cfg['tag_threshold'] - self.use_detection_val = cfg['use_detection_val'] self.ignore_too_much = cfg['ignore_too_much'] if self.num_joints == 17: @@ -141,12 +143,11 @@ def __init__(self, cfg): self.joint_order = list(np.arange(self.num_joints)) -class HeatmapParser: - """The heatmap parser for post processing.""" +class BaseBottomUpParser(metaclass=ABCMeta): + """The base bottom-up parser for post processing.""" def __init__(self, cfg): self.params = _Params(cfg) - self.tag_per_joint = cfg['tag_per_joint'] self.pool = torch.nn.MaxPool2d(cfg['nms_kernel'], 1, cfg['nms_padding']) self.use_udp = cfg.get('use_udp', False) @@ -167,6 +168,91 @@ def nms(self, heatmaps): return heatmaps + @staticmethod + def top_k_value(feature_maps, M): + """Find top_k values in the feature_maps. + + Note: + batch size: N + number of keypoints: K + heatmap height: H + heatmap width: W + max number of people: M + + Args: + feature_maps (torch.Tensor[NxKxHxW]) + + Return: + - val_k (torch.Tensor[NxKxM]): + top k value of feature map per keypoint. + - ind_k (torch.Tensor[NxKxM]): + index of the selected locations. + """ + N, K, H, W = feature_maps.size() + feature_maps = feature_maps.view(N, K, -1) + val_k, ind_k = feature_maps.topk(M, dim=2) + + return val_k, ind_k + + @staticmethod + def adjust(ans, heatmaps, use_udp=False): + """Adjust the coordinates for better accuracy. + + Note: + batch size: N + number of keypoints: K + heatmap height: H + heatmap width: W + + Args: + ans (list(np.ndarray)): Keypoint predictions. + heatmaps (torch.Tensor[NxKxHxW]): Heatmaps. + """ + + if use_udp: + for i in range(len(ans)): + if ans[i].shape[0] > 0: + ans[i][..., :2] = post_dark_udp(ans[i][..., :2].copy(), + heatmaps[i:i + 1, :]) + else: + _, _, H, W = heatmaps.shape + for batch_id, people in enumerate(ans): + for people_id, people_i in enumerate(people): + for joint_id, joint in enumerate(people_i): + if joint[2] > 0: + x, y = joint[0:2] + xx, yy = int(x), int(y) + tmp = heatmaps[batch_id][joint_id] + if tmp[min(H - 1, yy + 1), + xx] > tmp[max(0, yy - 1), xx]: + y += 0.25 + else: + y -= 0.25 + + if tmp[yy, min(W - 1, xx + + 1)] > tmp[yy, max(0, xx - 1)]: + x += 0.25 + else: + x -= 0.25 + ans[batch_id][people_id, joint_id, + 0:2] = (x + 0.5, y + 0.5) + return ans + + @abstractmethod + def parse(self, *args, **kwargs): + """Group keypoints into poses.""" + + +class HeatmapParser(BaseBottomUpParser): + """The heatmap parser for post processing.""" + + def __init__(self, cfg): + super().__init__(cfg) + self.tag_per_joint = cfg['tag_per_joint'] + + self.params.tag_threshold = cfg['tag_threshold'] + self.params.use_detection_val = cfg['use_detection_val'] + def match(self, tag_k, loc_k, val_k): """Group keypoints to human poses in a batch. @@ -188,7 +274,7 @@ def _match(x): return list(map(_match, zip(tag_k, loc_k, val_k))) def top_k(self, heatmaps, tags): - """Find top_k values in an image. + """Find top_k values in the feature maps. Note: batch size: N @@ -214,69 +300,33 @@ def top_k(self, heatmaps, tags): - val_k (np.ndarray[NxKxM]): top k value of feature map per keypoint. """ + heatmaps = self.nms(heatmaps) N, K, H, W = heatmaps.size() - heatmaps = heatmaps.view(N, K, -1) - val_k, ind = heatmaps.topk(self.params.max_num_people, dim=2) + val_k, ind_k = self.top_k_value(heatmaps, self.params.max_num_people) + + x = ind_k % W + y = ind_k // W + + loc_k = torch.stack((x, y), dim=3) tags = tags.view(tags.size(0), tags.size(1), W * H, -1) if not self.tag_per_joint: tags = tags.expand(-1, self.params.num_joints, -1, -1) - tag_k = torch.stack( - [torch.gather(tags[..., i], 2, ind) for i in range(tags.size(3))], - dim=3) - - x = ind % W - y = ind // W - - ind_k = torch.stack((x, y), dim=3) + tag_k = torch.stack([ + torch.gather(tags[..., i], 2, ind_k) for i in range(tags.size(3)) + ], + dim=3) ans = { 'tag_k': tag_k.cpu().numpy(), - 'loc_k': ind_k.cpu().numpy(), + 'loc_k': loc_k.cpu().numpy(), 'val_k': val_k.cpu().numpy() } return ans - @staticmethod - def adjust(ans, heatmaps): - """Adjust the coordinates for better accuracy. - - Note: - batch size: N - number of keypoints: K - heatmap height: H - heatmap width: W - - Args: - ans (list(np.ndarray)): Keypoint predictions. - heatmaps (torch.Tensor[NxKxHxW]): Heatmaps. - """ - _, _, H, W = heatmaps.shape - for batch_id, people in enumerate(ans): - for people_id, people_i in enumerate(people): - for joint_id, joint in enumerate(people_i): - if joint[2] > 0: - x, y = joint[0:2] - xx, yy = int(x), int(y) - tmp = heatmaps[batch_id][joint_id] - if tmp[min(H - 1, yy + 1), xx] > tmp[max(0, yy - 1), - xx]: - y += 0.25 - else: - y -= 0.25 - - if tmp[yy, min(W - 1, xx + 1)] > tmp[yy, - max(0, xx - 1)]: - x += 0.25 - else: - x -= 0.25 - ans[batch_id][people_id, joint_id, - 0:2] = (x + 0.5, y + 0.5) - return ans - @staticmethod def refine(heatmap, tag, keypoints, use_udp=False): """Given initial keypoint predictions, we identify missing joints. @@ -380,13 +430,7 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): ans = self.match(**self.top_k(heatmaps, tags)) if adjust: - if self.use_udp: - for i in range(len(ans)): - if ans[i].shape[0] > 0: - ans[i][..., :2] = post_dark_udp( - ans[i][..., :2].copy(), heatmaps[i:i + 1, :]) - else: - ans = self.adjust(ans, heatmaps) + ans = self.adjust(ans, heatmaps, self.use_udp) scores = [i[:, 2].mean() for i in ans[0]] @@ -406,16 +450,542 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): return ans, scores -# TODO -class PAFParser: +class PAFParser(BaseBottomUpParser): """The paf parser for post processing. Paper ref: Cao, Zhe, et al. "OpenPose: realtime multi-person 2D pose estimation using Part Affinity Fields." (TPAMI'2019) + + TODO: Rewrite this class. Currently, this part is copied from + 'https://github.com/tensorboy/' + 'pytorch_Realtime_Multi-Person_Pose_Estimation' """ def __init__(self, cfg): - self.params = _Params(cfg) + super().__init__(cfg) + + self.thre1 = 0.1 + self.thre2 = 0.05 + + # Heatmap indices to find each limb (joint connection). + # Eg: limb_type=1 is + # Neck->LShoulder, so joint_to_limb_heatmap_relationship[1] + # represents the + # indices of heatmaps to look for joints: neck=1, LShoulder=5 + # TODO should be self.ann_info['skeleton'] + self.joint_to_limb_heatmap_relationship = [[15, 13], [13, + 11], [16, 14], + [14, 12], [11, 12], [5, 11], + [6, 12], [5, 6], [5, 7], + [6, 8], [7, 9], [8, 10], + [1, 2], [0, 1], [0, 2], + [1, 3], [2, 4], [3, 5], + [4, 6]] + + # PAF indices containing the x and y coordinates of the PAF for a + # given limb. + # Eg: limb_type=1 is Neck->LShoulder, so + # PAFneckLShoulder_x=paf_xy_coords_per_limb[1][0] and + # PAFneckLShoulder_y=paf_xy_coords_per_limb[1][1] + self.paf_xy_coords_per_limb = [[0, 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], [28, 29], [30, 31], [32, 33], + [34, 35], [36, 37]] + + self.NUM_LIMBS = len(self.joint_to_limb_heatmap_relationship) + + def find_peaks(self, img): + """Given a (grayscale) image, find local maxima whose value is above a + given threshold (param['thre1']) + + :param img: Input image (2d array) where we want to find peaks + :return: 2d np.array containing the [x,y] coordinates of each + peak found + in the image + """ + + peaks_binary = (maximum_filter( + img, footprint=generate_binary_structure(2, 1)) == img) * ( + img > self.thre1) + # Note reverse ([::-1]): we return [[x y], [x y]...] instead of + # [[y x], [y + # x]...] + return np.array(np.nonzero(peaks_binary)[::-1]).T + + def compute_resized_coords(self, coords, resizeFactor): + """ + Given the index/coordinates of a cell in some input array (e.g. image + ), + provides the new coordinates if that array was resized by making it + resizeFactor times bigger. + E.g.: image of size 3x3 is resized to 6x6 (resizeFactor=2), we'd like + to + know the new coordinates of cell [1,2] -> Function would return [2.5, + 4.5] + :param coords: Coordinates (indices) of a cell in some input array + :param resizeFactor: Resize coefficient = shape_dest/shape_source. + E.g.: + resizeFactor=2 means the destination array is twice as big as the + original one + :return: Coordinates in an array of size + shape_dest=resizeFactor*shape_source, expressing the array indices + of the + closest point to 'coords' if an image of size shape_source was + resized to + shape_dest + """ + + # 1) Add 0.5 to coords to get coordinates of center of the pixel + # (e.g. + # index [0,0] represents the pixel at location [0.5,0.5]) + # 2) Transform those coordinates to shape_dest, by multiplying by + # resizeFactor + # 3) That number represents the location of the pixel center in the + # new array, + # so subtract 0.5 to get coordinates of the array index/indices + # (revert + # step 1) + return (np.array(coords, dtype=float) + 0.5) * resizeFactor - 0.5 + + def NMS(self, + heatmaps, + upsampFactor=1., + bool_refine_center=True, + bool_gaussian_filt=False): + """ + NonMaximaSuppression: find peaks (local maxima) in a set of grayscale + images + :param heatmaps: set of grayscale images on which to find local maxima + (3d np.array, + with dimensions image_height x image_width x num_heatmaps) + :param upsampFactor: Size ratio between CPM heatmap output and the + input image size. + Eg: upsampFactor=16 if original image was 480x640 and heatmaps are + 30x40xN + :param bool_refine_center: Flag indicating whether: + - False: Simply return the low-res peak found upscaled by upsampFactor + (subject to grid-snap) + - True: (Recommended, very accurate) Upsample a small + patch around each + low-res peak and + fine-tune the location of the peak at the resolution of the original + input image + :param bool_gaussian_filt: Flag indicating whether to apply a + 1d-GaussianFilter (smoothing) + to each upsampled patch before fine-tuning the location of each peak. + :return: a NUM_JOINTS x 4 np.array where each row represents a joint + type (0=nose, 1=neck...) + and the columns indicate the {x,y} position, the score (probability) + and a unique id (counter) + """ + # MODIFIED BY CARLOS: Instead of upsampling the heatmaps to + # heatmap_avg and + # then performing NMS to find peaks, this step can be sped up + # by ~25-50x by: + # (9-10ms [with GaussFilt] or 5-6ms [without GaussFilt] vs + # 250-280ms on RoG + # 1. Perform NMS at (low-res) CPM's output resolution + # 1.1. Find peaks using scipy.ndimage.filters.maximum_filter + # 2. Once a peak is found, take a patch of 5x5 centered around + # the peak, upsample it, and + # fine-tune the position of the actual maximum. + # '-> That's equivalent to having found the peak on heatmap_avg, + # but much faster because we only + # upsample and scan the 5x5 patch instead of the full (e.g.) + # 480x640 + + joint_list_per_joint_type = [] + cnt_total_joints = 0 + + # For every peak found, win_size specifies how many pixels in each + # direction from the peak we take to obtain the patch that will be + # upsampled. Eg: win_size=1 -> patch is 3x3; win_size=2 -> 5x5 + # (for BICUBIC interpolation to be accurate, win_size needs to + # be >=2!) + win_size = 2 + + for joint in range(heatmaps.shape[2]): + map_orig = heatmaps[:, :, joint] + peak_coords = self.find_peaks(map_orig) + peaks = np.zeros((len(peak_coords), 4)) + for i, peak in enumerate(peak_coords): + if bool_refine_center: + x_min, y_min = np.maximum(0, peak - win_size) + x_max, y_max = np.minimum( + np.array(map_orig.T.shape) - 1, peak + win_size) + + # Take a small patch around each peak and only upsample + # that + # tiny region + patch = map_orig[y_min:y_max + 1, x_min:x_max + 1] + map_upsamp = cv2.resize( + patch, + None, + fx=upsampFactor, + fy=upsampFactor, + interpolation=cv2.INTER_CUBIC) + + # Gaussian filtering takes an average of 0.8ms/peak + # (and there might be + # more than one peak per joint!) -> For now, skip it + # (it's + # accurate enough) + map_upsamp = self.gaussian_filter( + map_upsamp, + sigma=3) if bool_gaussian_filt else map_upsamp + + # Obtain the coordinates of the maximum value in the + # patch + location_of_max = np.unravel_index(map_upsamp.argmax(), + map_upsamp.shape) + # Remember that peaks indicates [x,y] -> need to + # reverse it for + # [y,x] + location_of_patch_center = self.compute_resized_coords( + peak[::-1] - [y_min, x_min], upsampFactor) + # Calculate the offset wrt to the patch center where + # the actual + # maximum is + refined_center = ( + location_of_max - location_of_patch_center) + peak_score = map_upsamp[location_of_max] + else: + refined_center = [0, 0] + # Flip peak coordinates since they are [x,y] instead + # of [y,x] + peak_score = map_orig[tuple(peak[::-1])] + peaks[i, :] = tuple([ + int(round(x)) for x in self.compute_resized_coords( + peak_coords[i], upsampFactor) + refined_center[::-1] + ]) + (peak_score, cnt_total_joints) + cnt_total_joints += 1 + joint_list_per_joint_type.append(peaks) + + return joint_list_per_joint_type + + def find_connected_joints(self, + paf_upsamp, + joint_list_per_joint_type, + num_intermed_pts=10): + """For every type of limb (eg: forearm, shin, etc.), look for every + potential pair of joints (eg: every wrist-elbow combination) and + evaluate the PAFs to determine which pairs are indeed body limbs. + + :param paf_upsamp: PAFs upsampled to the original input image + resolution + :param joint_list_per_joint_type: See 'return' doc of NMS() + :param num_intermed_pts: Int indicating how many intermediate + points to take + between joint_src and joint_dst, at which the PAFs will be + evaluated + :return: List of NUM_LIMBS rows. For every limb_type (a row) + we store + a list of all limbs of that type found (eg: all the right + forearms). + For each limb (each item in connected_limbs[limb_type]), we + store 5 cells: + # {joint_src_id,joint_dst_id}: a unique number associated with + each joint, + # limb_score_penalizing_long_dist: a score of how good a + connection + of the joints is, penalized if the limb length is too long + # {joint_src_index,joint_dst_index}: the index of the joint + within + all the joints of that type found (eg: the 3rd right elbow + found) + """ + connected_limbs = [] + + # Auxiliary array to access paf_upsamp quickly + limb_intermed_coords = np.empty((4, num_intermed_pts), dtype=np.intp) + for limb_type in range(self.NUM_LIMBS): + # List of all joints of type A found, where A is specified + # by limb_type + # (eg: a right forearm starts in a right elbow) + joints_src = joint_list_per_joint_type[ + self.joint_to_limb_heatmap_relationship[limb_type][0]] + # List of all joints of type B found, where B is specified + # by limb_type + # (eg: a right forearm ends in a right wrist) + joints_dst = joint_list_per_joint_type[ + self.joint_to_limb_heatmap_relationship[limb_type][1]] + if len(joints_src) == 0 or len(joints_dst) == 0: + # No limbs of this type found (eg: no right forearms + # found because + # we didn't find any right wrists or right elbows) + connected_limbs.append([]) + else: + connection_candidates = [] + # Specify the paf index that contains the x-coord of + # the paf for + # this limb + limb_intermed_coords[ + 2, :] = self.paf_xy_coords_per_limb[limb_type][0] + # And the y-coord paf index + limb_intermed_coords[ + 3, :] = self.paf_xy_coords_per_limb[limb_type][1] + for i, joint_src in enumerate(joints_src): + # Try every possible joints_src[i]-joints_dst[j] + # pair and see + # if it's a feasible limb + for j, joint_dst in enumerate(joints_dst): + # Subtract the position of both joints to obtain + # the + # direction of the potential limb + limb_dir = joint_dst[:2] - joint_src[:2] + # Compute the distance/length of the potential + # limb (norm + # of limb_dir) + limb_dist = np.sqrt(np.sum(limb_dir**2)) + 1e-8 + limb_dir = limb_dir / limb_dist + # Normalize limb_dir to be a unit vector + + # Linearly distribute num_intermed_pts points + # from the x + # coordinate of joint_src to the x coordinate + # of joint_dst + limb_intermed_coords[1, :] = np.round( + np.linspace( + joint_src[0], + joint_dst[0], + num=num_intermed_pts)) + limb_intermed_coords[0, :] = np.round( + np.linspace( + joint_src[1], + joint_dst[1], + num=num_intermed_pts) + ) # Same for the y coordinate + intermed_paf = paf_upsamp[limb_intermed_coords[0, :], + limb_intermed_coords[1, :], + limb_intermed_coords[ + 2:4, :]].T + + score_intermed_pts = intermed_paf.dot(limb_dir) + score_penalizing_long_dist = score_intermed_pts.mean( + ) + min(0.5 * paf_upsamp.shape[0] / limb_dist - 1, 0) + # Criterion 1: At least 80% of the intermediate + # points have + # a score higher than thre2 + criterion1 = ( + np.count_nonzero(score_intermed_pts > self.thre2) > + 0.8 * num_intermed_pts) + # Criterion 2: Mean score, penalized for large limb + # distances (larger than half the image height), is + # positive + criterion2 = (score_penalizing_long_dist > 0) + if criterion1 and criterion2: + # Last value is the combined paf(+limb_dist) + # + heatmap + # scores of both joints + connection_candidates.append([ + i, j, score_penalizing_long_dist, + score_penalizing_long_dist + joint_src[2] + + joint_dst[2] + ]) + + # Sort connection candidates based on their + # score_penalizing_long_dist + connection_candidates = sorted( + connection_candidates, key=lambda x: x[2], reverse=True) + connections = np.empty((0, 5)) + # There can only be as many limbs as the smallest number of + # source + # or destination joints (eg: only 2 forearms if there's 5 + # wrists + # but 2 elbows) + max_connections = min(len(joints_src), len(joints_dst)) + # Traverse all potential joint connections (sorted by their + # score) + for potential_connection in connection_candidates: + i, j, s = potential_connection[0:3] + # Make sure joints_src[i] or joints_dst[j] haven't + # already been + # connected to other joints_dst or joints_src + if i not in connections[:, 3] and j not in connections[:, + 4]: + # [joint_src_id, joint_dst_id, + # limb_score_penalizing_long_dist, joint_src_index, + # joint_dst_index] + connections = np.vstack([ + connections, + [joints_src[i][3], joints_dst[j][3], s, i, j] + ]) + # Exit if we've already established max_connections + # connections (each joint can't be connected to more + # than + # one joint) + if len(connections) >= max_connections: + break + connected_limbs.append(connections) + + return connected_limbs + + def group_limbs_of_same_person(self, connected_limbs, joint_list): + """Associate limbs belonging to the same person together. + + :param connected_limbs: See 'return' doc of + find_connected_joints() + :param joint_list: unravel'd version of joint_list_per_joint + [See 'return' doc of NMS()] + :return: 2d np.array of size num_people x (NUM_JOINTS+2). + For each person found: + # First NUM_JOINTS columns contain the index (in joint_list) + of the joints associated + with that person (or -1 if their i-th joint wasn't found) + # 2nd-to-last column: Overall score of the joints+limbs that + belong to this person + # Last column: Total count of joints found for this person + """ + person_to_joint_assoc = [] + + for limb_type in range(self.NUM_LIMBS): + joint_src_type, joint_dst_type = \ + self.joint_to_limb_heatmap_relationship[limb_type] + + for limb_info in connected_limbs[limb_type]: + person_assoc_idx = [] + for person, person_limbs in enumerate(person_to_joint_assoc): + if person_limbs[joint_src_type] == limb_info[ + 0] or person_limbs[joint_dst_type] == limb_info[1]: + person_assoc_idx.append(person) + + # If one of the joints has been associated to a person, + # and either + # the other joint is also associated with the same + # person or not + # associated to anyone yet: + if len(person_assoc_idx) == 1: + person_limbs = person_to_joint_assoc[person_assoc_idx[0]] + # If the other joint is not associated to anyone yet, + if person_limbs[joint_dst_type] != limb_info[1]: + # Associate it with the current person + person_limbs[joint_dst_type] = limb_info[1] + # Increase the number of limbs associated to + # this person + person_limbs[-1] += 1 + # And update the total score (+= heatmap score + # of joint_dst + # + score of connecting joint_src with joint_dst) + person_limbs[-2] += joint_list[ + limb_info[1].astype(int), 2] + limb_info[2] + elif len(person_assoc_idx + ) == 2: # if found 2 and disjoint, merge them + person1_limbs = person_to_joint_assoc[person_assoc_idx[0]] + person2_limbs = person_to_joint_assoc[person_assoc_idx[1]] + membership = ((person1_limbs >= 0) & + (person2_limbs >= 0))[:-2] + if not membership.any( + ): # If both people have no same joints connected, + # merge them into a single person + # Update which joints are connected + person1_limbs[:-2] += (person2_limbs[:-2] + 1) + # Update the overall score and total count of + # joints + # connected by summing their counters + person1_limbs[-2:] += person2_limbs[-2:] + # Add the score of the current joint connection + # to the + # overall score + person1_limbs[-2] += limb_info[2] + person_to_joint_assoc.pop(person_assoc_idx[1]) + else: # Same case as len(person_assoc_idx)==1 above + person1_limbs[joint_dst_type] = limb_info[1] + person1_limbs[-1] += 1 + person1_limbs[-2] += joint_list[ + limb_info[1].astype(int), 2] + limb_info[2] + else: # No person has claimed any of these joints, create + # a new person + # Initialize person info to all -1 + # (no joint associations) + row = -1 * np.ones(20) + # Store the joint info of the new connection + row[joint_src_type] = limb_info[0] + row[joint_dst_type] = limb_info[1] + # Total count of connected joints for this person: 2 + row[-1] = 2 + # Compute overall score: score joint_src + score + # joint_dst + score connection + # {joint_src,joint_dst} + row[-2] = sum(joint_list[limb_info[:2].astype(int), + 2]) + limb_info[2] + person_to_joint_assoc.append(row) + + # Delete people who have very few parts connected + people_to_delete = [] + for person_id, person_info in enumerate(person_to_joint_assoc): + if person_info[-1] < 3 or person_info[-2] / person_info[-1] < 0.2: + people_to_delete.append(person_id) + # Traverse the list in reverse order so we delete indices + # starting from the + # last one (otherwise, removing item for example 0 would + # modify the indices of + # the remaining people to be deleted!) + for index in people_to_delete[::-1]: + person_to_joint_assoc.pop(index) + + # Appending items to a np.array can be very costly + # (allocating new memory, copying over the array, + # then adding new row) + # Instead, we treat the set of people as a list + # (fast to append items) and + # only convert to np.array at the end + return np.array(person_to_joint_assoc) + + def output_format(self, joint_list, person_to_joint_assoc): + ans = [] + + if len(person_to_joint_assoc) > 0: + num_kpt = person_to_joint_assoc.shape[1] - 2 + + for person in person_to_joint_assoc: + ans_person = np.zeros((num_kpt, 5)) + for j in range(num_kpt): + joint_id = person[j] + if joint_id < 0: + continue + assert j == joint_list[joint_id, 4] + ans_person[j] = joint_list[joint_id] + ans.append(ans_person) + + return ans + + def match(self, heatmaps, pafs): + # Bottom-up approach: + # Step 1: find all joints in the image (organized by joint type: + # [0]=nose, [1]=neck...) + # 4 = img_orig.shape[0] / float(heatmaps.shape[0]) + + heatmaps = np.transpose(heatmaps[0], [1, 2, 0]) + pafs = np.transpose(pafs[0], [1, 2, 0]) + + joint_list_per_joint_type = self.NMS(heatmaps, 4) + # joint_list is an unravel'd version of joint_list_per_joint, + # where we + # add a 5th column to indicate the joint_type (0=nose, 1=neck...) + joint_list = np.array([ + tuple(peak) + (joint_type, ) + for joint_type, joint_peaks in enumerate(joint_list_per_joint_type) + for peak in joint_peaks + ]) + + # Step 2: find which joints go together to form limbs + # (which wrists go + # with which elbows) + paf_upsamp = cv2.resize( + pafs, (heatmaps.shape[1] * 4, heatmaps.shape[0] * 4), + interpolation=cv2.INTER_CUBIC) + connected_limbs = self.find_connected_joints( + paf_upsamp, joint_list_per_joint_type) + + # Step 3: associate limbs that belong to the same person + person_to_joint_assoc = self.group_limbs_of_same_person( + connected_limbs, joint_list) + + ans = self.output_format(joint_list, person_to_joint_assoc) + scores = [person[-2] for person in person_to_joint_assoc] + + return ans, scores def parse(self, heatmaps, pafs, adjust=True, refine=True): """Group keypoints into poses given heatmap and paf. @@ -438,4 +1008,16 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): - scores (list): Score of people. """ - return [], [] + # assert 0, 'The post-process of paf have not been completed.' + ans, scores = self.match(heatmaps.cpu().numpy(), pafs.cpu().numpy()) + + if adjust: + if self.use_udp: + for i in range(len(ans)): + if ans[i].shape[0] > 0: + ans[i][..., :2] = post_dark_udp( + ans[i][..., :2].copy(), heatmaps[i:i + 1, :]) + else: + ans = self.adjust(ans, heatmaps) + + return ans, scores diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index a063719763..2b97c7553b 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -61,12 +61,12 @@ def __init__(self, 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15 ] - # joint index starts from 1 - self.ann_info['skeleton'] = [[16, 14], [14, 12], [17, 15], [15, 13], - [12, 13], [6, 12], [7, 13], [6, 7], - [6, 8], [7, 9], [8, 10], [9, 11], [2, 3], - [1, 2], [1, 3], [2, 4], [3, 5], [4, 6], - [5, 7]] + # joint index starts from 0 + self.ann_info['skeleton'] = [[15, 13], [13, 11], [16, 14], [14, 12], + [11, 12], [5, 11], [6, 12], [5, 6], + [5, 7], [6, 8], [7, 9], [8, 10], [1, 2], + [0, 1], [0, 2], [1, 3], [2, 4], [3, 5], + [4, 6]] self.ann_info['flip_index_paf'] = [ 4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 12, 13, 10, 11, 14, 15, 18, 19, 16, diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index de43945e42..495b7f1e9f 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -283,17 +283,20 @@ def _accumulate_paf_map_(self, pafs, src, dst, count): min_y = max(np.floor(min(src[1], dst[1]) - self.limb_width), 0) max_y = min( np.ceil(max(src[1], dst[1]) + self.limb_width), - self.output_size + 1) + self.output_size - 1) range_x = list(range(int(min_x), int(max_x + 1), 1)) range_y = list(range(int(min_y), int(max_y + 1), 1)) - xx, yy = np.meshgrid(range_x, range_y) - delta_x = xx - src[0] - delta_y = yy - src[1] - dist = np.abs(delta_x * unit_limb_vec[1] - delta_y * unit_limb_vec[0]) - mask_local = (dist < self.limb_width) + mask = np.zeros_like(count, dtype=bool) - mask[xx, yy] = mask_local + if len(range_x) > 0 and len(range_y) > 0: + xx, yy = np.meshgrid(range_x, range_y) + delta_x = xx - src[0] + delta_y = yy - src[1] + dist = np.abs(delta_x * unit_limb_vec[1] - + delta_y * unit_limb_vec[0]) + mask_local = (dist < self.limb_width) + mask[xx, yy] = mask_local pafs[0, mask] += unit_limb_vec[0] pafs[1, mask] += unit_limb_vec[1] @@ -312,8 +315,8 @@ def __call__(self, joints): dtype=np.float32) for p in joints: - src = p[sk[0] - 1] - dst = p[sk[1] - 1] + src = p[sk[0]] + dst = p[sk[1]] if src[2] > 0 and dst[2] > 0: self._accumulate_paf_map_(pafs[2 * idx:2 * idx + 2], src[:2], dst[:2], count) @@ -347,9 +350,9 @@ def __call__(self, results): assert len(mask) == len(self.output_size) if np.random.random() < self.flip_prob: - image = image[:, ::-1] - np.zeros_like(image) + image = image[:, ::-1].copy() - np.zeros_like(image) for i, _output_size in enumerate(self.output_size): - mask[i] = mask[i][:, ::-1] + mask[i] = mask[i][:, ::-1].copy() joints[i] = joints[i][:, self.flip_index] joints[i][:, :, 0] = _output_size - joints[i][:, :, 0] - 1 results['img'], results['mask'], results[ @@ -535,19 +538,22 @@ def __call__(self, results): self._generate(results['ann_info']['num_joints'], results['ann_info']['heatmap_size']) target_list = list() - joints_list = results['joints'] + mask_list, joints_list = results['mask'], results['joints'] for scale_id in range(results['ann_info']['num_scales']): heatmaps = heatmap_generator[scale_id](joints_list[scale_id]) target_list.append(heatmaps.astype(np.float32)) - results['target'] = target_list + mask_list[scale_id] = mask_list[scale_id].astype(np.float32) + + results['targets'] = target_list + results['masks'] = mask_list return results @PIPELINES.register_module() class BottomUpGenerateTarget: - """Generate multi-scale heatmap target for bottom-up. + """Generate multi-scale heatmap target for associate embedding. Args: sigma (int): Sigma of heatmap Gaussian @@ -633,13 +639,15 @@ def __call__(self, results): self._generate(results['ann_info']['heatmap_size'], self.skeleton) target_list = list() - joints_list = results['joints'] + mask_list, joints_list = results['mask'], results['joints'] for scale_id in range(results['ann_info']['num_scales']): pafs = paf_generator[scale_id](joints_list[scale_id]) target_list.append(pafs.astype(np.float32)) + mask_list[scale_id] = mask_list[scale_id].astype(np.float32) - results['target'] = target_list + results['targets'] = target_list + results['masks'] = mask_list return results diff --git a/mmpose/datasets/pipelines/shared_transform.py b/mmpose/datasets/pipelines/shared_transform.py index 15e837c9a8..352418e331 100644 --- a/mmpose/datasets/pipelines/shared_transform.py +++ b/mmpose/datasets/pipelines/shared_transform.py @@ -414,29 +414,31 @@ class MultitaskGatherTarget: pipeline_indices (list[int]): Pipeline index of each head. """ - def __init__(self, pipeline_list, pipeline_indices): + def __init__(self, + pipeline_list, + pipeline_indices=None, + keys=('target', 'target_weight')): + self.keys = keys self.pipelines = [] for pipeline in pipeline_list: self.pipelines.append(Compose(pipeline)) - self.pipeline_indices = pipeline_indices + if pipeline_indices is None: + self.pipeline_indices = list(range(len(pipeline_list))) + else: + self.pipeline_indices = pipeline_indices def __call__(self, results): # generate target and target weights using all pipelines - _target, _target_weight = [], [] + pipeline_outputs = [] for pipeline in self.pipelines: - results_head = pipeline(results) - _target.append(results_head['target']) - _target_weight.append(results_head['target_weight']) - - # reorganize generated target, target_weights according - # to self.pipelines_indices - target, target_weight = [], [] - for ind in self.pipeline_indices: - target.append(_target[ind]) - target_weight.append(_target_weight[ind]) - - results['target'] = target - results['target_weight'] = target_weight + pipeline_output = pipeline(results) + pipeline_outputs.append(pipeline_output.copy()) + + for key in self.keys: + result_key = [] + for ind in self.pipeline_indices: + result_key.append(pipeline_outputs[ind].get(key, None)) + results[key] = result_key return results diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index 85eb8bcd21..ed8a568985 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -98,11 +98,11 @@ def forward(self, heatmaps height: H max_num_people: M Args: - img(torch.Tensor[NxCximgHximgW]): Input image. - targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. - masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target + img (torch.Tensor[NxCximgHximgW]): Input image. + targets (List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + masks (List(torch.Tensor[NxHxW])): Masks of multi-scale target heatmaps - joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target + joints (List(torch.Tensor[NxMxKx2])): Joints of multi-scale target heatmaps for ae loss img_metas(dict):Information about val&test By default this includes: @@ -144,13 +144,13 @@ def forward_train(self, img, targets, masks, joints, img_metas, **kwargs): max_num_people: M Args: - img(torch.Tensor[NxCximgHximgW]): Input image. - targets(List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. - masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target + img (torch.Tensor[NxCximgHximgW]): Input image. + targets (List(torch.Tensor[NxKxHxW])): Multi-scale target heatmaps. + masks (List(torch.Tensor[NxHxW])): Masks of multi-scale target heatmaps - joints(List(torch.Tensor[NxMxKx2])): Joints of multi-scale target + joints (List(torch.Tensor[NxMxKx2])): Joints of multi-scale target heatmaps for ae loss - img_metas(dict):Information about val&test + img_metas (dict):Information about val&test By default this includes: - "image_file": image path - "aug_data": input diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 41617145e5..442b283a79 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -100,10 +100,10 @@ def forward(self, max_num_people: M Args: img(torch.Tensor[NxCximgHximgW]): Input image. - targets (list(list)): List of heatmaps and pafs, each of which - multi-scale targets. - masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps. + targets (list(list)): List of heatmaps + and pafs, each of which multi-scale targets. + masks (list(list(torch.Tensor[NxHxW]))): Masks of multi-scale + target heatmaps. img_metas(dict):Information about val&test By default this includes: - "image_file": image path @@ -143,12 +143,12 @@ def forward_train(self, img, targets, masks, img_metas, **kwargs): max_num_people: M Args: - img(torch.Tensor[NxCximgHximgW]): Input image. - targets (list(list)): List of heatmaps and pafs, each of which - multi-scale targets. - masks(List(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps. - img_metas(dict):Information about val&test + img (torch.Tensor[NxCximgHximgW]): Input image. + targets (list(list)): List of heatmaps + and pafs, each of which multi-scale targets. + masks (list(list(torch.Tensor[NxHxW]))): Masks of multi-scale + target heatmaps. + img_metas (dict):Information about val&test By default this includes: - "image_file": image path - "aug_data": input @@ -226,16 +226,14 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): scale_heatmaps_list = [] scale_pafs_list = [] - aggregated_heatmaps = None - aggregated_pafs = None for idx, s in enumerate(sorted(test_scale_factor, reverse=True)): image_resized = aug_data[idx].to(img.device) features = self.backbone(image_resized) if self.with_keypoint: outputs = self.keypoint_head(features) - heatmaps = outputs['heatmaps'] - pafs = outputs['pafs'] + heatmaps = outputs['heatmaps'][-1] + pafs = outputs['pafs'][-1] if self.test_cfg.get('flip_test', True): # use flip test @@ -244,8 +242,8 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): if self.with_keypoint: outputs_flipped = self.keypoint_head(features_flipped) - heatmaps_flipped = outputs_flipped['heatmaps'] - pafs_flipped = outputs_flipped['pafs'] + heatmaps_flipped = outputs_flipped['heatmaps'][-1] + pafs_flipped = outputs_flipped['pafs'][-1] heatmaps_flipped = flip_feature_maps( heatmaps_flipped, @@ -253,7 +251,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): flip_output=True) pafs_flipped = flip_feature_maps( pafs_flipped, - img_metas['flip_index_paf'], + flip_index=img_metas['flip_index_paf'], flip_output=True) else: diff --git a/mmpose/models/heads/paf_head.py b/mmpose/models/heads/paf_head.py index bd1c52c6fd..563b770a78 100644 --- a/mmpose/models/heads/paf_head.py +++ b/mmpose/models/heads/paf_head.py @@ -27,12 +27,12 @@ def __init__(self, heatmap_heads_cfg, paf_heads_cfg, heatmap_index, assert len(paf_heads_cfg) == len(paf_index) # build heatmap heads - self.heatmap_heads_list = [] + self.heatmap_heads_list = nn.ModuleList() for head_cfg in heatmap_heads_cfg: self.heatmap_heads_list.append(build_head(head_cfg)) # build paf heads - self.paf_heads_list = [] + self.paf_heads_list = nn.ModuleList() for head_cfg in paf_heads_cfg: self.paf_heads_list.append(build_head(head_cfg)) @@ -50,19 +50,21 @@ def get_loss(self, outputs, targets, masks): Args: outputs (dict): Outputs of network, including heatmaps and pafs. - targets (list(list)): List of heatmaps and pafs, each of which - multi-scale targets. - masks (list(torch.Tensor[NxHxW])): Masks of multi-scale target - heatmaps and pafs. + targets (list(list)): List of heatmaps + and pafs, each of which multi-scale targets. + masks (list(list(torch.Tensor[NxHxW]))): Masks of multi-scale + target heatmaps. """ losses = dict() heatmap_outputs = outputs['heatmaps'] heatmap_targets = targets[:len(self.heatmap_heads_list)] + heatmap_masks = masks[:len(self.heatmap_heads_list)] for idx, head in enumerate(self.heatmap_heads_list): heatmap_losses = head.get_loss(heatmap_outputs[idx], - heatmap_targets[idx], masks) + heatmap_targets[idx], + heatmap_masks[idx]) if 'heatmap_loss' not in losses: losses['heatmap_loss'] = heatmap_losses['loss'] else: @@ -70,9 +72,10 @@ def get_loss(self, outputs, targets, masks): paf_outputs = outputs['pafs'] paf_targets = targets[len(self.heatmap_heads_list):] + paf_masks = masks[:len(self.heatmap_heads_list)] for idx, head in enumerate(self.paf_heads_list): paf_losses = head.get_loss(paf_outputs[idx], paf_targets[idx], - masks) + paf_masks[idx]) if 'paf_loss' not in losses: losses['paf_loss'] = paf_losses['loss'] else: From a51a4f329e6d8d747eee3978bc3803698145c3d2 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Thu, 17 Jun 2021 16:21:15 +0800 Subject: [PATCH 18/98] fix docstring --- mmpose/core/post_processing/group.py | 138 +++++++++++---------------- 1 file changed, 55 insertions(+), 83 deletions(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 09ed3fa40b..27eccdb9a2 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -464,7 +464,6 @@ class PAFParser(BaseBottomUpParser): def __init__(self, cfg): super().__init__(cfg) - self.thre1 = 0.1 self.thre2 = 0.05 # Heatmap indices to find each limb (joint connection). @@ -497,7 +496,7 @@ def __init__(self, cfg): def find_peaks(self, img): """Given a (grayscale) image, find local maxima whose value is above a - given threshold (param['thre1']) + given threshold (self.params.detection_threshold) :param img: Input image (2d array) where we want to find peaks :return: 2d np.array containing the [x,y] coordinates of each @@ -507,45 +506,36 @@ def find_peaks(self, img): peaks_binary = (maximum_filter( img, footprint=generate_binary_structure(2, 1)) == img) * ( - img > self.thre1) + img > self.params.detection_threshold) # Note reverse ([::-1]): we return [[x y], [x y]...] instead of - # [[y x], [y - # x]...] + # [[y x], [y x]...] return np.array(np.nonzero(peaks_binary)[::-1]).T def compute_resized_coords(self, coords, resizeFactor): - """ - Given the index/coordinates of a cell in some input array (e.g. image - ), - provides the new coordinates if that array was resized by making it - resizeFactor times bigger. + """ Given the index/coordinates of a cell in some input array + (e.g. image), provides the new coordinates if that array was resized + by making it resizeFactor times bigger. E.g.: image of size 3x3 is resized to 6x6 (resizeFactor=2), we'd like - to - know the new coordinates of cell [1,2] -> Function would return [2.5, - 4.5] + to know the new coordinates of cell [1,2] -> Function would return + [2.5,4.5]. :param coords: Coordinates (indices) of a cell in some input array :param resizeFactor: Resize coefficient = shape_dest/shape_source. - E.g.: - resizeFactor=2 means the destination array is twice as big as the - original one + E.g.: resizeFactor=2 means the destination array is twice as big as + the original one + :return: Coordinates in an array of size shape_dest=resizeFactor*shape_source, expressing the array indices - of the - closest point to 'coords' if an image of size shape_source was - resized to - shape_dest + of the closest point to 'coords' if an image of size shape_source + was resized to shape_dest """ # 1) Add 0.5 to coords to get coordinates of center of the pixel - # (e.g. - # index [0,0] represents the pixel at location [0.5,0.5]) + # (e.g. index [0, 0] represents the pixel at location [0.5, 0.5]) # 2) Transform those coordinates to shape_dest, by multiplying by # resizeFactor # 3) That number represents the location of the pixel center in the - # new array, - # so subtract 0.5 to get coordinates of the array index/indices - # (revert - # step 1) + # new array, so subtract 0.5 to get coordinates of the array + # index/indices (revert step 1) return (np.array(coords, dtype=float) + 0.5) * resizeFactor - 0.5 def NMS(self, @@ -553,47 +543,42 @@ def NMS(self, upsampFactor=1., bool_refine_center=True, bool_gaussian_filt=False): - """ - NonMaximaSuppression: find peaks (local maxima) in a set of grayscale - images + """NonMaximaSuppression: find peaks (local maxima) in a set of grayscale + images. + :param heatmaps: set of grayscale images on which to find local maxima (3d np.array, - with dimensions image_height x image_width x num_heatmaps) + with dimensions image_height x image_width x num_heatmaps) :param upsampFactor: Size ratio between CPM heatmap output and the - input image size. - Eg: upsampFactor=16 if original image was 480x640 and heatmaps are - 30x40xN + input image size. Eg: upsampFactor=16 if original image was 480x640 + and heatmaps are 30x40xN :param bool_refine_center: Flag indicating whether: - False: Simply return the low-res peak found upscaled by upsampFactor (subject to grid-snap) - - True: (Recommended, very accurate) Upsample a small - patch around each - low-res peak and - fine-tune the location of the peak at the resolution of the original - input image + - True: (Recommended, very accurate) Upsample a small patch around + each low-res peak and fine-tune the location of the peak at the + resolution of the original input image :param bool_gaussian_filt: Flag indicating whether to apply a - 1d-GaussianFilter (smoothing) - to each upsampled patch before fine-tuning the location of each peak. + 1d-GaussianFilter (smoothing) to each upsampled patch before + fine-tuning the location of each peak. + :return: a NUM_JOINTS x 4 np.array where each row represents a joint - type (0=nose, 1=neck...) - and the columns indicate the {x,y} position, the score (probability) - and a unique id (counter) + type (0=nose, 1=neck...) and the columns indicate the {x,y} position, + the score (probability) and a unique id (counter) """ + # MODIFIED BY CARLOS: Instead of upsampling the heatmaps to - # heatmap_avg and - # then performing NMS to find peaks, this step can be sped up - # by ~25-50x by: + # heatmap_avg and then performing NMS to find peaks, + # this step can be sped up by ~25-50x by: # (9-10ms [with GaussFilt] or 5-6ms [without GaussFilt] vs # 250-280ms on RoG # 1. Perform NMS at (low-res) CPM's output resolution # 1.1. Find peaks using scipy.ndimage.filters.maximum_filter # 2. Once a peak is found, take a patch of 5x5 centered around - # the peak, upsample it, and - # fine-tune the position of the actual maximum. - # '-> That's equivalent to having found the peak on heatmap_avg, - # but much faster because we only - # upsample and scan the 5x5 patch instead of the full (e.g.) - # 480x640 + # the peak, upsample it, and fine-tune the position of the actual + # maximum. '-> That's equivalent to having found the peak on + # heatmap_avg, but much faster because we only upsample and + # scan the 5x5 patch instead of the full (e.g.) 480x640 joint_list_per_joint_type = [] cnt_total_joints = 0 @@ -627,10 +612,8 @@ def NMS(self, interpolation=cv2.INTER_CUBIC) # Gaussian filtering takes an average of 0.8ms/peak - # (and there might be - # more than one peak per joint!) -> For now, skip it - # (it's - # accurate enough) + # (and there might be more than one peak per joint!) + # -> For now, skip it (it's accurate enough) map_upsamp = self.gaussian_filter( map_upsamp, sigma=3) if bool_gaussian_filt else map_upsamp @@ -640,13 +623,11 @@ def NMS(self, location_of_max = np.unravel_index(map_upsamp.argmax(), map_upsamp.shape) # Remember that peaks indicates [x,y] -> need to - # reverse it for - # [y,x] + # reverse it for [y,x] location_of_patch_center = self.compute_resized_coords( peak[::-1] - [y_min, x_min], upsampFactor) # Calculate the offset wrt to the patch center where - # the actual - # maximum is + # the actual maximum is refined_center = ( location_of_max - location_of_patch_center) peak_score = map_upsamp[location_of_max] @@ -727,16 +708,13 @@ def find_connected_joints(self, 3, :] = self.paf_xy_coords_per_limb[limb_type][1] for i, joint_src in enumerate(joints_src): # Try every possible joints_src[i]-joints_dst[j] - # pair and see - # if it's a feasible limb + # pair and see if it's a feasible limb for j, joint_dst in enumerate(joints_dst): # Subtract the position of both joints to obtain - # the - # direction of the potential limb + # the direction of the potential limb limb_dir = joint_dst[:2] - joint_src[:2] # Compute the distance/length of the potential - # limb (norm - # of limb_dir) + # limb (norm of limb_dir) limb_dist = np.sqrt(np.sum(limb_dir**2)) + 1e-8 limb_dir = limb_dir / limb_dist # Normalize limb_dir to be a unit vector @@ -765,8 +743,7 @@ def find_connected_joints(self, score_penalizing_long_dist = score_intermed_pts.mean( ) + min(0.5 * paf_upsamp.shape[0] / limb_dist - 1, 0) # Criterion 1: At least 80% of the intermediate - # points have - # a score higher than thre2 + # points have a score higher than thre2 criterion1 = ( np.count_nonzero(score_intermed_pts > self.thre2) > 0.8 * num_intermed_pts) @@ -800,8 +777,8 @@ def find_connected_joints(self, for potential_connection in connection_candidates: i, j, s = potential_connection[0:3] # Make sure joints_src[i] or joints_dst[j] haven't - # already been - # connected to other joints_dst or joints_src + # already been connected to other joints_dst or joints_ + # src if i not in connections[:, 3] and j not in connections[:, 4]: # [joint_src_id, joint_dst_id, @@ -813,8 +790,7 @@ def find_connected_joints(self, ]) # Exit if we've already established max_connections # connections (each joint can't be connected to more - # than - # one joint) + # than one joint) if len(connections) >= max_connections: break connected_limbs.append(connections) @@ -881,12 +857,10 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): # Update which joints are connected person1_limbs[:-2] += (person2_limbs[:-2] + 1) # Update the overall score and total count of - # joints - # connected by summing their counters + # joints connected by summing their counters person1_limbs[-2:] += person2_limbs[-2:] # Add the score of the current joint connection - # to the - # overall score + # to the overall score person1_limbs[-2] += limb_info[2] person_to_joint_assoc.pop(person_assoc_idx[1]) else: # Same case as len(person_assoc_idx)==1 above @@ -894,9 +868,9 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): person1_limbs[-1] += 1 person1_limbs[-2] += joint_list[ limb_info[1].astype(int), 2] + limb_info[2] - else: # No person has claimed any of these joints, create - # a new person - # Initialize person info to all -1 + else: + # No person has claimed any of these joints, create + # a new person Initialize person info to all -1 # (no joint associations) row = -1 * np.ones(20) # Store the joint info of the new connection @@ -954,11 +928,10 @@ def match(self, heatmaps, pafs): # Bottom-up approach: # Step 1: find all joints in the image (organized by joint type: # [0]=nose, [1]=neck...) - # 4 = img_orig.shape[0] / float(heatmaps.shape[0]) - heatmaps = np.transpose(heatmaps[0], [1, 2, 0]) pafs = np.transpose(pafs[0], [1, 2, 0]) + # 4 = img_orig.shape[0] / float(heatmaps.shape[0]) joint_list_per_joint_type = self.NMS(heatmaps, 4) # joint_list is an unravel'd version of joint_list_per_joint, # where we @@ -970,8 +943,7 @@ def match(self, heatmaps, pafs): ]) # Step 2: find which joints go together to form limbs - # (which wrists go - # with which elbows) + # (which wrists go with which elbows) paf_upsamp = cv2.resize( pafs, (heatmaps.shape[1] * 4, heatmaps.shape[0] * 4), interpolation=cv2.INTER_CUBIC) From 2a4ad0718cb1d9450b8d7775d4b05240971bad05 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Thu, 17 Jun 2021 16:29:34 +0800 Subject: [PATCH 19/98] fix docstring --- mmpose/core/post_processing/group.py | 103 ++++++++++++--------------- 1 file changed, 44 insertions(+), 59 deletions(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 27eccdb9a2..68dc4f715a 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -500,8 +500,7 @@ def find_peaks(self, img): :param img: Input image (2d array) where we want to find peaks :return: 2d np.array containing the [x,y] coordinates of each - peak found - in the image + peak found in the image """ peaks_binary = (maximum_filter( @@ -657,24 +656,20 @@ def find_connected_joints(self, resolution :param joint_list_per_joint_type: See 'return' doc of NMS() :param num_intermed_pts: Int indicating how many intermediate - points to take - between joint_src and joint_dst, at which the PAFs will be - evaluated + points to take between joint_src and joint_dst, at which the + PAFs will be evaluated :return: List of NUM_LIMBS rows. For every limb_type (a row) - we store - a list of all limbs of that type found (eg: all the right - forearms). - For each limb (each item in connected_limbs[limb_type]), we - store 5 cells: - # {joint_src_id,joint_dst_id}: a unique number associated with - each joint, - # limb_score_penalizing_long_dist: a score of how good a - connection - of the joints is, penalized if the limb length is too long - # {joint_src_index,joint_dst_index}: the index of the joint - within - all the joints of that type found (eg: the 3rd right elbow - found) + we store a list of all limbs of that type found (eg: all the + right forearms). For each limb (each item in + connected_limbs[limb_type]), we store 5 cells: + # {joint_src_id,joint_dst_id}: a unique number associated with + each joint, + # limb_score_penalizing_long_dist: a score of how good a + connection of the joints is, penalized if the limb length is + too long + # {joint_src_index,joint_dst_index}: the index of the joint + within all the joints of that type found (eg: the 3rd right + elbow found) """ connected_limbs = [] @@ -682,25 +677,22 @@ def find_connected_joints(self, limb_intermed_coords = np.empty((4, num_intermed_pts), dtype=np.intp) for limb_type in range(self.NUM_LIMBS): # List of all joints of type A found, where A is specified - # by limb_type - # (eg: a right forearm starts in a right elbow) + # by limb_type (eg: a right forearm starts in a right elbow) joints_src = joint_list_per_joint_type[ self.joint_to_limb_heatmap_relationship[limb_type][0]] # List of all joints of type B found, where B is specified - # by limb_type - # (eg: a right forearm ends in a right wrist) + # by limb_type (eg: a right forearm ends in a right wrist) joints_dst = joint_list_per_joint_type[ self.joint_to_limb_heatmap_relationship[limb_type][1]] if len(joints_src) == 0 or len(joints_dst) == 0: # No limbs of this type found (eg: no right forearms - # found because - # we didn't find any right wrists or right elbows) + # found because we didn't find any right wrists or + # right elbows) connected_limbs.append([]) else: connection_candidates = [] # Specify the paf index that contains the x-coord of - # the paf for - # this limb + # the paf for this limb limb_intermed_coords[ 2, :] = self.paf_xy_coords_per_limb[limb_type][0] # And the y-coord paf index @@ -720,20 +712,19 @@ def find_connected_joints(self, # Normalize limb_dir to be a unit vector # Linearly distribute num_intermed_pts points - # from the x - # coordinate of joint_src to the x coordinate - # of joint_dst + # from the x coordinate of joint_src to the + # x coordinate of joint_dst limb_intermed_coords[1, :] = np.round( np.linspace( joint_src[0], joint_dst[0], num=num_intermed_pts)) + # Same for the y coordinate limb_intermed_coords[0, :] = np.round( np.linspace( joint_src[1], joint_dst[1], - num=num_intermed_pts) - ) # Same for the y coordinate + num=num_intermed_pts)) intermed_paf = paf_upsamp[limb_intermed_coords[0, :], limb_intermed_coords[1, :], limb_intermed_coords[ @@ -752,9 +743,8 @@ def find_connected_joints(self, # positive criterion2 = (score_penalizing_long_dist > 0) if criterion1 and criterion2: - # Last value is the combined paf(+limb_dist) - # + heatmap - # scores of both joints + # Last value is the combined paf (+limb_dist) + # + heatmap scores of both joints connection_candidates.append([ i, j, score_penalizing_long_dist, score_penalizing_long_dist + joint_src[2] + @@ -767,20 +757,18 @@ def find_connected_joints(self, connection_candidates, key=lambda x: x[2], reverse=True) connections = np.empty((0, 5)) # There can only be as many limbs as the smallest number of - # source - # or destination joints (eg: only 2 forearms if there's 5 - # wrists - # but 2 elbows) + # source or destination joints (eg: only 2 forearms if + # there's 5 wrists but 2 elbows) max_connections = min(len(joints_src), len(joints_dst)) # Traverse all potential joint connections (sorted by their # score) for potential_connection in connection_candidates: i, j, s = potential_connection[0:3] # Make sure joints_src[i] or joints_dst[j] haven't - # already been connected to other joints_dst or joints_ - # src - if i not in connections[:, 3] and j not in connections[:, - 4]: + # already been connected to other joints_dst or + # joints_ src + if i not in connections[:, 3] and \ + j not in connections[:, 4]: # [joint_src_id, joint_dst_id, # limb_score_penalizing_long_dist, joint_src_index, # joint_dst_index] @@ -801,17 +789,17 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): """Associate limbs belonging to the same person together. :param connected_limbs: See 'return' doc of - find_connected_joints() + find_connected_joints() :param joint_list: unravel'd version of joint_list_per_joint [See 'return' doc of NMS()] :return: 2d np.array of size num_people x (NUM_JOINTS+2). For each person found: - # First NUM_JOINTS columns contain the index (in joint_list) - of the joints associated - with that person (or -1 if their i-th joint wasn't found) - # 2nd-to-last column: Overall score of the joints+limbs that - belong to this person - # Last column: Total count of joints found for this person + # First NUM_JOINTS columns contain the index (in joint_list) + of the joints associated with that person (or -1 if their + i-th joint wasn't found) + # 2nd-to-last column: Overall score of the joints+limbs that + belong to this person + # Last column: Total count of joints found for this person """ person_to_joint_assoc = [] @@ -827,10 +815,8 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): person_assoc_idx.append(person) # If one of the joints has been associated to a person, - # and either - # the other joint is also associated with the same - # person or not - # associated to anyone yet: + # and either the other joint is also associated with the same + # person or not associated to anyone yet: if len(person_assoc_idx) == 1: person_limbs = person_to_joint_assoc[person_assoc_idx[0]] # If the other joint is not associated to anyone yet, @@ -841,8 +827,8 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): # this person person_limbs[-1] += 1 # And update the total score (+= heatmap score - # of joint_dst - # + score of connecting joint_src with joint_dst) + # of joint_dst + score of connecting joint_src with + # joint_dst) person_limbs[-2] += joint_list[ limb_info[1].astype(int), 2] + limb_info[2] elif len(person_assoc_idx @@ -925,7 +911,6 @@ def output_format(self, joint_list, person_to_joint_assoc): return ans def match(self, heatmaps, pafs): - # Bottom-up approach: # Step 1: find all joints in the image (organized by joint type: # [0]=nose, [1]=neck...) heatmaps = np.transpose(heatmaps[0], [1, 2, 0]) @@ -934,8 +919,8 @@ def match(self, heatmaps, pafs): # 4 = img_orig.shape[0] / float(heatmaps.shape[0]) joint_list_per_joint_type = self.NMS(heatmaps, 4) # joint_list is an unravel'd version of joint_list_per_joint, - # where we - # add a 5th column to indicate the joint_type (0=nose, 1=neck...) + # where we add a 5th column to indicate the joint_type + # (0=nose, 1=neck...) joint_list = np.array([ tuple(peak) + (joint_type, ) for joint_type, joint_peaks in enumerate(joint_list_per_joint_type) From 1a7ef22dd1b6255b178cf817549ff64fec221301 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 18 Jun 2021 18:15:33 +0800 Subject: [PATCH 20/98] fix config --- .../part_affinity_field/coco/hrnet_w32_coco_512x512.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index 68cc1ee3b0..3b3da15569 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -150,10 +150,7 @@ ], pipeline_indices=[0, 1], keys=['targets', 'masks']), - dict( - type='Collect', - keys=['img', 'joints', 'targets', 'masks'], - meta_keys=[]), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), ] val_pipeline = [ From a31c5cf8e4ebca40850c447b1cdb1e22833fa93b Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 18 Jun 2021 18:21:03 +0800 Subject: [PATCH 21/98] add res50 config --- .../coco/res50_coco_512x512.py | 172 ++++++++++++++++++ 1 file changed, 172 insertions(+) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py new file mode 100644 index 0000000000..b645a4da3b --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -0,0 +1,172 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=512, + base_size=256, + base_sigma=2, + heatmap_size=[128], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='torchvision://resnet50', + backbone=dict(type='ResNet', depth=50), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=17, + num_deconv_layers=0, + extra=dict(final_conv_kernel=1, ), + loss_keypoint=dict(type='MaskedMSELoss', )), + ], + paf_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=38, + num_deconv_layers=0, + extra=dict(final_conv_kernel=1, ), + loss_keypoint=dict(type='MaskedMSELoss', )), + ], + heatmap_index=[0], + paf_index=[0], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0, 1], + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'flip_index_paf' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From f9044e5cde119d0b644fcd80dcb14a4faf03af0a Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 18 Jun 2021 18:30:50 +0800 Subject: [PATCH 22/98] add res50 config --- .../part_affinity_field/coco/res50_coco_512x512.py | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index b645a4da3b..9e5de30221 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -57,19 +57,15 @@ heatmap_heads_cfg=[ dict( type='DeconvHead', - in_channels=32, + in_channels=2048, out_channels=17, - num_deconv_layers=0, - extra=dict(final_conv_kernel=1, ), loss_keypoint=dict(type='MaskedMSELoss', )), ], paf_heads_cfg=[ dict( type='DeconvHead', - in_channels=32, + in_channels=2048, out_channels=38, - num_deconv_layers=0, - extra=dict(final_conv_kernel=1, ), loss_keypoint=dict(type='MaskedMSELoss', )), ], heatmap_index=[0], From e2b83edcc4edb938495fbe3ac73a3619b362d3a3 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sun, 20 Jun 2021 21:10:08 +0800 Subject: [PATCH 23/98] fix bugs in paf generator --- mmpose/core/post_processing/group.py | 24 +++++++++---------- .../datasets/pipelines/bottom_up_transform.py | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 68dc4f715a..cff5cc0454 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -200,12 +200,13 @@ def adjust(ans, heatmaps, use_udp=False): Note: batch size: N + number of person: M number of keypoints: K heatmap height: H heatmap width: W Args: - ans (list(np.ndarray)): Keypoint predictions. + ans (list(np.array([M,K,5]))): Keypoint predictions. heatmaps (torch.Tensor[NxKxHxW]): Heatmaps. """ @@ -471,7 +472,6 @@ def __init__(self, cfg): # Neck->LShoulder, so joint_to_limb_heatmap_relationship[1] # represents the # indices of heatmaps to look for joints: neck=1, LShoulder=5 - # TODO should be self.ann_info['skeleton'] self.joint_to_limb_heatmap_relationship = [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], [5, 11], @@ -858,7 +858,7 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): # No person has claimed any of these joints, create # a new person Initialize person info to all -1 # (no joint associations) - row = -1 * np.ones(20) + row = -1 * np.ones(self.params.num_joints + 2) # Store the joint info of the new connection row[joint_src_type] = limb_info[0] row[joint_dst_type] = limb_info[1] @@ -896,19 +896,18 @@ def output_format(self, joint_list, person_to_joint_assoc): ans = [] if len(person_to_joint_assoc) > 0: - num_kpt = person_to_joint_assoc.shape[1] - 2 - for person in person_to_joint_assoc: - ans_person = np.zeros((num_kpt, 5)) - for j in range(num_kpt): - joint_id = person[j] + ans_person = np.zeros((self.params.num_joints, 5)) + for j in range(self.params.num_joints): + joint_id = int(person[j]) if joint_id < 0: continue - assert j == joint_list[joint_id, 4] ans_person[j] = joint_list[joint_id] + ans_person[:, :2] /= 4 ans.append(ans_person) - - return ans + return [np.stack(ans)] + else: + return [] def match(self, heatmaps, pafs): # Step 1: find all joints in the image (organized by joint type: @@ -949,6 +948,7 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): Note: batch size: N + number of people: M number of keypoints: K number of paf maps: P heatmap height: H @@ -961,7 +961,7 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): Returns: tuple: A tuple containing keypoint grouping results. - - ans (list(np.ndarray)): Pose results. + - ans (list(np.array([M,K,5]))): Keypoint predictions. - scores (list): Score of people. """ diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index 495b7f1e9f..fc82116912 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -296,7 +296,7 @@ def _accumulate_paf_map_(self, pafs, src, dst, count): dist = np.abs(delta_x * unit_limb_vec[1] - delta_y * unit_limb_vec[0]) mask_local = (dist < self.limb_width) - mask[xx, yy] = mask_local + mask[yy, xx] = mask_local pafs[0, mask] += unit_limb_vec[0] pafs[1, mask] += unit_limb_vec[1] From cb5a59016d224b93cf5c37cf400c015164822abf Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 21 Jun 2021 13:37:00 +0800 Subject: [PATCH 24/98] update paf flip --- mmpose/core/evaluation/bottom_up_eval.py | 3 +++ mmpose/models/detectors/associative_embedding.py | 3 ++- mmpose/models/detectors/paf.py | 6 +++++- 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 4761fa2fcd..71dc6dfc23 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -188,6 +188,9 @@ def aggregate_stage_flip(feature_maps, Aggregated feature maps. """ + if feature_maps_flip is None: + aggregate_flip = 'none' + output_feature_maps = [] if aggregate_stage == 'average': diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index ed8a568985..bc05c3e60b 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -265,7 +265,8 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): tags_flipped, flip_index=None, flip_output=True) else: - outputs_flipped = None + heatmaps_flipped = None + tags_flipped = None # TODO: move `align_corners' to test_cfg aggregated_heatmaps = aggregate_stage_flip( diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 442b283a79..cd2ff6ed0e 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -253,9 +253,13 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): pafs_flipped, flip_index=img_metas['flip_index_paf'], flip_output=True) + for _pafs in pafs_flipped: + # flip the x-axis + _pafs[:, ::2, :, :] *= -1 else: - outputs_flipped = None + heatmaps_flipped = None + pafs_flipped = None # TODO: move `align_corners' to test_cfg aggregated_heatmaps = aggregate_stage_flip( From afb5c76e553b7020f3bafd5b28caf6acf06238c6 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 21 Jun 2021 14:49:53 +0800 Subject: [PATCH 25/98] update paf group --- mmpose/core/post_processing/group.py | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index cff5cc0454..05f871adf5 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -820,7 +820,8 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): if len(person_assoc_idx) == 1: person_limbs = person_to_joint_assoc[person_assoc_idx[0]] # If the other joint is not associated to anyone yet, - if person_limbs[joint_dst_type] != limb_info[1]: + if person_limbs[joint_src_type] == limb_info[0] and \ + person_limbs[joint_dst_type] != limb_info[1]: # Associate it with the current person person_limbs[joint_dst_type] = limb_info[1] # Increase the number of limbs associated to @@ -831,6 +832,21 @@ def group_limbs_of_same_person(self, connected_limbs, joint_list): # joint_dst) person_limbs[-2] += joint_list[ limb_info[1].astype(int), 2] + limb_info[2] + elif person_limbs[joint_src_type] != limb_info[0] and \ + person_limbs[joint_dst_type] == limb_info[1]: + # Associate it with the current person + person_limbs[joint_src_type] = limb_info[0] + # Increase the number of limbs associated to + # this person + person_limbs[-1] += 1 + # And update the total score (+= heatmap score + # of joint_dst + score of connecting joint_src with + # joint_dst) + person_limbs[-2] += joint_list[ + limb_info[0].astype(int), 2] + limb_info[2] + else: + NotImplementedError() + elif len(person_assoc_idx ) == 2: # if found 2 and disjoint, merge them person1_limbs = person_to_joint_assoc[person_assoc_idx[0]] From e9080e7f9f98964f3c39f556b9955e1287941468 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 21 Jun 2021 15:28:48 +0800 Subject: [PATCH 26/98] update deconvhead --- mmpose/models/detectors/paf.py | 17 ++ mmpose/models/heads/deconv_head.py | 153 ++++++++++++++++-- .../heads/topdown_heatmap_simple_head.py | 2 +- tests/test_model/test_bottom_up_head.py | 2 +- .../test_bottom_up_pipelines.py | 8 +- 5 files changed, 161 insertions(+), 21 deletions(-) diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index cd2ff6ed0e..9ca9d576d2 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -303,6 +303,23 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): aggregate_scale='average', align_corners=self.use_udp) + import cv2 + import numpy as np + + def torch2img(tens, idx=0): + return np.transpose(tens[idx].detach().cpu().numpy(), [1, 2, 0]) + + for i in range(17): + heatmap_np = torch2img(aggregated_heatmaps, 0) + cv2.imwrite( + f'pred_heatmap_{i}.jpg', + np.repeat(np.abs(heatmap_np[:, :, i:i + 1]) * 255, 3, axis=2)) + for i in range(38): + paf_np = torch2img(aggregated_pafs, 0) + cv2.imwrite( + f'pred_paf_{i}.jpg', + np.repeat(np.abs(paf_np[:, :, i:i + 1]) * 255, 3, axis=2)) + # perform grouping grouped, scores = self.parser.parse(aggregated_heatmaps, aggregated_pafs, diff --git a/mmpose/models/heads/deconv_head.py b/mmpose/models/heads/deconv_head.py index 8550f505c2..d2e27e2e22 100644 --- a/mmpose/models/heads/deconv_head.py +++ b/mmpose/models/heads/deconv_head.py @@ -1,8 +1,10 @@ +import torch import torch.nn as nn -from mmcv.cnn import (build_conv_layer, build_upsample_layer, constant_init, - normal_init) +from mmcv.cnn import (build_conv_layer, build_norm_layer, build_upsample_layer, + constant_init, normal_init) from mmpose.models.builder import HEADS, build_loss +from mmpose.models.utils.ops import resize @HEADS.register_module() @@ -18,6 +20,18 @@ class DeconvHead(nn.Module): num_deconv_filters (list|tuple): Number of filters. If num_deconv_layers > 0, the length of num_deconv_kernels (list|tuple): Kernel sizes. + in_index (int|Sequence[int]): Input feature index. Default: 0 + input_transform (str|None): Transformation type of input features. + Options: 'resize_concat', 'multiple_select', None. + 'resize_concat': Multiple feature maps will be resized to the + same size as the first one and then concat together. + Usually used in FCN head of HRNet. + 'multiple_select': Multiple feature maps will be bundle into + a list and passed into decode head. + None: Only one select feature map is allowed. + Default: None. + align_corners (bool): align_corners argument of F.interpolate. + Default: False. loss_keypoint (dict): Config for loss. Default: None. """ @@ -28,12 +42,18 @@ def __init__(self, num_deconv_filters=(256, 256, 256), num_deconv_kernels=(4, 4, 4), extra=None, + in_index=0, + input_transform=None, + align_corners=False, loss_keypoint=None): super().__init__() + self.in_channels = in_channels self.loss = build_loss(loss_keypoint) - self.in_channels = in_channels + self._init_inputs(in_channels, in_index, input_transform) + self.in_index = in_index + self.align_corners = align_corners if extra is not None and not isinstance(extra, dict): raise TypeError('extra should be dict or None.') @@ -50,25 +70,127 @@ def __init__(self, raise ValueError( f'num_deconv_layers ({num_deconv_layers}) should >= 0.') + identity_final_layer = False if extra is not None and 'final_conv_kernel' in extra: - assert extra['final_conv_kernel'] in [1, 3] + assert extra['final_conv_kernel'] in [0, 1, 3] if extra['final_conv_kernel'] == 3: padding = 1 - else: + elif extra['final_conv_kernel'] == 1: padding = 0 + else: + # 0 for Identity mapping. + identity_final_layer = True kernel_size = extra['final_conv_kernel'] else: kernel_size = 1 padding = 0 - self.final_layer = build_conv_layer( - cfg=dict(type='Conv2d'), - in_channels=num_deconv_filters[-1] - if num_deconv_layers > 0 else in_channels, - out_channels=out_channels, - kernel_size=kernel_size, - stride=1, - padding=padding) + if identity_final_layer: + self.final_layer = nn.Identity() + else: + conv_channels = num_deconv_filters[ + -1] if num_deconv_layers > 0 else self.in_channels + + layers = [] + if extra is not None: + num_conv_layers = extra.get('num_conv_layers', 0) + num_conv_kernels = extra.get('num_conv_kernels', + [1] * num_conv_layers) + + for i in range(num_conv_layers): + layers.append( + build_conv_layer( + dict(type='Conv2d'), + in_channels=conv_channels, + out_channels=conv_channels, + kernel_size=num_conv_kernels[i], + stride=1, + padding=(num_conv_kernels[i] - 1) // 2)) + layers.append( + build_norm_layer(dict(type='BN'), conv_channels)[1]) + layers.append(nn.ReLU(inplace=True)) + + layers.append( + build_conv_layer( + cfg=dict(type='Conv2d'), + in_channels=conv_channels, + out_channels=out_channels, + kernel_size=kernel_size, + stride=1, + padding=padding)) + + if len(layers) > 1: + self.final_layer = nn.Sequential(*layers) + else: + self.final_layer = layers[0] + + def _init_inputs(self, in_channels, in_index, input_transform): + """Check and initialize input transforms. + + The in_channels, in_index and input_transform must match. + Specifically, when input_transform is None, only single feature map + will be selected. So in_channels and in_index must be of type int. + When input_transform is not None, in_channels and in_index must be + list or tuple, with the same length. + + Args: + in_channels (int|Sequence[int]): Input channels. + in_index (int|Sequence[int]): Input feature index. + input_transform (str|None): Transformation type of input features. + Options: 'resize_concat', 'multiple_select', None. + 'resize_concat': Multiple feature maps will be resize to the + same size as first one and than concat together. + Usually used in FCN head of HRNet. + 'multiple_select': Multiple feature maps will be bundle into + a list and passed into decode head. + None: Only one select feature map is allowed. + """ + + if input_transform is not None: + assert input_transform in ['resize_concat', 'multiple_select'] + self.input_transform = input_transform + self.in_index = in_index + if input_transform is not None: + assert isinstance(in_channels, (list, tuple)) + assert isinstance(in_index, (list, tuple)) + assert len(in_channels) == len(in_index) + if input_transform == 'resize_concat': + self.in_channels = sum(in_channels) + else: + self.in_channels = in_channels + else: + assert isinstance(in_channels, int) + assert isinstance(in_index, int) + self.in_channels = in_channels + + def _transform_inputs(self, inputs): + """Transform inputs for decoder. + + Args: + inputs (list[Tensor] | Tensor): multi-level img features. + + Returns: + Tensor: The transformed inputs + """ + if not isinstance(inputs, list): + return inputs + + if self.input_transform == 'resize_concat': + inputs = [inputs[i] for i in self.in_index] + upsampled_inputs = [ + resize( + input=x, + size=inputs[0].shape[2:], + mode='bilinear', + align_corners=self.align_corners) for x in inputs + ] + inputs = torch.cat(upsampled_inputs, dim=1) + elif self.input_transform == 'multiple_select': + inputs = [inputs[i] for i in self.in_index] + else: + inputs = inputs[self.in_index] + + return inputs def _make_deconv_layer(self, num_layers, num_filters, num_kernels): """Make deconv layers.""" @@ -149,8 +271,7 @@ def get_loss(self, outputs, targets, masks): def forward(self, x): """Forward function.""" - if isinstance(x, list): - x = x[0] + x = self._transform_inputs(x) final_outputs = [] x = self.deconv_layers(x) y = self.final_layer(x) @@ -167,3 +288,5 @@ def init_weights(self): for m in self.final_layer.modules(): if isinstance(m, nn.Conv2d): normal_init(m, std=0.001, bias=0) + elif isinstance(m, nn.BatchNorm2d): + constant_init(m, 1) diff --git a/mmpose/models/heads/topdown_heatmap_simple_head.py b/mmpose/models/heads/topdown_heatmap_simple_head.py index 7a3499e167..7cf02e1d97 100644 --- a/mmpose/models/heads/topdown_heatmap_simple_head.py +++ b/mmpose/models/heads/topdown_heatmap_simple_head.py @@ -28,7 +28,7 @@ class TopdownHeatmapSimpleHead(TopdownHeatmapBaseHead): num_deconv_filters (list|tuple): Number of filters. If num_deconv_layers > 0, the length of num_deconv_kernels (list|tuple): Kernel sizes. - in_index (int|Sequence[int]): Input feature index. Default: -1 + in_index (int|Sequence[int]): Input feature index. Default: 0 input_transform (str|None): Transformation type of input features. Options: 'resize_concat', 'multiple_select', None. 'resize_concat': Multiple feature maps will be resized to the diff --git a/tests/test_model/test_bottom_up_head.py b/tests/test_model/test_bottom_up_head.py index 41b2f4ef1e..df9b0093ba 100644 --- a/tests/test_model/test_bottom_up_head.py +++ b/tests/test_model/test_bottom_up_head.py @@ -31,7 +31,7 @@ def test_ae_simple_head(): in_channels=512, num_joints=17, with_ae_loss=[True], - extra={'final_conv_kernel': 0}, + extra={'final_conv_kernel': -1}, loss_keypoint=dict( type='MultiLossFactory', num_joints=17, diff --git a/tests/test_pipelines/test_bottom_up_pipelines.py b/tests/test_pipelines/test_bottom_up_pipelines.py index ec855a4b79..b1b14eea36 100644 --- a/tests/test_pipelines/test_bottom_up_pipelines.py +++ b/tests/test_pipelines/test_bottom_up_pipelines.py @@ -276,15 +276,15 @@ def test_BottomUpGenerateHeatmapTarget(): generate_heatmap_target = BottomUpGenerateHeatmapTarget(2) results_generate_heatmap_target = generate_heatmap_target(results) - assert 'target' in results_generate_heatmap_target - assert len(results_generate_heatmap_target['target'] + assert 'targets' in results_generate_heatmap_target + assert len(results_generate_heatmap_target['targets'] ) == results['ann_info']['num_scales'] def test_BottomUpGeneratePAFTarget(): ann_info = {} - ann_info['skeleton'] = [[1, 2], [3, 4]] + ann_info['skeleton'] = [[0, 1], [2, 3]] ann_info['heatmap_size'] = np.array([5]) ann_info['num_joints'] = 4 ann_info['num_scales'] = 1 @@ -305,7 +305,7 @@ def test_BottomUpGeneratePAFTarget(): generate_paf_target = BottomUpGeneratePAFTarget(1) results_generate_paf_target = generate_paf_target(results) sqrt = np.sqrt(2) / 2 - assert (results_generate_paf_target['target'] == np.array( + assert (results_generate_paf_target['targets'] == np.array( [[[sqrt, sqrt, 0, sqrt, sqrt], [sqrt, sqrt, sqrt, sqrt, sqrt], [0, sqrt, sqrt, sqrt, 0], [sqrt, sqrt, sqrt, sqrt, sqrt], [sqrt, sqrt, 0, sqrt, sqrt]], From 801afe67e367f6335926cc5b66f4bceb5ffdef4b Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 21 Jun 2021 15:32:16 +0800 Subject: [PATCH 27/98] paf + head --- .../part_affinity_field/coco/hrnet_w32_coco_512x512.py | 10 ++++++++-- .../part_affinity_field/coco/res50_coco_512x512.py | 10 ++++++++++ 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index 3b3da15569..33a3166595 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -89,7 +89,10 @@ in_channels=32, out_channels=17, num_deconv_layers=0, - extra=dict(final_conv_kernel=1, ), + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), loss_keypoint=dict(type='MaskedMSELoss', )), ], paf_heads_cfg=[ @@ -98,7 +101,10 @@ in_channels=32, out_channels=38, num_deconv_layers=0, - extra=dict(final_conv_kernel=1, ), + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), loss_keypoint=dict(type='MaskedMSELoss', )), ], heatmap_index=[0], diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index 9e5de30221..4d7e5e2a08 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -59,6 +59,11 @@ type='DeconvHead', in_channels=2048, out_channels=17, + num_deconv_layers=0, + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), loss_keypoint=dict(type='MaskedMSELoss', )), ], paf_heads_cfg=[ @@ -66,6 +71,11 @@ type='DeconvHead', in_channels=2048, out_channels=38, + num_deconv_layers=0, + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), loss_keypoint=dict(type='MaskedMSELoss', )), ], heatmap_index=[0], From 09dc28b0f1b85c33f7f76ac14afef79e1dcd88fb Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 21 Jun 2021 16:10:32 +0800 Subject: [PATCH 28/98] fix config --- .../part_affinity_field/coco/res50_coco_512x512.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index 4d7e5e2a08..29ecc417bc 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -59,7 +59,6 @@ type='DeconvHead', in_channels=2048, out_channels=17, - num_deconv_layers=0, extra=dict( final_conv_kernel=1, num_conv_layers=1, @@ -71,7 +70,6 @@ type='DeconvHead', in_channels=2048, out_channels=38, - num_deconv_layers=0, extra=dict( final_conv_kernel=1, num_conv_layers=1, From 8f12bd4f57f56a9eab1d0caee10e8600a90ab36a Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 23 Jun 2021 20:11:37 +0800 Subject: [PATCH 29/98] update post-processing --- mmpose/apis/inference.py | 5 + mmpose/core/post_processing/group.py | 797 +++++++++++---------------- mmpose/models/detectors/paf.py | 17 - 3 files changed, 313 insertions(+), 506 deletions(-) diff --git a/mmpose/apis/inference.py b/mmpose/apis/inference.py index bcb6c73a61..cb1918c9a9 100644 --- a/mmpose/apis/inference.py +++ b/mmpose/apis/inference.py @@ -470,6 +470,11 @@ def inference_bottom_up_pose_model(model, cfg.data_cfg['num_joints'], 'flip_index': [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15], + 'flip_index_paf': [ + 4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 12, 13, 10, 11, 14, 15, 18, 19, + 16, 17, 22, 23, 20, 21, 24, 25, 28, 29, 26, 27, 32, 33, 30, 31, + 36, 37, 34, 35 + ] } } diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 05f871adf5..092fee6201 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -1,16 +1,8 @@ -# ------------------------------------------------------------------------------ -# Adapted from https://github.com/princeton-vl/pose-ae-train/ -# Original licence: Copyright (c) 2017, umich-vl, under BSD 3-Clause License. -# ------------------------------------------------------------------------------ - from abc import ABCMeta, abstractmethod -import cv2 import numpy as np import torch from munkres import Munkres -from scipy.ndimage.filters import maximum_filter -from scipy.ndimage.morphology import generate_binary_structure from mmpose.core.evaluation import post_dark_udp @@ -245,7 +237,14 @@ def parse(self, *args, **kwargs): class HeatmapParser(BaseBottomUpParser): - """The heatmap parser for post processing.""" + """The associative embedding parser. + + Paper ref: Alejandro Newell et al. "Associative Embedding: + End-to-end Learning for Joint Detection and Grouping." (NeurIPS'2017) + + Adapted from https://github.com/princeton-vl/pose-ae-train/ + Original licence: Copyright (c) 2017, umich-vl, under BSD 3-Clause License. + """ def __init__(self, cfg): super().__init__(cfg) @@ -452,518 +451,334 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): class PAFParser(BaseBottomUpParser): - """The paf parser for post processing. + """The part-affinity field parser. Paper ref: Cao, Zhe, et al. "OpenPose: realtime multi-person 2D pose estimation using Part Affinity Fields." (TPAMI'2019) - TODO: Rewrite this class. Currently, this part is copied from - 'https://github.com/tensorboy/' - 'pytorch_Realtime_Multi-Person_Pose_Estimation' + Adapted from 'https://github.com/Daniil-Osokin/ + lightweight-human-pose-estimation.pytorch' + + Original licence: Copyright 2018, under Apache License 2.0. """ def __init__(self, cfg): super().__init__(cfg) - self.thre2 = 0.05 - + self.paf_thr = 0.05 # Heatmap indices to find each limb (joint connection). - # Eg: limb_type=1 is - # Neck->LShoulder, so joint_to_limb_heatmap_relationship[1] - # represents the - # indices of heatmaps to look for joints: neck=1, LShoulder=5 - self.joint_to_limb_heatmap_relationship = [[15, 13], [13, - 11], [16, 14], - [14, 12], [11, 12], [5, 11], - [6, 12], [5, 6], [5, 7], - [6, 8], [7, 9], [8, 10], - [1, 2], [0, 1], [0, 2], - [1, 3], [2, 4], [3, 5], - [4, 6]] + self.limb2joint = [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], + [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], + [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], + [3, 5], [4, 6]] # PAF indices containing the x and y coordinates of the PAF for a # given limb. - # Eg: limb_type=1 is Neck->LShoulder, so - # PAFneckLShoulder_x=paf_xy_coords_per_limb[1][0] and - # PAFneckLShoulder_y=paf_xy_coords_per_limb[1][1] - self.paf_xy_coords_per_limb = [[0, 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], [28, 29], [30, 31], [32, 33], - [34, 35], [36, 37]] - - self.NUM_LIMBS = len(self.joint_to_limb_heatmap_relationship) - - def find_peaks(self, img): - """Given a (grayscale) image, find local maxima whose value is above a - given threshold (self.params.detection_threshold) - - :param img: Input image (2d array) where we want to find peaks - :return: 2d np.array containing the [x,y] coordinates of each - peak found in the image - """ + self.limb2paf = [[0, 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], [28, 29], [30, 31], + [32, 33], [34, 35], [36, 37]] - peaks_binary = (maximum_filter( - img, footprint=generate_binary_structure(2, 1)) == img) * ( - img > self.params.detection_threshold) - # Note reverse ([::-1]): we return [[x y], [x y]...] instead of - # [[y x], [y x]...] - return np.array(np.nonzero(peaks_binary)[::-1]).T - - def compute_resized_coords(self, coords, resizeFactor): - """ Given the index/coordinates of a cell in some input array - (e.g. image), provides the new coordinates if that array was resized - by making it resizeFactor times bigger. - E.g.: image of size 3x3 is resized to 6x6 (resizeFactor=2), we'd like - to know the new coordinates of cell [1,2] -> Function would return - [2.5,4.5]. - :param coords: Coordinates (indices) of a cell in some input array - :param resizeFactor: Resize coefficient = shape_dest/shape_source. - E.g.: resizeFactor=2 means the destination array is twice as big as - the original one - - :return: Coordinates in an array of size - shape_dest=resizeFactor*shape_source, expressing the array indices - of the closest point to 'coords' if an image of size shape_source - was resized to shape_dest - """ + self.NUM_LIMBS = len(self.limb2joint) - # 1) Add 0.5 to coords to get coordinates of center of the pixel - # (e.g. index [0, 0] represents the pixel at location [0.5, 0.5]) - # 2) Transform those coordinates to shape_dest, by multiplying by - # resizeFactor - # 3) That number represents the location of the pixel center in the - # new array, so subtract 0.5 to get coordinates of the array - # index/indices (revert step 1) - return (np.array(coords, dtype=float) + 0.5) * resizeFactor - 0.5 - - def NMS(self, - heatmaps, - upsampFactor=1., - bool_refine_center=True, - bool_gaussian_filt=False): - """NonMaximaSuppression: find peaks (local maxima) in a set of grayscale - images. - - :param heatmaps: set of grayscale images on which to find local maxima - (3d np.array, - with dimensions image_height x image_width x num_heatmaps) - :param upsampFactor: Size ratio between CPM heatmap output and the - input image size. Eg: upsampFactor=16 if original image was 480x640 - and heatmaps are 30x40xN - :param bool_refine_center: Flag indicating whether: - - False: Simply return the low-res peak found upscaled by upsampFactor - (subject to grid-snap) - - True: (Recommended, very accurate) Upsample a small patch around - each low-res peak and fine-tune the location of the peak at the - resolution of the original input image - :param bool_gaussian_filt: Flag indicating whether to apply a - 1d-GaussianFilter (smoothing) to each upsampled patch before - fine-tuning the location of each peak. - - :return: a NUM_JOINTS x 4 np.array where each row represents a joint - type (0=nose, 1=neck...) and the columns indicate the {x,y} position, - the score (probability) and a unique id (counter) - """ + def output_format(self, all_keypoints, pose_entries): + """Format transform. - # MODIFIED BY CARLOS: Instead of upsampling the heatmaps to - # heatmap_avg and then performing NMS to find peaks, - # this step can be sped up by ~25-50x by: - # (9-10ms [with GaussFilt] or 5-6ms [without GaussFilt] vs - # 250-280ms on RoG - # 1. Perform NMS at (low-res) CPM's output resolution - # 1.1. Find peaks using scipy.ndimage.filters.maximum_filter - # 2. Once a peak is found, take a patch of 5x5 centered around - # the peak, upsample it, and fine-tune the position of the actual - # maximum. '-> That's equivalent to having found the peak on - # heatmap_avg, but much faster because we only upsample and - # scan the 5x5 patch instead of the full (e.g.) 480x640 - - joint_list_per_joint_type = [] - cnt_total_joints = 0 - - # For every peak found, win_size specifies how many pixels in each - # direction from the peak we take to obtain the patch that will be - # upsampled. Eg: win_size=1 -> patch is 3x3; win_size=2 -> 5x5 - # (for BICUBIC interpolation to be accurate, win_size needs to - # be >=2!) - win_size = 2 - - for joint in range(heatmaps.shape[2]): - map_orig = heatmaps[:, :, joint] - peak_coords = self.find_peaks(map_orig) - peaks = np.zeros((len(peak_coords), 4)) - for i, peak in enumerate(peak_coords): - if bool_refine_center: - x_min, y_min = np.maximum(0, peak - win_size) - x_max, y_max = np.minimum( - np.array(map_orig.T.shape) - 1, peak + win_size) - - # Take a small patch around each peak and only upsample - # that - # tiny region - patch = map_orig[y_min:y_max + 1, x_min:x_max + 1] - map_upsamp = cv2.resize( - patch, - None, - fx=upsampFactor, - fy=upsampFactor, - interpolation=cv2.INTER_CUBIC) - - # Gaussian filtering takes an average of 0.8ms/peak - # (and there might be more than one peak per joint!) - # -> For now, skip it (it's accurate enough) - map_upsamp = self.gaussian_filter( - map_upsamp, - sigma=3) if bool_gaussian_filt else map_upsamp - - # Obtain the coordinates of the maximum value in the - # patch - location_of_max = np.unravel_index(map_upsamp.argmax(), - map_upsamp.shape) - # Remember that peaks indicates [x,y] -> need to - # reverse it for [y,x] - location_of_patch_center = self.compute_resized_coords( - peak[::-1] - [y_min, x_min], upsampFactor) - # Calculate the offset wrt to the patch center where - # the actual maximum is - refined_center = ( - location_of_max - location_of_patch_center) - peak_score = map_upsamp[location_of_max] - else: - refined_center = [0, 0] - # Flip peak coordinates since they are [x,y] instead - # of [y,x] - peak_score = map_orig[tuple(peak[::-1])] - peaks[i, :] = tuple([ - int(round(x)) for x in self.compute_resized_coords( - peak_coords[i], upsampFactor) + refined_center[::-1] - ]) + (peak_score, cnt_total_joints) - cnt_total_joints += 1 - joint_list_per_joint_type.append(peaks) - - return joint_list_per_joint_type - - def find_connected_joints(self, - paf_upsamp, - joint_list_per_joint_type, - num_intermed_pts=10): - """For every type of limb (eg: forearm, shin, etc.), look for every - potential pair of joints (eg: every wrist-elbow combination) and - evaluate the PAFs to determine which pairs are indeed body limbs. - - :param paf_upsamp: PAFs upsampled to the original input image - resolution - :param joint_list_per_joint_type: See 'return' doc of NMS() - :param num_intermed_pts: Int indicating how many intermediate - points to take between joint_src and joint_dst, at which the - PAFs will be evaluated - :return: List of NUM_LIMBS rows. For every limb_type (a row) - we store a list of all limbs of that type found (eg: all the - right forearms). For each limb (each item in - connected_limbs[limb_type]), we store 5 cells: - # {joint_src_id,joint_dst_id}: a unique number associated with - each joint, - # limb_score_penalizing_long_dist: a score of how good a - connection of the joints is, penalized if the limb length is - too long - # {joint_src_index,joint_dst_index}: the index of the joint - within all the joints of that type found (eg: the 3rd right - elbow found) - """ - connected_limbs = [] - - # Auxiliary array to access paf_upsamp quickly - limb_intermed_coords = np.empty((4, num_intermed_pts), dtype=np.intp) - for limb_type in range(self.NUM_LIMBS): - # List of all joints of type A found, where A is specified - # by limb_type (eg: a right forearm starts in a right elbow) - joints_src = joint_list_per_joint_type[ - self.joint_to_limb_heatmap_relationship[limb_type][0]] - # List of all joints of type B found, where B is specified - # by limb_type (eg: a right forearm ends in a right wrist) - joints_dst = joint_list_per_joint_type[ - self.joint_to_limb_heatmap_relationship[limb_type][1]] - if len(joints_src) == 0 or len(joints_dst) == 0: - # No limbs of this type found (eg: no right forearms - # found because we didn't find any right wrists or - # right elbows) - connected_limbs.append([]) - else: - connection_candidates = [] - # Specify the paf index that contains the x-coord of - # the paf for this limb - limb_intermed_coords[ - 2, :] = self.paf_xy_coords_per_limb[limb_type][0] - # And the y-coord paf index - limb_intermed_coords[ - 3, :] = self.paf_xy_coords_per_limb[limb_type][1] - for i, joint_src in enumerate(joints_src): - # Try every possible joints_src[i]-joints_dst[j] - # pair and see if it's a feasible limb - for j, joint_dst in enumerate(joints_dst): - # Subtract the position of both joints to obtain - # the direction of the potential limb - limb_dir = joint_dst[:2] - joint_src[:2] - # Compute the distance/length of the potential - # limb (norm of limb_dir) - limb_dist = np.sqrt(np.sum(limb_dir**2)) + 1e-8 - limb_dir = limb_dir / limb_dist - # Normalize limb_dir to be a unit vector - - # Linearly distribute num_intermed_pts points - # from the x coordinate of joint_src to the - # x coordinate of joint_dst - limb_intermed_coords[1, :] = np.round( - np.linspace( - joint_src[0], - joint_dst[0], - num=num_intermed_pts)) - # Same for the y coordinate - limb_intermed_coords[0, :] = np.round( - np.linspace( - joint_src[1], - joint_dst[1], - num=num_intermed_pts)) - intermed_paf = paf_upsamp[limb_intermed_coords[0, :], - limb_intermed_coords[1, :], - limb_intermed_coords[ - 2:4, :]].T - - score_intermed_pts = intermed_paf.dot(limb_dir) - score_penalizing_long_dist = score_intermed_pts.mean( - ) + min(0.5 * paf_upsamp.shape[0] / limb_dist - 1, 0) - # Criterion 1: At least 80% of the intermediate - # points have a score higher than thre2 - criterion1 = ( - np.count_nonzero(score_intermed_pts > self.thre2) > - 0.8 * num_intermed_pts) - # Criterion 2: Mean score, penalized for large limb - # distances (larger than half the image height), is - # positive - criterion2 = (score_penalizing_long_dist > 0) - if criterion1 and criterion2: - # Last value is the combined paf (+limb_dist) - # + heatmap scores of both joints - connection_candidates.append([ - i, j, score_penalizing_long_dist, - score_penalizing_long_dist + joint_src[2] + - joint_dst[2] - ]) - - # Sort connection candidates based on their - # score_penalizing_long_dist - connection_candidates = sorted( - connection_candidates, key=lambda x: x[2], reverse=True) - connections = np.empty((0, 5)) - # There can only be as many limbs as the smallest number of - # source or destination joints (eg: only 2 forearms if - # there's 5 wrists but 2 elbows) - max_connections = min(len(joints_src), len(joints_dst)) - # Traverse all potential joint connections (sorted by their - # score) - for potential_connection in connection_candidates: - i, j, s = potential_connection[0:3] - # Make sure joints_src[i] or joints_dst[j] haven't - # already been connected to other joints_dst or - # joints_ src - if i not in connections[:, 3] and \ - j not in connections[:, 4]: - # [joint_src_id, joint_dst_id, - # limb_score_penalizing_long_dist, joint_src_index, - # joint_dst_index] - connections = np.vstack([ - connections, - [joints_src[i][3], joints_dst[j][3], s, i, j] - ]) - # Exit if we've already established max_connections - # connections (each joint can't be connected to more - # than one joint) - if len(connections) >= max_connections: - break - connected_limbs.append(connections) - - return connected_limbs - - def group_limbs_of_same_person(self, connected_limbs, joint_list): - """Associate limbs belonging to the same person together. - - :param connected_limbs: See 'return' doc of - find_connected_joints() - :param joint_list: unravel'd version of joint_list_per_joint - [See 'return' doc of NMS()] - :return: 2d np.array of size num_people x (NUM_JOINTS+2). - For each person found: - # First NUM_JOINTS columns contain the index (in joint_list) - of the joints associated with that person (or -1 if their - i-th joint wasn't found) - # 2nd-to-last column: Overall score of the joints+limbs that - belong to this person - # Last column: Total count of joints found for this person + Note: + batch size: N + number of people: M + number of keypoints: K + number of detected keypoints in the image: P + + Args: + all_keypoints (np.ndarray(P, 4)): Each keypoint contains + (x, y, score, keypoint id) + pose_entries (np.ndarray(M, K + 2)): For each person, + it contains K keypoint id, the human score, and + the number of detected keypoints. + + Returns: + ans (list(np.ndarray)): Pose results. """ - person_to_joint_assoc = [] - - for limb_type in range(self.NUM_LIMBS): - joint_src_type, joint_dst_type = \ - self.joint_to_limb_heatmap_relationship[limb_type] - - for limb_info in connected_limbs[limb_type]: - person_assoc_idx = [] - for person, person_limbs in enumerate(person_to_joint_assoc): - if person_limbs[joint_src_type] == limb_info[ - 0] or person_limbs[joint_dst_type] == limb_info[1]: - person_assoc_idx.append(person) - - # If one of the joints has been associated to a person, - # and either the other joint is also associated with the same - # person or not associated to anyone yet: - if len(person_assoc_idx) == 1: - person_limbs = person_to_joint_assoc[person_assoc_idx[0]] - # If the other joint is not associated to anyone yet, - if person_limbs[joint_src_type] == limb_info[0] and \ - person_limbs[joint_dst_type] != limb_info[1]: - # Associate it with the current person - person_limbs[joint_dst_type] = limb_info[1] - # Increase the number of limbs associated to - # this person - person_limbs[-1] += 1 - # And update the total score (+= heatmap score - # of joint_dst + score of connecting joint_src with - # joint_dst) - person_limbs[-2] += joint_list[ - limb_info[1].astype(int), 2] + limb_info[2] - elif person_limbs[joint_src_type] != limb_info[0] and \ - person_limbs[joint_dst_type] == limb_info[1]: - # Associate it with the current person - person_limbs[joint_src_type] = limb_info[0] - # Increase the number of limbs associated to - # this person - person_limbs[-1] += 1 - # And update the total score (+= heatmap score - # of joint_dst + score of connecting joint_src with - # joint_dst) - person_limbs[-2] += joint_list[ - limb_info[0].astype(int), 2] + limb_info[2] - else: - NotImplementedError() - - elif len(person_assoc_idx - ) == 2: # if found 2 and disjoint, merge them - person1_limbs = person_to_joint_assoc[person_assoc_idx[0]] - person2_limbs = person_to_joint_assoc[person_assoc_idx[1]] - membership = ((person1_limbs >= 0) & - (person2_limbs >= 0))[:-2] - if not membership.any( - ): # If both people have no same joints connected, - # merge them into a single person - # Update which joints are connected - person1_limbs[:-2] += (person2_limbs[:-2] + 1) - # Update the overall score and total count of - # joints connected by summing their counters - person1_limbs[-2:] += person2_limbs[-2:] - # Add the score of the current joint connection - # to the overall score - person1_limbs[-2] += limb_info[2] - person_to_joint_assoc.pop(person_assoc_idx[1]) - else: # Same case as len(person_assoc_idx)==1 above - person1_limbs[joint_dst_type] = limb_info[1] - person1_limbs[-1] += 1 - person1_limbs[-2] += joint_list[ - limb_info[1].astype(int), 2] + limb_info[2] - else: - # No person has claimed any of these joints, create - # a new person Initialize person info to all -1 - # (no joint associations) - row = -1 * np.ones(self.params.num_joints + 2) - # Store the joint info of the new connection - row[joint_src_type] = limb_info[0] - row[joint_dst_type] = limb_info[1] - # Total count of connected joints for this person: 2 - row[-1] = 2 - # Compute overall score: score joint_src + score - # joint_dst + score connection - # {joint_src,joint_dst} - row[-2] = sum(joint_list[limb_info[:2].astype(int), - 2]) + limb_info[2] - person_to_joint_assoc.append(row) - - # Delete people who have very few parts connected - people_to_delete = [] - for person_id, person_info in enumerate(person_to_joint_assoc): - if person_info[-1] < 3 or person_info[-2] / person_info[-1] < 0.2: - people_to_delete.append(person_id) - # Traverse the list in reverse order so we delete indices - # starting from the - # last one (otherwise, removing item for example 0 would - # modify the indices of - # the remaining people to be deleted!) - for index in people_to_delete[::-1]: - person_to_joint_assoc.pop(index) - - # Appending items to a np.array can be very costly - # (allocating new memory, copying over the array, - # then adding new row) - # Instead, we treat the set of people as a list - # (fast to append items) and - # only convert to np.array at the end - return np.array(person_to_joint_assoc) - - def output_format(self, joint_list, person_to_joint_assoc): ans = [] - if len(person_to_joint_assoc) > 0: - for person in person_to_joint_assoc: - ans_person = np.zeros((self.params.num_joints, 5)) + if len(pose_entries) > 0: + for person in pose_entries: + ans_person = np.zeros( + (self.params.num_joints, all_keypoints.shape[1]), + np.float32) for j in range(self.params.num_joints): joint_id = int(person[j]) if joint_id < 0: continue - ans_person[j] = joint_list[joint_id] - ans_person[:, :2] /= 4 + ans_person[j] = all_keypoints[joint_id] ans.append(ans_person) return [np.stack(ans)] else: return [] - def match(self, heatmaps, pafs): - # Step 1: find all joints in the image (organized by joint type: - # [0]=nose, [1]=neck...) - heatmaps = np.transpose(heatmaps[0], [1, 2, 0]) - pafs = np.transpose(pafs[0], [1, 2, 0]) - - # 4 = img_orig.shape[0] / float(heatmaps.shape[0]) - joint_list_per_joint_type = self.NMS(heatmaps, 4) - # joint_list is an unravel'd version of joint_list_per_joint, - # where we add a 5th column to indicate the joint_type - # (0=nose, 1=neck...) - joint_list = np.array([ - tuple(peak) + (joint_type, ) - for joint_type, joint_peaks in enumerate(joint_list_per_joint_type) - for peak in joint_peaks - ]) - - # Step 2: find which joints go together to form limbs - # (which wrists go with which elbows) - paf_upsamp = cv2.resize( - pafs, (heatmaps.shape[1] * 4, heatmaps.shape[0] * 4), - interpolation=cv2.INTER_CUBIC) - connected_limbs = self.find_connected_joints( - paf_upsamp, joint_list_per_joint_type) - - # Step 3: associate limbs that belong to the same person - person_to_joint_assoc = self.group_limbs_of_same_person( - connected_limbs, joint_list) - - ans = self.output_format(joint_list, person_to_joint_assoc) - scores = [person[-2] for person in person_to_joint_assoc] + def connections_nms(self, a_idx, b_idx, affinity_scores): + """From all retrieved connections that share the same starting/ending + keypoints leave only the top-scoring ones. + + Args: + a_idx (list(int)): index of the starting keypoints. + b_idx (list(int)): index of the ending keypoints. + affinity_scores (list(float)): affinity scores. + + Returns: + a_idx (list(int)): index of the starting keypoints. + b_idx (list(int)): index of the ending keypoints. + affinity_scores (list(float)): affinity scores. + """ + order = affinity_scores.argsort()[::-1] + affinity_scores = affinity_scores[order] + a_idx = a_idx[order] + b_idx = b_idx[order] + idx = [] + has_kpt_a = set() + has_kpt_b = set() + for t, (i, j) in enumerate(zip(a_idx, b_idx)): + if i not in has_kpt_a and j not in has_kpt_b: + idx.append(t) + has_kpt_a.add(i) + has_kpt_b.add(j) + idx = np.asarray(idx, dtype=np.int32) + return a_idx[idx], b_idx[idx], affinity_scores[idx] + + def group_keypoints(self, all_keypoints_by_type, pafs): + """Group keypoints based on part-affinity fields. + + Note: + batch size: N + number of keypoints: K + heatmap height: H + heatmap width: W + + Args: + all_keypoints_by_type (list(tuple)): list of tuples + containing keypoint detection results (x, y, score, id). + pafs (np.ndarray[W, H, C]): part-affinity fields + + Returns: + - ans (list(np.array([M, K, 4]))): Keypoint predictions. + - scores (list): Score of people. + """ + pose_entries = [] + all_keypoints = np.array( + [item for sublist in all_keypoints_by_type for item in sublist]) + points_per_limb = 10 + grid = np.arange(points_per_limb, dtype=np.float32).reshape(1, -1, 1) + all_keypoints_by_type = [ + np.array(keypoints, np.float32) + for keypoints in all_keypoints_by_type + ] + for part_id in range(len(self.limb2paf)): + part_pafs = pafs[:, :, self.limb2paf[part_id]] + kpts_a = all_keypoints_by_type[self.limb2joint[part_id][0]] + kpts_b = all_keypoints_by_type[self.limb2joint[part_id][1]] + n = len(kpts_a) + m = len(kpts_b) + if n == 0 or m == 0: + continue + + # Get vectors between all pairs of keypoints, + # i.e. candidate limb vectors. + a = kpts_a[:, :2] + a = np.broadcast_to(a[None], (m, n, 2)) + b = kpts_b[:, :2] + vec_raw = (b[:, None, :] - a).reshape(-1, 1, 2) + + # Sample points along every candidate limb vector. + steps = (1 / (points_per_limb - 1) * vec_raw) + points = steps * grid + a.reshape(-1, 1, 2) + points = points.round().astype(dtype=np.int32) + x = points[..., 0].ravel() + y = points[..., 1].ravel() + + # Compute affinity score between candidate + # limb vectors and part affinity field. + field = part_pafs[y, x].reshape(-1, points_per_limb, 2) + vec_norm = np.linalg.norm(vec_raw, ord=2, axis=-1, keepdims=True) + vec = vec_raw / (vec_norm + 1e-6) + affinity_scores = (field * + vec).sum(-1).reshape(-1, points_per_limb) + valid_affinity_scores = affinity_scores > self.paf_thr + valid_num = valid_affinity_scores.sum(1) + affinity_scores = (affinity_scores * + valid_affinity_scores).sum(1) / ( + valid_num + 1e-6) + success_ratio = valid_num / points_per_limb + + # Get a list of limbs according to the obtained affinity score. + valid_limbs = np.where( + np.logical_and(affinity_scores > 0, success_ratio > 0.8))[0] + if len(valid_limbs) == 0: + continue + b_idx, a_idx = np.divmod(valid_limbs, n) + affinity_scores = affinity_scores[valid_limbs] + + # Suppress incompatible connections. + a_idx, b_idx, affinity_scores = self.connections_nms( + a_idx, b_idx, affinity_scores) + connections = list( + zip(kpts_a[a_idx, 3].astype(np.int32), + kpts_b[b_idx, 3].astype(np.int32), affinity_scores)) + if len(connections) == 0: + continue + + if part_id == 0: + pose_entries = [ + np.ones(self.params.num_joints + 2) * -1 + for _ in range(len(connections)) + ] + for i in range(len(connections)): + pose_entries[i][self.limb2joint[0][0]] = connections[i][0] + pose_entries[i][self.limb2joint[0][1]] = connections[i][1] + pose_entries[i][-1] = 2 + pose_entries[i][-2] = np.sum( + all_keypoints[connections[i][0:2], + 2]) + connections[i][2] + else: + kpt_a_id = self.limb2joint[part_id][0] + kpt_b_id = self.limb2joint[part_id][1] + for i in range(len(connections)): + found_pose_list = [] + for j in range(len(pose_entries)): + if pose_entries[j][kpt_a_id] == connections[i][ + 0] and pose_entries[j][kpt_b_id] == -1: + pose_entries[j][kpt_b_id] = connections[i][1] + pose_entries[j][-1] += 1 + pose_entries[j][-2] += all_keypoints[ + connections[i][1], 2] + connections[i][2] + found_pose_list.append( + (j, all_keypoints[connections[i][1], 2] + + connections[i][2])) + + if pose_entries[j][kpt_b_id] == connections[i][ + 1] and pose_entries[j][kpt_a_id] == -1: + pose_entries[j][kpt_a_id] = connections[i][0] + pose_entries[j][-1] += 1 + pose_entries[j][-2] += all_keypoints[ + connections[i][1], 2] + connections[i][2] + found_pose_list.append( + (j, all_keypoints[connections[i][1], 2] + + connections[i][2])) + + if len(found_pose_list) == 0: + pose_entry = np.ones(self.params.num_joints + 2) * -1 + pose_entry[kpt_a_id] = connections[i][0] + pose_entry[kpt_b_id] = connections[i][1] + pose_entry[-1] = 2 + pose_entry[-2] = np.sum( + all_keypoints[connections[i][0:2], + 2]) + connections[i][2] + pose_entries.append(pose_entry) + + elif len(found_pose_list) == 2: + # merge two pose entries + found_pose_list.sort(key=lambda x: x[0], reverse=True) + pose_entry = np.ones(self.params.num_joints + 2) * -1 + + entry_id1, score1 = found_pose_list[0] + entry_id2, score2 = found_pose_list[1] + assert score1 == score2 + + pose_entry1 = pose_entries.pop(entry_id1) + pose_entry2 = pose_entries.pop(entry_id2) + + num_kpt = 0 + score = pose_entry1[-2] + pose_entry2[-2] - score1 + + for j in range(self.params.num_joints): + kpt_id1 = int(pose_entry1[j]) + kpt_id2 = int(pose_entry2[j]) + + if kpt_id1 == -1 and kpt_id2 == -1: + continue + elif kpt_id1 == -1 and kpt_id2 != -1: + pose_entry[j] = kpt_id2 + num_kpt += 1 + elif kpt_id2 == -1 and kpt_id1 != -1: + pose_entry[j] = kpt_id1 + num_kpt += 1 + else: + # both have the same joint-id, + # choose the one with higher score. + if all_keypoints[kpt_id1, + 2] > all_keypoints[kpt_id2, + 2]: + pose_entry[j] = kpt_id1 + else: + pose_entry[j] = kpt_id2 + num_kpt += 1 + + pose_entry[-2] = score + pose_entry[-1] = num_kpt + + pose_entries.append(pose_entry) + + filtered_entries = [] + for i in range(len(pose_entries)): + if pose_entries[i][-1] < 3 or ( + pose_entries[i][-2] / pose_entries[i][-1] < 0.2): + continue + filtered_entries.append(pose_entries[i]) + pose_entries = np.asarray(filtered_entries) + + ans = self.output_format(all_keypoints, pose_entries) + scores = [person[-2] for person in pose_entries] return ans, scores + def get_keypoints(self, heatmaps): + """Extract keypoints from heatmaps. + + Note: + batch size: N + number of keypoints: K + heatmap height: H + heatmap width: W + + Args: + heatmaps (torch.Tensor[NxKxHxW]): model output heatmaps. + + Returns: + list(tuple): list of tuples containing keypoint detection + results (x, y, score, id). + """ + + keypoint_num = 0 + all_keypoints_by_type = [[] for _ in range(self.params.num_joints)] + + heatmaps = self.nms(heatmaps) + N, K, H, W = heatmaps.size() + val_k, ind_k = self.top_k_value(heatmaps, self.params.max_num_people) + + x = ind_k % W + y = ind_k // W + + loc_k = torch.stack((x, y), dim=3) + + for kpt_idx in range(self.params.num_joints): + for m in range(self.params.max_num_people): + if val_k[0][kpt_idx][m] < self.params.detection_threshold: + break + else: + x = loc_k[0][kpt_idx][m][0].item() + y = loc_k[0][kpt_idx][m][1].item() + score = val_k[0][kpt_idx][m].item() + all_keypoints_by_type[kpt_idx].append( + (x, y, score, keypoint_num)) + keypoint_num += 1 + + return all_keypoints_by_type + def parse(self, heatmaps, pafs, adjust=True, refine=True): """Group keypoints into poses given heatmap and paf. Note: - batch size: N + batch size: N (currently we only support N==1) number of people: M number of keypoints: K number of paf maps: P @@ -977,12 +792,16 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): Returns: tuple: A tuple containing keypoint grouping results. - - ans (list(np.array([M,K,5]))): Keypoint predictions. + - ans (list(np.array([M,K,4]))): Keypoint predictions. - scores (list): Score of people. """ - # assert 0, 'The post-process of paf have not been completed.' - ans, scores = self.match(heatmaps.cpu().numpy(), pafs.cpu().numpy()) + assert heatmaps.shape[0] == 1, 'The batch size is ' \ + f'{heatmaps.shape[0]}, but we only support batch size==1.' + + all_keypoints_by_type = self.get_keypoints(heatmaps) + pafs_np = np.transpose(pafs.detach().cpu().numpy()[0], [1, 2, 0]) + ans, scores = self.group_keypoints(all_keypoints_by_type, pafs_np) if adjust: if self.use_udp: diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 9ca9d576d2..cd2ff6ed0e 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -303,23 +303,6 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): aggregate_scale='average', align_corners=self.use_udp) - import cv2 - import numpy as np - - def torch2img(tens, idx=0): - return np.transpose(tens[idx].detach().cpu().numpy(), [1, 2, 0]) - - for i in range(17): - heatmap_np = torch2img(aggregated_heatmaps, 0) - cv2.imwrite( - f'pred_heatmap_{i}.jpg', - np.repeat(np.abs(heatmap_np[:, :, i:i + 1]) * 255, 3, axis=2)) - for i in range(38): - paf_np = torch2img(aggregated_pafs, 0) - cv2.imwrite( - f'pred_paf_{i}.jpg', - np.repeat(np.abs(paf_np[:, :, i:i + 1]) * 255, 3, axis=2)) - # perform grouping grouped, scores = self.parser.parse(aggregated_heatmaps, aggregated_pafs, From e251ee86126f83d24f19ad2bb69ed91758073bd4 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 23 Jun 2021 22:04:28 +0800 Subject: [PATCH 30/98] fix bugs in flip paf --- .../coco/hrnet_w32_coco_512x512.py | 2 +- .../coco/res50_coco_512x512.py | 2 +- mmpose/apis/inference.py | 9 ++-- mmpose/core/evaluation/__init__.py | 6 +-- mmpose/core/evaluation/bottom_up_eval.py | 50 +++++++++++++++++-- .../datasets/bottom_up/bottom_up_coco.py | 6 --- .../models/detectors/associative_embedding.py | 8 +-- mmpose/models/detectors/paf.py | 16 +++--- 8 files changed, 63 insertions(+), 36 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index 33a3166595..8a1e626352 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -176,7 +176,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'flip_index_paf' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index 29ecc417bc..be446902da 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -145,7 +145,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'flip_index_paf' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/mmpose/apis/inference.py b/mmpose/apis/inference.py index cb1918c9a9..77cb710048 100644 --- a/mmpose/apis/inference.py +++ b/mmpose/apis/inference.py @@ -470,11 +470,10 @@ def inference_bottom_up_pose_model(model, cfg.data_cfg['num_joints'], 'flip_index': [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15], - 'flip_index_paf': [ - 4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 12, 13, 10, 11, 14, 15, 18, 19, - 16, 17, 22, 23, 20, 21, 24, 25, 28, 29, 26, 27, 32, 33, 30, 31, - 36, 37, 34, 35 - ] + 'skeleton': [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], + [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], + [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], + [3, 5], [4, 6]] } } diff --git a/mmpose/core/evaluation/__init__.py b/mmpose/core/evaluation/__init__.py index de0503e62b..2c2984f313 100644 --- a/mmpose/core/evaluation/__init__.py +++ b/mmpose/core/evaluation/__init__.py @@ -1,6 +1,6 @@ from .bottom_up_eval import (aggregate_scale, aggregate_stage_flip, - flip_feature_maps, get_group_preds, - split_ae_outputs) + flip_feature_maps, flip_part_affinity_fields, + get_group_preds, split_ae_outputs) from .eval_hooks import DistEvalHook, EvalHook from .mesh_eval import compute_similarity_transform from .pose3d_eval import keypoint_mpjpe @@ -16,5 +16,5 @@ 'keypoint_epe', 'get_group_preds', 'split_ae_outputs', 'flip_feature_maps', 'aggregate_stage_flip', 'aggregate_scale', 'compute_similarity_transform', 'post_dark_udp', 'keypoint_mpjpe', 'keypoints_from_heatmaps3d', - 'multilabel_classification_accuracy' + 'multilabel_classification_accuracy', 'flip_part_affinity_fields' ] diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 71dc6dfc23..44812a4348 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -35,21 +35,19 @@ def split_ae_outputs(outputs, num_joints, with_heatmaps, with_ae): return heatmaps, tags -def flip_feature_maps(feature_maps, flip_index=None, flip_output=False): +def flip_feature_maps(feature_maps, flip_index=None): """Flip the feature maps and swap the channels. Args: feature_maps (list(torch.Tensor)): Feature maps. flip_index (list(int) | None): Channel-flip indexes. If None, do not flip channels. - flip_output (bool): Whether to perform horizontal-flip. Returns: flipped_feature_maps (list(torch.Tensor)): Flipped feature_maps. """ flipped_feature_maps = [] for feature_map in feature_maps: - if flip_output: - feature_map = torch.flip(feature_map, [3]) + feature_map = torch.flip(feature_map, [3]) if flip_index is not None: flipped_feature_maps.append(feature_map[:, flip_index, :, :]) else: @@ -58,6 +56,50 @@ def flip_feature_maps(feature_maps, flip_index=None, flip_output=False): return flipped_feature_maps +def flip_part_affinity_fields(pafs, flip_index, skeleton): + """Flip the feature maps and swap the channels. + + Args: + feature_maps (list(torch.Tensor)): Feature maps. + flip_index (list(int) | None): Channel-flip indexes. If None, + do not flip channels. + Returns: + flipped_feature_maps (list(torch.Tensor)): Flipped feature_maps. + """ + + flipped_skeleton = [[flip_index[a], flip_index[b]] for a, b in skeleton] + + flip_index_paf = [] + flip_x_index = [] + for sk_id, sk in enumerate(flipped_skeleton): + try: + # found flip-pairs + ind = skeleton.index(sk) + flip_x_index.append(sk_id * 2) + except ValueError: + try: + # unidirectional edge + ind = skeleton.index([sk[1], sk[0]]) + except ValueError: + raise ValueError('The skeleton should be symmetric.') + + flip_index_paf.append(2 * ind) + flip_index_paf.append(2 * ind + 1) + + flipped_pafs = [] + for paf in pafs: + paf = torch.flip(paf, [3]) + # flip the x-axis direction + paf[:, flip_x_index, :, :] *= -1 + # flip channels + if flip_index is not None: + flipped_pafs.append(paf[:, flip_index_paf, :, :]) + else: + flipped_pafs.append(paf) + + return flipped_pafs + + def _resize_average(feature_maps, align_corners, index=-1, resize_size=None): """Resize the feature maps and compute the average. diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index 2b97c7553b..7f1ea14b4c 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -68,12 +68,6 @@ def __init__(self, [0, 1], [0, 2], [1, 3], [2, 4], [3, 5], [4, 6]] - self.ann_info['flip_index_paf'] = [ - 4, 5, 6, 7, 0, 1, 2, 3, 8, 9, 12, 13, 10, 11, 14, 15, 18, 19, 16, - 17, 22, 23, 20, 21, 24, 25, 28, 29, 26, 27, 32, 33, 30, 31, 36, 37, - 34, 35 - ] - self.ann_info['use_different_joint_weights'] = False self.ann_info['joint_weights'] = np.array( [ diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index bc05c3e60b..c5b4c9de45 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -252,14 +252,10 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): self.test_cfg['with_heatmaps'], self.test_cfg['with_ae']) heatmaps_flipped = flip_feature_maps( - heatmaps_flipped, - flip_index=img_metas['flip_index'], - flip_output=True) + heatmaps_flipped, flip_index=img_metas['flip_index']) if self.test_cfg['tag_per_joint']: tags_flipped = flip_feature_maps( - tags_flipped, - flip_index=img_metas['flip_index'], - flip_output=True) + tags_flipped, flip_index=img_metas['flip_index']) else: tags_flipped = flip_feature_maps( tags_flipped, flip_index=None, flip_output=True) diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index cd2ff6ed0e..d59c239549 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -6,7 +6,8 @@ from mmcv.visualization.image import imshow from mmpose.core.evaluation import (aggregate_scale, aggregate_stage_flip, - flip_feature_maps, get_group_preds) + flip_feature_maps, + flip_part_affinity_fields, get_group_preds) from mmpose.core.post_processing.group import PAFParser from mmpose.core.visualization import imshow_keypoints from .. import builder @@ -246,16 +247,11 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): pafs_flipped = outputs_flipped['pafs'][-1] heatmaps_flipped = flip_feature_maps( - heatmaps_flipped, - flip_index=img_metas['flip_index'], - flip_output=True) - pafs_flipped = flip_feature_maps( + heatmaps_flipped, flip_index=img_metas['flip_index']) + pafs_flipped = flip_part_affinity_fields( pafs_flipped, - flip_index=img_metas['flip_index_paf'], - flip_output=True) - for _pafs in pafs_flipped: - # flip the x-axis - _pafs[:, ::2, :, :] *= -1 + flip_index=img_metas['flip_index'], + skeleton=img_metas['skeleton']) else: heatmaps_flipped = None From 4c4e174ccbe4e2ff2e3c937fa623d01ad55e138c Mon Sep 17 00:00:00 2001 From: jin-s13 Date: Thu, 24 Jun 2021 15:33:43 +0800 Subject: [PATCH 31/98] update unittest --- mmpose/core/evaluation/bottom_up_eval.py | 8 ++++---- tests/test_evaluation/test_bottom_up_eval.py | 20 +++++++++++++++++--- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/mmpose/core/evaluation/bottom_up_eval.py b/mmpose/core/evaluation/bottom_up_eval.py index 44812a4348..98b6daaace 100644 --- a/mmpose/core/evaluation/bottom_up_eval.py +++ b/mmpose/core/evaluation/bottom_up_eval.py @@ -57,16 +57,16 @@ def flip_feature_maps(feature_maps, flip_index=None): def flip_part_affinity_fields(pafs, flip_index, skeleton): - """Flip the feature maps and swap the channels. + """Flip the part affinity fields and swap the channels. Args: - feature_maps (list(torch.Tensor)): Feature maps. + pafs (list(torch.Tensor)): Part-affinity fields. flip_index (list(int) | None): Channel-flip indexes. If None, do not flip channels. + skeleton (list(list(int, int))): Pairs of linked keypoints. Returns: - flipped_feature_maps (list(torch.Tensor)): Flipped feature_maps. + flipped_pafs (list(torch.Tensor)): Flipped pafs. """ - flipped_skeleton = [[flip_index[a], flip_index[b]] for a, b in skeleton] flip_index_paf = [] diff --git a/tests/test_evaluation/test_bottom_up_eval.py b/tests/test_evaluation/test_bottom_up_eval.py index f4e8622a67..9993219880 100644 --- a/tests/test_evaluation/test_bottom_up_eval.py +++ b/tests/test_evaluation/test_bottom_up_eval.py @@ -1,8 +1,10 @@ import numpy as np +import pytest import torch from mmpose.core import (aggregate_scale, aggregate_stage_flip, - flip_feature_maps, get_group_preds, split_ae_outputs) + flip_feature_maps, flip_part_affinity_fields, + get_group_preds, split_ae_outputs) def test_split_ae_outputs(): @@ -13,8 +15,20 @@ def test_split_ae_outputs(): def test_flip_feature_maps(): fake_outputs = [torch.zeros((1, 4, 2, 2))] - _ = flip_feature_maps(fake_outputs, None, False) - _ = flip_feature_maps(fake_outputs, flip_index=[1, 0], flip_output=True) + _ = flip_feature_maps(fake_outputs, None) + _ = flip_feature_maps(fake_outputs, flip_index=[1, 0]) + + +def test_flip_part_affinity_fields(): + fake_outputs = [torch.zeros((1, 4, 2, 2))] + + _ = flip_part_affinity_fields(fake_outputs, None, skeleton=[]) + _ = flip_part_affinity_fields( + fake_outputs, flip_index=[1, 0], skeleton=[[0, 1]]) + + with pytest.raises(ValueError): + _ = flip_part_affinity_fields( + fake_outputs, flip_index=[1, 0], skeleton=[[0, 0]]) def test_aggregate_stage_flip(): From 3e18b2aa6cbc7514bad531c9a95bbb8406128d5d Mon Sep 17 00:00:00 2001 From: jin-s13 Date: Thu, 24 Jun 2021 15:48:52 +0800 Subject: [PATCH 32/98] add 'align_corners' in cfg --- .../aic/higherhrnet_w32_aic_512x512.py | 1 + .../associative_embedding/aic/hrnet_w32_aic_512x512.py | 1 + .../coco/higherhrnet_w32_coco_512x512.py | 1 + .../coco/higherhrnet_w32_coco_512x512_udp.py | 1 + .../coco/higherhrnet_w32_coco_640x640.py | 1 + .../coco/higherhrnet_w32_coco_640x640_udp.py | 1 + .../coco/higherhrnet_w48_coco_512x512.py | 1 + .../coco/higherhrnet_w48_coco_512x512_udp.py | 1 + .../associative_embedding/coco/hrnet_w32_coco_512x512.py | 1 + .../coco/hrnet_w32_coco_512x512_udp.py | 1 + .../associative_embedding/coco/hrnet_w32_coco_640x640.py | 1 + .../coco/hrnet_w32_coco_640x640_udp.py | 1 + .../associative_embedding/coco/hrnet_w48_coco_512x512.py | 1 + .../coco/hrnet_w48_coco_512x512_udp.py | 1 + .../associative_embedding/coco/hrnet_w48_coco_640x640.py | 1 + .../coco/hrnet_w48_coco_640x640_udp.py | 1 + .../coco/mobilenetv2_coco_512x512.py | 1 + .../associative_embedding/coco/res101_coco_512x512.py | 1 + .../associative_embedding/coco/res101_coco_640x640.py | 1 + .../associative_embedding/coco/res152_coco_512x512.py | 1 + .../associative_embedding/coco/res152_coco_640x640.py | 1 + .../associative_embedding/coco/res50_coco_512x512.py | 1 + .../associative_embedding/coco/res50_coco_640x640.py | 1 + .../crowdpose/higherhrnet_w32_crowdpose_512x512.py | 1 + .../crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py | 1 + .../crowdpose/higherhrnet_w32_crowdpose_640x640.py | 1 + .../crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py | 1 + .../crowdpose/higherhrnet_w48_crowdpose_512x512.py | 1 + .../crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py | 1 + .../crowdpose/mobilenetv2_crowdpose_512x512.py | 1 + .../crowdpose/res101_crowdpose_512x512.py | 1 + .../crowdpose/res152_crowdpose_512x512.py | 1 + .../crowdpose/res50_crowdpose_512x512.py | 1 + .../associative_embedding/mhp/hrnet_w48_mhp_512x512.py | 1 + .../part_affinity_field/coco/hrnet_w32_coco_512x512.py | 1 + .../part_affinity_field/coco/res50_coco_512x512.py | 1 + .../higherhrnet_w32_coco_wholebody_512x512.py | 1 + .../higherhrnet_w32_coco_wholebody_640x640.py | 1 + .../higherhrnet_w48_coco_wholebody_512x512.py | 1 + .../higherhrnet_w48_coco_wholebody_640x640.py | 1 + .../coco-wholebody/hrnet_w32_coco_wholebody_512x512.py | 1 + .../coco-wholebody/hrnet_w32_coco_wholebody_640x640.py | 1 + .../coco-wholebody/hrnet_w48_coco_wholebody_512x512.py | 1 + .../coco-wholebody/hrnet_w48_coco_wholebody_640x640.py | 1 + mmpose/models/detectors/associative_embedding.py | 9 ++++----- mmpose/models/detectors/paf.py | 9 ++++----- 46 files changed, 52 insertions(+), 10 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py index 18232da1a6..03e6a87c49 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py index b47d60d2d5..5aa4cf7fbe 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py @@ -108,6 +108,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py index c90d963323..17e8ce8179 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py index fce8a984e4..710efa958e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py index be70c08c8f..5054ec5ffd 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py index a188c49658..0255ca09aa 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py index 9c2556dcea..d5e7a33e75 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py index 21e4e9e676..05e1cb3899 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py index af264c5d80..674d5a5f92 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py index fcce049a87..a482b70269 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py index 3932853586..3c756f6c8d 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py index d7bd592ddf..4c52f5c433 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py index 2f1d9c2b4c..ddcff0b45a 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py index 8be8badf1a..2297593ac2 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py index 3696316448..7cf4cfbec2 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py index c1dc7849f9..f71ac4e6e8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py index 3f5dc99686..7593f8f7e8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py index 025daa8266..83926738be 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py index 8d0ae90a12..9036ded98f 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py index 4cb0aeb580..c3639afa6e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py index d75f69e511..6827e4e184 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py index 058cac49ef..a30e40f41f 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py @@ -79,6 +79,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py index 68e1716705..e023a1e8f6 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py index 4746ae594f..0e91de073d 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py index 7538300d2c..a7aff7deee 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py index ece8ccbb9b..66b7510279 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py index 24c33b3d60..274f60ec71 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py index 8addf87d6c..f55083ebe0 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py index 0ee83bba23..ef5ed914de 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py @@ -112,6 +112,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=False, + align_corners=True, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py index 2f035e99e6..fe38c94d5b 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py @@ -77,6 +77,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py index 8fb3959670..340f8c04e9 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py @@ -77,6 +77,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py index 45d740e699..6378529d58 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py @@ -77,6 +77,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py index aa161e3fe2..e87af8ce0b 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py @@ -78,6 +78,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py index 27ce967f17..a4b5142882 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py @@ -107,6 +107,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index 8a1e626352..0828c5a393 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -120,6 +120,7 @@ with_heatmaps=[True], with_pafs=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index be446902da..ad20ea764e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -89,6 +89,7 @@ with_heatmaps=[True], with_pafs=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_512x512.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_512x512.py index db89340076..c4060f7c4d 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_512x512.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_512x512.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_640x640.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_640x640.py index 4483e6eb81..09c1562b5a 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_640x640.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w32_coco_wholebody_640x640.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_512x512.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_512x512.py index b05b0ad812..0ecbe2f070 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_512x512.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_512x512.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_640x640.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_640x640.py index 38a6938ab3..b406b94b86 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_640x640.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_w48_coco_wholebody_640x640.py @@ -113,6 +113,7 @@ with_heatmaps=[True, True], with_ae=[True, False], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_512x512.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_512x512.py index 06ff2edf81..2cee3f056a 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_512x512.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_512x512.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_640x640.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_640x640.py index 595ecb0052..40df05bc05 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_640x640.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w32_coco_wholebody_640x640.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_512x512.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_512x512.py index a9a567b48f..d62412a6fe 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_512x512.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_512x512.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_640x640.py b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_640x640.py index c320d625b2..2b0f7cfb92 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_640x640.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_w48_coco_wholebody_640x640.py @@ -109,6 +109,7 @@ with_heatmaps=[True], with_ae=[True], project2image=True, + align_corners=False, nms_kernel=5, nms_padding=2, tag_per_joint=True, diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index c5b4c9de45..59eaac57dc 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -264,14 +264,13 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): heatmaps_flipped = None tags_flipped = None - # TODO: move `align_corners' to test_cfg aggregated_heatmaps = aggregate_stage_flip( heatmaps, heatmaps_flipped, index=-1, project2image=self.test_cfg['project2image'], size_projected=base_size, - align_corners=self.use_udp, + align_corners=self.test_cfg.get('align_corners', True), aggregate_stage='average', aggregate_flip='average') @@ -281,7 +280,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): index=-1, project2image=self.test_cfg['project2image'], size_projected=base_size, - align_corners=self.use_udp, + align_corners=self.test_cfg.get('align_corners', True), aggregate_stage='concat', aggregate_flip='concat') @@ -298,12 +297,12 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): aggregated_heatmaps = aggregate_scale( scale_heatmaps_list, - align_corners=self.use_udp, + align_corners=self.test_cfg.get('align_corners', True), aggregate_scale='average') aggregated_tags = aggregate_scale( scale_tags_list, - align_corners=self.use_udp, + align_corners=self.test_cfg.get('align_corners', True), aggregate_scale='unsqueeze_concat') # perform grouping diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index d59c239549..7c393f033c 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -257,14 +257,13 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): heatmaps_flipped = None pafs_flipped = None - # TODO: move `align_corners' to test_cfg aggregated_heatmaps = aggregate_stage_flip( heatmaps, heatmaps_flipped, index=-1, project2image=self.test_cfg['project2image'], size_projected=base_size, - align_corners=self.use_udp, + align_corners=self.test_cfg.get('align_corners', True), aggregate_stage='average', aggregate_flip='average') @@ -274,7 +273,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): index=-1, project2image=self.test_cfg['project2image'], size_projected=base_size, - align_corners=self.use_udp, + align_corners=self.test_cfg.get('align_corners', True), aggregate_stage='average', aggregate_flip='average') @@ -292,12 +291,12 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): aggregated_heatmaps = aggregate_scale( scale_heatmaps_list, aggregate_scale='average', - align_corners=self.use_udp) + align_corners=self.test_cfg.get('align_corners', True)) aggregated_pafs = aggregate_scale( scale_pafs_list, aggregate_scale='average', - align_corners=self.use_udp) + align_corners=self.test_cfg.get('align_corners', True)) # perform grouping grouped, scores = self.parser.parse(aggregated_heatmaps, From 10f132d320f237117779dff084dcfe85c63152ee Mon Sep 17 00:00:00 2001 From: jin-s13 Date: Thu, 24 Jun 2021 17:14:14 +0800 Subject: [PATCH 33/98] update refine --- mmpose/core/post_processing/group.py | 177 +++++++++++++++------------ 1 file changed, 98 insertions(+), 79 deletions(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 092fee6201..2c3eca0086 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -186,6 +186,85 @@ def top_k_value(feature_maps, M): return val_k, ind_k + @staticmethod + def refine(heatmap, tag, keypoints, use_udp=False): + """Given initial keypoint predictions, we identify missing joints. + + Note: + number of keypoints: K + heatmap height: H + heatmap width: W + dim of tags: L + If use flip testing, L=2; else L=1. + + Args: + heatmap: np.ndarray(K, H, W). + tag: np.ndarray(K, H, W) | np.ndarray(K, H, W, L) + keypoints: np.ndarray of size (K, 3 + L) + last dim is (x, y, score, tag). + use_udp: bool-unbiased data processing + + Returns: + np.ndarray: The refined keypoints. + """ + + K, H, W = heatmap.shape + if len(tag.shape) == 3: + tag = tag[..., None] + + tags = [] + for i in range(K): + if keypoints[i, 2] > 0: + # save tag value of detected keypoint + x, y = keypoints[i][:2].astype(int) + x = np.clip(x, 0, W - 1) + y = np.clip(y, 0, H - 1) + tags.append(tag[i, y, x]) + + # mean tag of current detected people + prev_tag = np.mean(tags, axis=0) + ans = [] + + for _heatmap, _tag in zip(heatmap, tag): + # distance of all tag values with mean tag of + # current detected people + distance_tag = (((_tag - + prev_tag[None, None, :])**2).sum(axis=2)**0.5) + norm_heatmap = _heatmap - np.round(distance_tag) + + # find maximum position + y, x = np.unravel_index(np.argmax(norm_heatmap), _heatmap.shape) + xx = x.copy() + yy = y.copy() + # detection score at maximum position + val = _heatmap[y, x] + if not use_udp: + # offset by 0.5 + x += 0.5 + y += 0.5 + + # add a quarter offset + if _heatmap[yy, min(W - 1, xx + 1)] > _heatmap[yy, max(0, xx - 1)]: + x += 0.25 + else: + x -= 0.25 + + if _heatmap[min(H - 1, yy + 1), xx] > _heatmap[max(0, yy - 1), xx]: + y += 0.25 + else: + y -= 0.25 + + ans.append((x, y, val)) + ans = np.array(ans) + + if ans is not None: + for i in range(K): + # add keypoint if it is not detected + if ans[i, 2] > 0 and keypoints[i, 2] == 0: + keypoints[i, :3] = ans[i, :3] + + return keypoints + @staticmethod def adjust(ans, heatmaps, use_udp=False): """Adjust the coordinates for better accuracy. @@ -327,85 +406,6 @@ def top_k(self, heatmaps, tags): return ans - @staticmethod - def refine(heatmap, tag, keypoints, use_udp=False): - """Given initial keypoint predictions, we identify missing joints. - - Note: - number of keypoints: K - heatmap height: H - heatmap width: W - dim of tags: L - If use flip testing, L=2; else L=1. - - Args: - heatmap: np.ndarray(K, H, W). - tag: np.ndarray(K, H, W) | np.ndarray(K, H, W, L) - keypoints: np.ndarray of size (K, 3 + L) - last dim is (x, y, score, tag). - use_udp: bool-unbiased data processing - - Returns: - np.ndarray: The refined keypoints. - """ - - K, H, W = heatmap.shape - if len(tag.shape) == 3: - tag = tag[..., None] - - tags = [] - for i in range(K): - if keypoints[i, 2] > 0: - # save tag value of detected keypoint - x, y = keypoints[i][:2].astype(int) - x = np.clip(x, 0, W - 1) - y = np.clip(y, 0, H - 1) - tags.append(tag[i, y, x]) - - # mean tag of current detected people - prev_tag = np.mean(tags, axis=0) - ans = [] - - for _heatmap, _tag in zip(heatmap, tag): - # distance of all tag values with mean tag of - # current detected people - distance_tag = (((_tag - - prev_tag[None, None, :])**2).sum(axis=2)**0.5) - norm_heatmap = _heatmap - np.round(distance_tag) - - # find maximum position - y, x = np.unravel_index(np.argmax(norm_heatmap), _heatmap.shape) - xx = x.copy() - yy = y.copy() - # detection score at maximum position - val = _heatmap[y, x] - if not use_udp: - # offset by 0.5 - x += 0.5 - y += 0.5 - - # add a quarter offset - if _heatmap[yy, min(W - 1, xx + 1)] > _heatmap[yy, max(0, xx - 1)]: - x += 0.25 - else: - x -= 0.25 - - if _heatmap[min(H - 1, yy + 1), xx] > _heatmap[max(0, yy - 1), xx]: - y += 0.25 - else: - y -= 0.25 - - ans.append((x, y, val)) - ans = np.array(ans) - - if ans is not None: - for i in range(K): - # add keypoint if it is not detected - if ans[i, 2] > 0 and keypoints[i, 2] == 0: - keypoints[i, :3] = ans[i, :3] - - return keypoints - def parse(self, heatmaps, tags, adjust=True, refine=True): """Group keypoints into poses given heatmap and tag. @@ -812,4 +812,23 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): else: ans = self.adjust(ans, heatmaps) + if refine: + ans = ans[0] + # for every detected person + for i in range(len(ans)): + heatmap_numpy = heatmaps[0].cpu().numpy() + _, image_width, image_height = heatmap_numpy.shape + y_coords = 2.0 * np.repeat( + np.arange(image_height)[:, None], image_width, + axis=1) / (image_height - 1.0) - 1.0 + x_coords = 2.0 * np.repeat( + np.arange(image_width)[None, :], image_height, + axis=0) / (image_width - 1.0) - 1.0 + coord_numpy = np.tile( + np.stack([x_coords, y_coords], axis=-1), + (self.params.num_joints, 1, 1, 1)) + ans[i] = self.refine( + heatmap_numpy, coord_numpy, ans[i], use_udp=self.use_udp) + ans = [ans] + return ans, scores From f4f2a927ad116508a4b930b3eba9e7f4f50e6595 Mon Sep 17 00:00:00 2001 From: jin-s13 Date: Thu, 24 Jun 2021 17:34:16 +0800 Subject: [PATCH 34/98] handle empty list --- mmpose/core/post_processing/group.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 2c3eca0086..441e3789aa 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -429,6 +429,9 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): """ ans = self.match(**self.top_k(heatmaps, tags)) + if len(ans) == 0: + return [], [] + if adjust: ans = self.adjust(ans, heatmaps, self.use_udp) @@ -803,6 +806,9 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): pafs_np = np.transpose(pafs.detach().cpu().numpy()[0], [1, 2, 0]) ans, scores = self.group_keypoints(all_keypoints_by_type, pafs_np) + if len(ans) == 0: + return [], [] + if adjust: if self.use_udp: for i in range(len(ans)): From 942f076521fd5c35671694cb7d710a53c5fa1956 Mon Sep 17 00:00:00 2001 From: jin-s13 Date: Thu, 24 Jun 2021 17:45:24 +0800 Subject: [PATCH 35/98] fix order --- mmpose/core/post_processing/group.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 441e3789aa..5c458e36ce 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -823,7 +823,7 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): # for every detected person for i in range(len(ans)): heatmap_numpy = heatmaps[0].cpu().numpy() - _, image_width, image_height = heatmap_numpy.shape + _, image_height, image_width = heatmap_numpy.shape y_coords = 2.0 * np.repeat( np.arange(image_height)[:, None], image_width, axis=1) / (image_height - 1.0) - 1.0 From c64dc427286ba9658a63f9ad6b0e05b0a25aec9b Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 25 Jun 2021 16:16:35 +0800 Subject: [PATCH 36/98] update pose filter --- mmpose/core/post_processing/group.py | 44 ++++++++++++++----- .../models/detectors/associative_embedding.py | 3 +- mmpose/models/detectors/paf.py | 3 +- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 5c458e36ce..d2ac173da9 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -277,7 +277,7 @@ def adjust(ans, heatmaps, use_udp=False): heatmap width: W Args: - ans (list(np.array([M,K,5]))): Keypoint predictions. + ans (list(np.array([M,K,3+]))): Keypoint predictions. heatmaps (torch.Tensor[NxKxHxW]): Heatmaps. """ @@ -310,6 +310,28 @@ def adjust(ans, heatmaps, use_udp=False): 0:2] = (x + 0.5, y + 0.5) return ans + def filter_pose(self, ans, kpt_num_thr=3, mean_score_thr=0.2): + """Filter out the poses with #keypoints < kpt_num_thr, and those with + keypoint score < mean_score_thr. + + Note: + number of person: M + number of keypoints: K + + Args: + filtered_ans (list(np.array([M,K,3+]))): Keypoint predictions. + """ + filtered_ans = [] + for i in range(len(ans[0])): + score = ans[0][i, :, 2] + if sum(score > 0) < kpt_num_thr or (score[score > 0].mean() < + mean_score_thr): + continue + filtered_ans.append(ans[0][i]) + filtered_ans = np.asarray(filtered_ans) + + return [filtered_ans] + @abstractmethod def parse(self, *args, **kwargs): """Group keypoints into poses.""" @@ -406,7 +428,7 @@ def top_k(self, heatmaps, tags): return ans - def parse(self, heatmaps, tags, adjust=True, refine=True): + def parse(self, heatmaps, tags, adjust=True, refine=True, filter=False): """Group keypoints into poses given heatmap and tag. Note: @@ -432,6 +454,9 @@ def parse(self, heatmaps, tags, adjust=True, refine=True): if len(ans) == 0: return [], [] + if filter: + ans = self.filter_pose(ans) + if adjust: ans = self.adjust(ans, heatmaps, self.use_udp) @@ -564,7 +589,7 @@ def group_keypoints(self, all_keypoints_by_type, pafs): pafs (np.ndarray[W, H, C]): part-affinity fields Returns: - - ans (list(np.array([M, K, 4]))): Keypoint predictions. + - ans (list(np.array([M, K, 3+]))): Keypoint predictions. - scores (list): Score of people. """ pose_entries = [] @@ -721,14 +746,6 @@ def group_keypoints(self, all_keypoints_by_type, pafs): pose_entries.append(pose_entry) - filtered_entries = [] - for i in range(len(pose_entries)): - if pose_entries[i][-1] < 3 or ( - pose_entries[i][-2] / pose_entries[i][-1] < 0.2): - continue - filtered_entries.append(pose_entries[i]) - pose_entries = np.asarray(filtered_entries) - ans = self.output_format(all_keypoints, pose_entries) scores = [person[-2] for person in pose_entries] @@ -777,7 +794,7 @@ def get_keypoints(self, heatmaps): return all_keypoints_by_type - def parse(self, heatmaps, pafs, adjust=True, refine=True): + def parse(self, heatmaps, pafs, adjust=True, refine=True, filter=False): """Group keypoints into poses given heatmap and paf. Note: @@ -809,6 +826,9 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True): if len(ans) == 0: return [], [] + if filter: + ans = self.filter_pose(ans) + if adjust: if self.use_udp: for i in range(len(ans)): diff --git a/mmpose/models/detectors/associative_embedding.py b/mmpose/models/detectors/associative_embedding.py index 59eaac57dc..078fe1cdc8 100644 --- a/mmpose/models/detectors/associative_embedding.py +++ b/mmpose/models/detectors/associative_embedding.py @@ -309,7 +309,8 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): grouped, scores = self.parser.parse(aggregated_heatmaps, aggregated_tags, self.test_cfg['adjust'], - self.test_cfg['refine']) + self.test_cfg['refine'], + self.test_cfg.get('filter', False)) preds = get_group_preds( grouped, diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 7c393f033c..33340fc266 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -302,7 +302,8 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): grouped, scores = self.parser.parse(aggregated_heatmaps, aggregated_pafs, self.test_cfg['adjust'], - self.test_cfg['refine']) + self.test_cfg['refine'], + self.test_cfg.get('filter', False)) preds = get_group_preds( grouped, From 03cc0897dbe0fc93427239aaa49748476ef06093 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sat, 26 Jun 2021 23:55:18 +0800 Subject: [PATCH 37/98] add openpose network --- mmpose/models/backbones/__init__.py | 3 +- mmpose/models/backbones/cpm.py | 40 +++- mmpose/models/backbones/openpose.py | 184 ++++++++++++++++++ tests/test_backbones/test_cpm.py | 18 ++ tests/test_backbones/test_openpose_network.py | 25 +++ 5 files changed, 259 insertions(+), 11 deletions(-) create mode 100644 mmpose/models/backbones/openpose.py create mode 100644 tests/test_backbones/test_openpose_network.py diff --git a/mmpose/models/backbones/__init__.py b/mmpose/models/backbones/__init__.py index eb3959d495..1bb273d9f4 100644 --- a/mmpose/models/backbones/__init__.py +++ b/mmpose/models/backbones/__init__.py @@ -5,6 +5,7 @@ from .mobilenet_v2 import MobileNetV2 from .mobilenet_v3 import MobileNetV3 from .mspn import MSPN +from .openpose import OpenPoseNetwork from .regnet import RegNet from .resnest import ResNeSt from .resnet import ResNet, ResNetV1d @@ -22,5 +23,5 @@ 'AlexNet', 'HourglassNet', 'HRNet', 'MobileNetV2', 'MobileNetV3', 'RegNet', 'ResNet', 'ResNetV1d', 'ResNeXt', 'SCNet', 'SEResNet', 'SEResNeXt', 'ShuffleNetV1', 'ShuffleNetV2', 'CPM', 'RSN', 'MSPN', 'ResNeSt', 'VGG', - 'TCN' + 'TCN', 'OpenPoseNetwork' ] diff --git a/mmpose/models/backbones/cpm.py b/mmpose/models/backbones/cpm.py index 3aa09523ed..f954ad85a6 100644 --- a/mmpose/models/backbones/cpm.py +++ b/mmpose/models/backbones/cpm.py @@ -18,18 +18,35 @@ class CpmBlock(nn.Module): Args: in_channels (int): Input channels of this block. - out_channels (int): Output channels of this block. + channels (list): Output channels of each conv module. + kernels (list): Kernel sizes of each conv module. """ - def __init__(self, in_channels, out_channels, norm_cfg=None): + def __init__(self, + in_channels, + channels=(128, 128, 128), + kernels=(11, 11, 11), + norm_cfg=None): super().__init__() - self.model = nn.Sequential( - ConvModule( - in_channels, out_channels, 11, padding=5, norm_cfg=norm_cfg), - ConvModule( - out_channels, out_channels, 11, padding=5, norm_cfg=norm_cfg), + + assert len(channels) == len(kernels) + layers = [] + layers.append( ConvModule( - out_channels, out_channels, 11, padding=5, norm_cfg=norm_cfg)) + in_channels, + channels[0], + kernels[0], + padding=(kernels[0] - 1) // 2, + norm_cfg=norm_cfg)) + for i in range(1, len(channels)): + layers.append( + ConvModule( + channels[i - 1], + channels[i], + kernels[i], + padding=(kernels[i] - 1) // 2, + norm_cfg=norm_cfg)) + self.model = nn.Sequential(*layers) def forward(self, x): """Model forward function.""" @@ -107,8 +124,11 @@ def __init__(self, nn.MaxPool2d(kernel_size=3, stride=2, padding=1)) self.cpm_stages = nn.ModuleList([ - CpmBlock(middle_channels + out_channels, feat_channels, norm_cfg) - for _ in range(num_stages - 1) + CpmBlock( + middle_channels + out_channels, + channels=[feat_channels, feat_channels, feat_channels], + kernels=[11, 11, 11], + norm_cfg=norm_cfg) for _ in range(num_stages - 1) ]) self.middle_conv = nn.ModuleList([ diff --git a/mmpose/models/backbones/openpose.py b/mmpose/models/backbones/openpose.py new file mode 100644 index 0000000000..a8ab66c545 --- /dev/null +++ b/mmpose/models/backbones/openpose.py @@ -0,0 +1,184 @@ +import copy + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, constant_init, normal_init +from torch.nn.modules.batchnorm import _BatchNorm + +from mmpose.utils import get_root_logger +from ..builder import BACKBONES +from .base_backbone import BaseBackbone +from .cpm import CpmBlock +from .utils import load_checkpoint + + +@BACKBONES.register_module() +class OpenPoseNetwork(BaseBackbone): + """OpenPose backbone Network. + + Realtime Multi-Person 2D Pose Estimation using Part Affinity Fields. + More details can be found in the `paper + `__ . + + Based on the officially released model + 'https://github.com/CMU-Perceptual-Computing-Lab/openpose/ + blob/master/models/pose/coco/pose_deploy_linevec.prototxt' + + Args: + in_channels (int): The input channels. + out_channels_heatmap (int): The output channels for heatmap. + out_channels_heatmap (int): The output channels for paf. + feat_channels (int): Feature channel of each stage. + num_stages (int): Number of stages. + norm_cfg (dict): Dictionary to construct and config norm layer. + + Example: + >>> from mmpose.models import OpenPoseNetwork + >>> import torch + >>> self = OpenPoseNetwork(3, 19, 38) + >>> self.eval() + >>> inputs = torch.rand(1, 3, 368, 368) + >>> level_outputs = self.forward(inputs) + >>> for level_output in level_outputs: + ... print(tuple(level_output.shape)) + (1, 19, 46, 46) + (1, 19, 46, 46) + (1, 19, 46, 46) + (1, 19, 46, 46) + (1, 19, 46, 46) + (1, 19, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + """ + + def __init__(self, + in_channels, + out_channels_heatmap=19, + out_channels_paf=38, + feat_channels=128, + num_stages=6, + norm_cfg=dict(type='BN', requires_grad=True)): + # Protect mutable default arguments + norm_cfg = copy.deepcopy(norm_cfg) + super().__init__() + + assert in_channels == 3 + + self.num_stages = num_stages + assert self.num_stages >= 1 + + self.stem = nn.Sequential( + ConvModule(in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, feat_channels, 3, padding=1, norm_cfg=norm_cfg)) + + # stage 0 + self.heatmap_stages = nn.ModuleList([ + CpmBlock(feat_channels, + [feat_channels, feat_channels, feat_channels, 512], + [3, 3, 3, 1], norm_cfg) + ]) + + # stage 1 to n-1 + for _ in range(1, self.num_stages): + self.heatmap_stages.append( + CpmBlock( + feat_channels + out_channels_heatmap + out_channels_paf, [ + feat_channels, feat_channels, feat_channels, + feat_channels, feat_channels, feat_channels + ], [7, 7, 7, 7, 7, 1], norm_cfg)) + + # stage 0 + self.paf_stages = nn.ModuleList([ + CpmBlock(feat_channels, + [feat_channels, feat_channels, feat_channels, 512], + [3, 3, 3, 1], norm_cfg) + ]) + + # stage 1 to n-1 + for _ in range(1, self.num_stages): + self.paf_stages.append( + CpmBlock( + feat_channels + out_channels_heatmap + out_channels_paf, [ + feat_channels, feat_channels, feat_channels, + feat_channels, feat_channels, feat_channels + ], [7, 7, 7, 7, 7, 1], norm_cfg)) + + # stage 0 + self.heatmap_out_convs = nn.ModuleList( + [ConvModule(512, out_channels_heatmap, 1, act_cfg=None)]) + # stage 1 to n-1 + for _ in range(1, self.num_stages): + self.heatmap_out_convs.append( + ConvModule( + feat_channels, out_channels_heatmap, 1, act_cfg=None)) + + # stage 0 + self.paf_out_convs = nn.ModuleList( + [ConvModule(512, out_channels_paf, 1, act_cfg=None)]) + # stage 1 to n-1 + for _ in range(1, self.num_stages): + self.paf_out_convs.append( + ConvModule(feat_channels, out_channels_paf, 1, act_cfg=None)) + + def init_weights(self, pretrained=None): + """Initialize the weights in backbone. + + Args: + pretrained (str, optional): Path to pre-trained weights. + Defaults to None. + """ + if isinstance(pretrained, str): + logger = get_root_logger() + load_checkpoint(self, pretrained, strict=False, logger=logger) + elif pretrained is None: + for m in self.modules(): + if isinstance(m, nn.Conv2d): + normal_init(m, std=0.001) + elif isinstance(m, (_BatchNorm, nn.GroupNorm)): + constant_init(m, 1) + else: + raise TypeError('pretrained must be a str or None') + + def forward(self, x): + """Model forward function.""" + stem_feat = self.stem(x) + out_feats = [] + out_feats.append(stem_feat) + + heatmap_outputs = [] + paf_outputs = [] + + for ind in range(self.num_stages): + heatmap_stage = self.heatmap_stages[ind] + paf_stage = self.paf_stages[ind] + + heatmap_out_conv = self.heatmap_out_convs[ind] + paf_out_conv = self.paf_out_convs[ind] + + heatmap_output = heatmap_out_conv(heatmap_stage(out_feats[-1])) + heatmap_outputs.append(heatmap_output) + paf_output = paf_out_conv(paf_stage(out_feats[-1])) + paf_outputs.append(paf_output) + + out_feat = torch.cat([stem_feat, heatmap_output, paf_output], 1) + + out_feats.append(out_feat) + + return [*heatmap_outputs, *paf_outputs] diff --git a/tests/test_backbones/test_cpm.py b/tests/test_backbones/test_cpm.py index 3a9481539a..dc6dc45dea 100644 --- a/tests/test_backbones/test_cpm.py +++ b/tests/test_backbones/test_cpm.py @@ -2,6 +2,24 @@ import torch from mmpose.models import CPM +from mmpose.models.backbones.cpm import CpmBlock + + +def test_cpm_block(): + with pytest.raises(AssertionError): + # len(channels) == len(kernels) + CpmBlock( + 3, channels=[3, 3, 3], kernels=[ + 1, + ]) + + # Test CPM Block + model = CpmBlock(3, channels=[3, 3, 3], kernels=[1, 1, 1]) + model.train() + + imgs = torch.randn(1, 3, 10, 10) + feat = model(imgs) + assert feat.shape == torch.Size([1, 3, 10, 10]) def test_cpm_backbone(): diff --git a/tests/test_backbones/test_openpose_network.py b/tests/test_backbones/test_openpose_network.py new file mode 100644 index 0000000000..0ce8cfee8b --- /dev/null +++ b/tests/test_backbones/test_openpose_network.py @@ -0,0 +1,25 @@ +import pytest +import torch + +from mmpose.models import OpenPoseNetwork + + +def test_openpose_network_backbone(): + with pytest.raises(AssertionError): + # OpenPoseNetwork's num_stacks should larger than 0 + OpenPoseNetwork(in_channels=3, num_stages=-1) + + with pytest.raises(AssertionError): + # OpenPoseNetwork's in_channels should be 3 + OpenPoseNetwork(in_channels=2) + + # Test OpenPoseNetwork + model = OpenPoseNetwork(in_channels=3) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 368, 368) + feat = model(imgs) + assert len(feat) == 12 + assert feat[0].shape == torch.Size([1, 19, 46, 46]) + assert feat[-1].shape == torch.Size([1, 38, 46, 46]) From 11250215e62aed87674f5fdf00bd0803caf5d4a8 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sun, 27 Jun 2021 20:58:39 +0800 Subject: [PATCH 38/98] add openpose_v1 and openpose_v2 model --- mmpose/models/backbones/__init__.py | 5 +- mmpose/models/backbones/cpm.py | 17 +- .../backbones/{openpose.py => openpose_v1.py} | 92 +++--- mmpose/models/backbones/openpose_v2.py | 276 ++++++++++++++++++ ...penpose_network.py => test_openpose_v1.py} | 10 +- tests/test_backbones/test_openpose_v2.py | 35 +++ 6 files changed, 373 insertions(+), 62 deletions(-) rename mmpose/models/backbones/{openpose.py => openpose_v1.py} (66%) create mode 100644 mmpose/models/backbones/openpose_v2.py rename tests/test_backbones/{test_openpose_network.py => test_openpose_v1.py} (68%) create mode 100644 tests/test_backbones/test_openpose_v2.py diff --git a/mmpose/models/backbones/__init__.py b/mmpose/models/backbones/__init__.py index 1bb273d9f4..c3cf3cd6b8 100644 --- a/mmpose/models/backbones/__init__.py +++ b/mmpose/models/backbones/__init__.py @@ -5,7 +5,8 @@ from .mobilenet_v2 import MobileNetV2 from .mobilenet_v3 import MobileNetV3 from .mspn import MSPN -from .openpose import OpenPoseNetwork +from .openpose_v1 import OpenPoseNetworkV1 +from .openpose_v2 import OpenPoseNetworkV2 from .regnet import RegNet from .resnest import ResNeSt from .resnet import ResNet, ResNetV1d @@ -23,5 +24,5 @@ 'AlexNet', 'HourglassNet', 'HRNet', 'MobileNetV2', 'MobileNetV3', 'RegNet', 'ResNet', 'ResNetV1d', 'ResNeXt', 'SCNet', 'SEResNet', 'SEResNeXt', 'ShuffleNetV1', 'ShuffleNetV2', 'CPM', 'RSN', 'MSPN', 'ResNeSt', 'VGG', - 'TCN', 'OpenPoseNetwork' + 'TCN', 'OpenPoseNetworkV1', 'OpenPoseNetworkV2' ] diff --git a/mmpose/models/backbones/cpm.py b/mmpose/models/backbones/cpm.py index f954ad85a6..1659589bac 100644 --- a/mmpose/models/backbones/cpm.py +++ b/mmpose/models/backbones/cpm.py @@ -14,8 +14,6 @@ class CpmBlock(nn.Module): """CpmBlock for Convolutional Pose Machine. - Generate module recursively and use BasicBlock as the base unit. - Args: in_channels (int): Input channels of this block. channels (list): Output channels of each conv module. @@ -31,17 +29,14 @@ def __init__(self, assert len(channels) == len(kernels) layers = [] - layers.append( - ConvModule( - in_channels, - channels[0], - kernels[0], - padding=(kernels[0] - 1) // 2, - norm_cfg=norm_cfg)) - for i in range(1, len(channels)): + for i in range(len(channels)): + if i == 0: + input_channels = in_channels + else: + input_channels = channels[i - 1] layers.append( ConvModule( - channels[i - 1], + input_channels, channels[i], kernels[i], padding=(kernels[i] - 1) // 2, diff --git a/mmpose/models/backbones/openpose.py b/mmpose/models/backbones/openpose_v1.py similarity index 66% rename from mmpose/models/backbones/openpose.py rename to mmpose/models/backbones/openpose_v1.py index a8ab66c545..2732010486 100644 --- a/mmpose/models/backbones/openpose.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -13,7 +13,7 @@ @BACKBONES.register_module() -class OpenPoseNetwork(BaseBackbone): +class OpenPoseNetworkV1(BaseBackbone): """OpenPose backbone Network. Realtime Multi-Person 2D Pose Estimation using Part Affinity Fields. @@ -26,14 +26,16 @@ class OpenPoseNetwork(BaseBackbone): Args: in_channels (int): The input channels. - out_channels_heatmap (int): The output channels for heatmap. - out_channels_heatmap (int): The output channels for paf. - feat_channels (int): Feature channel of each stage. + out_channels_cm (int): The output channels for CM ( + confidence map, or heatmap). + out_channels_paf (int): The output channels for PAF ( + part-affinity field). + stem_feat_channels (int): Feature channel of the stem network. num_stages (int): Number of stages. norm_cfg (dict): Dictionary to construct and config norm layer. Example: - >>> from mmpose.models import OpenPoseNetwork + >>> from mmpose.models import OpenPoseNetworkV1 >>> import torch >>> self = OpenPoseNetwork(3, 19, 38) >>> self.eval() @@ -57,9 +59,9 @@ class OpenPoseNetwork(BaseBackbone): def __init__(self, in_channels, - out_channels_heatmap=19, + out_channels_cm=19, out_channels_paf=38, - feat_channels=128, + stem_feat_channels=128, num_stages=6, norm_cfg=dict(type='BN', requires_grad=True)): # Protect mutable default arguments @@ -86,56 +88,58 @@ def __init__(self, ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, feat_channels, 3, padding=1, norm_cfg=norm_cfg)) + ConvModule( + 256, stem_feat_channels, 3, padding=1, norm_cfg=norm_cfg)) # stage 0 - self.heatmap_stages = nn.ModuleList([ - CpmBlock(feat_channels, - [feat_channels, feat_channels, feat_channels, 512], - [3, 3, 3, 1], norm_cfg) + self.cm_stages = nn.ModuleList([ + CpmBlock(stem_feat_channels, [ + stem_feat_channels, stem_feat_channels, stem_feat_channels, 512 + ], [3, 3, 3, 1], norm_cfg) ]) # stage 1 to n-1 for _ in range(1, self.num_stages): - self.heatmap_stages.append( + self.cm_stages.append( CpmBlock( - feat_channels + out_channels_heatmap + out_channels_paf, [ - feat_channels, feat_channels, feat_channels, - feat_channels, feat_channels, feat_channels + stem_feat_channels + out_channels_cm + out_channels_paf, [ + stem_feat_channels, stem_feat_channels, + stem_feat_channels, stem_feat_channels, + stem_feat_channels, stem_feat_channels ], [7, 7, 7, 7, 7, 1], norm_cfg)) # stage 0 self.paf_stages = nn.ModuleList([ - CpmBlock(feat_channels, - [feat_channels, feat_channels, feat_channels, 512], - [3, 3, 3, 1], norm_cfg) + CpmBlock(stem_feat_channels, [ + stem_feat_channels, stem_feat_channels, stem_feat_channels, 512 + ], [3, 3, 3, 1], norm_cfg) ]) # stage 1 to n-1 for _ in range(1, self.num_stages): self.paf_stages.append( CpmBlock( - feat_channels + out_channels_heatmap + out_channels_paf, [ - feat_channels, feat_channels, feat_channels, - feat_channels, feat_channels, feat_channels + stem_feat_channels + out_channels_cm + out_channels_paf, [ + stem_feat_channels, stem_feat_channels, + stem_feat_channels, stem_feat_channels, + stem_feat_channels, stem_feat_channels ], [7, 7, 7, 7, 7, 1], norm_cfg)) - # stage 0 - self.heatmap_out_convs = nn.ModuleList( - [ConvModule(512, out_channels_heatmap, 1, act_cfg=None)]) - # stage 1 to n-1 - for _ in range(1, self.num_stages): - self.heatmap_out_convs.append( - ConvModule( - feat_channels, out_channels_heatmap, 1, act_cfg=None)) - - # stage 0 - self.paf_out_convs = nn.ModuleList( - [ConvModule(512, out_channels_paf, 1, act_cfg=None)]) - # stage 1 to n-1 - for _ in range(1, self.num_stages): + for i in range(self.num_stages): + if i == 0: + input_channels = 512 + else: + input_channels = stem_feat_channels + self.cm_out_convs.append( + ConvModule(input_channels, out_channels_cm, 1, act_cfg=None)) + + for i in range(1, self.num_stages): + if i == 0: + input_channels = 512 + else: + input_channels = stem_feat_channels self.paf_out_convs.append( - ConvModule(feat_channels, out_channels_paf, 1, act_cfg=None)) + ConvModule(input_channels, out_channels_paf, 1, act_cfg=None)) def init_weights(self, pretrained=None): """Initialize the weights in backbone. @@ -162,23 +166,23 @@ def forward(self, x): out_feats = [] out_feats.append(stem_feat) - heatmap_outputs = [] + cm_outputs = [] paf_outputs = [] for ind in range(self.num_stages): - heatmap_stage = self.heatmap_stages[ind] + cm_stage = self.cm_stages[ind] paf_stage = self.paf_stages[ind] - heatmap_out_conv = self.heatmap_out_convs[ind] + cm_out_conv = self.cm_out_convs[ind] paf_out_conv = self.paf_out_convs[ind] - heatmap_output = heatmap_out_conv(heatmap_stage(out_feats[-1])) - heatmap_outputs.append(heatmap_output) + cm_output = cm_out_conv(cm_stage(out_feats[-1])) + cm_outputs.append(cm_output) paf_output = paf_out_conv(paf_stage(out_feats[-1])) paf_outputs.append(paf_output) - out_feat = torch.cat([stem_feat, heatmap_output, paf_output], 1) + out_feat = torch.cat([stem_feat, cm_output, paf_output], 1) out_feats.append(out_feat) - return [*heatmap_outputs, *paf_outputs] + return [*cm_outputs, *paf_outputs] diff --git a/mmpose/models/backbones/openpose_v2.py b/mmpose/models/backbones/openpose_v2.py new file mode 100644 index 0000000000..e1c62b78f3 --- /dev/null +++ b/mmpose/models/backbones/openpose_v2.py @@ -0,0 +1,276 @@ +import copy + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, constant_init, normal_init +from torch.nn.modules.batchnorm import _BatchNorm + +from mmpose.utils import get_root_logger +from ..builder import BACKBONES +from .base_backbone import BaseBackbone +from .utils import load_checkpoint + + +class MconvBlock(nn.Module): + """MconvBlock for replacing convolutions of 7x7 kernel. + + Args: + in_channels (int): Input channels of this block. + channels (list): Output channels of each conv module. + kernels (list): Kernel sizes of each conv module. + """ + + def __init__(self, + in_channels, + channels=(96, 96, 96), + kernels=(3, 3, 3), + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU')): + super().__init__() + + assert len(channels) == len(kernels) + + self.num_layers = len(channels) + + self.model = nn.ModuleList() + for i in range(self.num_layers): + if i == 0: + input_channels = in_channels + else: + input_channels = channels[i - 1] + self.model.append( + ConvModule( + input_channels, + channels[i], + kernels[i], + padding=(kernels[i] - 1) // 2, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + def forward(self, x): + """Model forward function.""" + feat = [] + feat.append(x) + for i in range(self.num_layers): + feat.append(self.model[i](feat[-1])) + out = torch.cat([*feat[1:]], 1) + return out + + +class MconvStage(nn.Module): + """MconvStage. + + Args: + in_channels (int): Input channels of this block. + channels (list): Output channels of each conv module. + kernels (list): Kernel sizes of each conv module. + """ + + def __init__(self, + in_channels, + out_channels, + num_blocks=5, + block_channels=(96, 96, 96), + block_kernels=(3, 3, 3), + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU')): + super().__init__() + + layers = [] + for i in range(num_blocks): + + if i == 0: + input_channels = in_channels + else: + input_channels = sum(block_channels) + + layers.append( + MconvBlock( + input_channels, + channels=block_channels, + kernels=block_kernels, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU'))) + + layers.append( + ConvModule( + sum(block_channels), + out_channels, + kernel_size=1, + padding=0, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + self.model = nn.Sequential(*layers) + + def forward(self, x): + """Model forward function.""" + out = self.model(x) + return out + + +@BACKBONES.register_module() +class OpenPoseNetworkV2(BaseBackbone): + """OpenPose backbone Network. + + Open{P}ose: realtime multi-person 2{D} pose estimation + using {P}art {A}ffinity {F}ields. + More details can be found in the `paper + `__ . + + Based on the officially released model + 'https://raw.githubusercontent.com/CMU-Perceptual-Computing-Lab/' + 'openpose/master/models/pose/body_25/pose_deploy.prototxt' + + Args: + in_channels (int): The input channels. + out_channels_cm (int): The output channels for CM ( + confidence map, or heatmap). + out_channels_paf (int): The output channels for PAF ( + part-affinity field). + stem_feat_channels (int): Feature channel of the stem network. + num_stages (int): Number of stages. + norm_cfg (dict): Dictionary to construct and config norm layer. + + Example: + >>> from mmpose.models import OpenPoseNetworkV2 + >>> import torch + >>> self = OpenPoseNetworkV2(3) + >>> self.eval() + >>> inputs = torch.rand(1, 3, 368, 368) + >>> level_outputs = self.forward(inputs) + >>> for level_output in level_outputs: + ... print(tuple(level_output.shape)) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + (1, 19, 46, 46) + """ + + def __init__(self, + in_channels, + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU')): + # Protect mutable default arguments + norm_cfg = copy.deepcopy(norm_cfg) + super().__init__() + + assert in_channels == 3 + assert num_stages == len(stage_types) + + self.num_stages = num_stages + assert self.num_stages >= 1 + + self.stem = nn.Sequential( + ConvModule(in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + nn.MaxPool2d(kernel_size=2, stride=2, padding=0), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule( + 512, 512, 3, padding=1, norm_cfg=norm_cfg, act_cfg=act_cfg), + ConvModule( + 512, 256, 3, padding=1, norm_cfg=norm_cfg, act_cfg=act_cfg), + ConvModule( + 256, + stem_feat_channels, + 3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg)) + + self.stages = nn.ModuleList() + self.out_convs = nn.ModuleList() + + for i, stage_type in enumerate(stage_types): + if i == 0: + input_channels = stem_feat_channels + else: + if stage_types[i - 1] == 'CM': + input_channels = stem_feat_channels + out_channels_cm + else: + # stage_types[i-1] == 'PAF': + input_channels = stem_feat_channels + out_channels_paf + + if stage_type.upper() == 'CM': + self.stages.append( + MconvStage( + input_channels, + 256, + num_blocks=num_blocks, + block_channels=[block_channels] * num_blocks, + block_kernels=[3] * num_blocks, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU'))) + self.out_convs.append( + ConvModule(256, out_channels_cm, 1, act_cfg=None)) + + elif stage_type.upper() == 'PAF': + self.stages.append( + MconvStage( + input_channels, + 256, + num_blocks=num_blocks, + block_channels=[block_channels] * num_blocks, + block_kernels=[3] * num_blocks, + norm_cfg=dict(type='BN', requires_grad=True), + act_cfg=dict(type='PReLU'))) + self.out_convs.append( + ConvModule(256, out_channels_paf, 1, act_cfg=None)) + + else: + raise ValueError("stage_type should be either 'CM' or 'PAF'.") + + def init_weights(self, pretrained=None): + """Initialize the weights in backbone. + + Args: + pretrained (str, optional): Path to pre-trained weights. + Defaults to None. + """ + if isinstance(pretrained, str): + logger = get_root_logger() + load_checkpoint(self, pretrained, strict=False, logger=logger) + elif pretrained is None: + for m in self.modules(): + if isinstance(m, nn.Conv2d): + normal_init(m, std=0.001) + elif isinstance(m, (_BatchNorm, nn.GroupNorm)): + constant_init(m, 1) + else: + raise TypeError('pretrained must be a str or None') + + def forward(self, x): + """Model forward function.""" + stem_feat = self.stem(x) + out_feats = [] + out_feats.append(stem_feat) + + outputs = [] + + for ind in range(self.num_stages): + single_stage = self.stages[ind] + single_out_conv = self.out_convs[ind] + output = single_out_conv(single_stage(out_feats[-1])) + outputs.append(output) + + out_feat = torch.cat([stem_feat, output], 1) + out_feats.append(out_feat) + + return [*outputs] diff --git a/tests/test_backbones/test_openpose_network.py b/tests/test_backbones/test_openpose_v1.py similarity index 68% rename from tests/test_backbones/test_openpose_network.py rename to tests/test_backbones/test_openpose_v1.py index 0ce8cfee8b..1599fd58d4 100644 --- a/tests/test_backbones/test_openpose_network.py +++ b/tests/test_backbones/test_openpose_v1.py @@ -1,20 +1,20 @@ import pytest import torch -from mmpose.models import OpenPoseNetwork +from mmpose.models import OpenPoseNetworkV1 -def test_openpose_network_backbone(): +def test_openpose_network_v1_backbone(): with pytest.raises(AssertionError): # OpenPoseNetwork's num_stacks should larger than 0 - OpenPoseNetwork(in_channels=3, num_stages=-1) + OpenPoseNetworkV1(in_channels=3, num_stages=-1) with pytest.raises(AssertionError): # OpenPoseNetwork's in_channels should be 3 - OpenPoseNetwork(in_channels=2) + OpenPoseNetworkV1(in_channels=2) # Test OpenPoseNetwork - model = OpenPoseNetwork(in_channels=3) + model = OpenPoseNetworkV1(in_channels=3) model.init_weights() model.train() diff --git a/tests/test_backbones/test_openpose_v2.py b/tests/test_backbones/test_openpose_v2.py new file mode 100644 index 0000000000..c0981e82bd --- /dev/null +++ b/tests/test_backbones/test_openpose_v2.py @@ -0,0 +1,35 @@ +import pytest +import torch + +from mmpose.models import OpenPoseNetworkV2 + + +def test_openpose_network_v2_backbone(): + with pytest.raises(AssertionError): + # OpenPoseNetwork's num_stacks should larger than 0 + OpenPoseNetworkV2(in_channels=3, num_stages=-1) + + with pytest.raises(AssertionError): + # OpenPoseNetwork's in_channels should be 3 + OpenPoseNetworkV2(in_channels=2) + + with pytest.raises(AssertionError): + # len(stage_types) == num_stages + OpenPoseNetworkV2( + in_channels=3, num_stages=3, stage_types=('PAF', 'CM')) + + with pytest.raises(ValueError): + # stage_type should be either 'CM' or 'PAF'. + OpenPoseNetworkV2( + in_channels=3, num_stages=2, stage_types=('PAF', 'CC')) + + # Test OpenPoseNetwork + model = OpenPoseNetworkV2(in_channels=3) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 368, 368) + feat = model(imgs) + assert len(feat) == 6 + assert feat[0].shape == torch.Size([1, 38, 46, 46]) + assert feat[-1].shape == torch.Size([1, 19, 46, 46]) From 6d74e22562d15f77421db31c64bff15a15536bfd Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sun, 27 Jun 2021 21:14:26 +0800 Subject: [PATCH 39/98] fix openpose v1 --- mmpose/models/backbones/openpose_v1.py | 24 ++++++++---------------- 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index 2732010486..6edb10d74a 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -97,6 +97,11 @@ def __init__(self, stem_feat_channels, stem_feat_channels, stem_feat_channels, 512 ], [3, 3, 3, 1], norm_cfg) ]) + self.paf_stages = nn.ModuleList([ + CpmBlock(stem_feat_channels, [ + stem_feat_channels, stem_feat_channels, stem_feat_channels, 512 + ], [3, 3, 3, 1], norm_cfg) + ]) # stage 1 to n-1 for _ in range(1, self.num_stages): @@ -107,16 +112,6 @@ def __init__(self, stem_feat_channels, stem_feat_channels, stem_feat_channels, stem_feat_channels ], [7, 7, 7, 7, 7, 1], norm_cfg)) - - # stage 0 - self.paf_stages = nn.ModuleList([ - CpmBlock(stem_feat_channels, [ - stem_feat_channels, stem_feat_channels, stem_feat_channels, 512 - ], [3, 3, 3, 1], norm_cfg) - ]) - - # stage 1 to n-1 - for _ in range(1, self.num_stages): self.paf_stages.append( CpmBlock( stem_feat_channels + out_channels_cm + out_channels_paf, [ @@ -125,6 +120,9 @@ def __init__(self, stem_feat_channels, stem_feat_channels ], [7, 7, 7, 7, 7, 1], norm_cfg)) + self.cm_out_convs = nn.ModuleList() + self.paf_out_convs = nn.ModuleList() + for i in range(self.num_stages): if i == 0: input_channels = 512 @@ -132,12 +130,6 @@ def __init__(self, input_channels = stem_feat_channels self.cm_out_convs.append( ConvModule(input_channels, out_channels_cm, 1, act_cfg=None)) - - for i in range(1, self.num_stages): - if i == 0: - input_channels = 512 - else: - input_channels = stem_feat_channels self.paf_out_convs.append( ConvModule(input_channels, out_channels_paf, 1, act_cfg=None)) From 38197a225269ee67a9fc238840ffd9488e18e0e7 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sun, 27 Jun 2021 21:27:41 +0800 Subject: [PATCH 40/98] rename stem to features for pre-trained vgg model loading --- mmpose/models/backbones/openpose_v1.py | 4 ++-- mmpose/models/backbones/openpose_v2.py | 4 ++-- tests/test_backbones/test_openpose_v2.py | 3 +++ 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index 6edb10d74a..af06e1235b 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -73,7 +73,7 @@ def __init__(self, self.num_stages = num_stages assert self.num_stages >= 1 - self.stem = nn.Sequential( + self.features = nn.Sequential( ConvModule(in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), @@ -154,7 +154,7 @@ def init_weights(self, pretrained=None): def forward(self, x): """Model forward function.""" - stem_feat = self.stem(x) + stem_feat = self.features(x) out_feats = [] out_feats.append(stem_feat) diff --git a/mmpose/models/backbones/openpose_v2.py b/mmpose/models/backbones/openpose_v2.py index e1c62b78f3..7f09add08f 100644 --- a/mmpose/models/backbones/openpose_v2.py +++ b/mmpose/models/backbones/openpose_v2.py @@ -170,7 +170,7 @@ def __init__(self, self.num_stages = num_stages assert self.num_stages >= 1 - self.stem = nn.Sequential( + self.features = nn.Sequential( ConvModule(in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), @@ -258,7 +258,7 @@ def init_weights(self, pretrained=None): def forward(self, x): """Model forward function.""" - stem_feat = self.stem(x) + stem_feat = self.features(x) out_feats = [] out_feats.append(stem_feat) diff --git a/tests/test_backbones/test_openpose_v2.py b/tests/test_backbones/test_openpose_v2.py index c0981e82bd..0af920acb2 100644 --- a/tests/test_backbones/test_openpose_v2.py +++ b/tests/test_backbones/test_openpose_v2.py @@ -33,3 +33,6 @@ def test_openpose_network_v2_backbone(): assert len(feat) == 6 assert feat[0].shape == torch.Size([1, 38, 46, 46]) assert feat[-1].shape == torch.Size([1, 19, 46, 46]) + + +test_openpose_network_v2_backbone() From 450af69485363ffc606e815e337cc1ba418638f5 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sun, 27 Jun 2021 23:10:38 +0800 Subject: [PATCH 41/98] add openpose v1 v2 configs --- .../coco/openpose_v1_coco_368x368.py | 179 +++++++++++++++++ .../coco/openpose_v2_coco_368x368.py | 182 ++++++++++++++++++ mmpose/models/heads/paf_head.py | 2 +- 3 files changed, 362 insertions(+), 1 deletion(-) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py new file mode 100644 index 0000000000..156b3b1c55 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py @@ -0,0 +1,179 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV1', + in_channels=3, + out_channels_cm=17, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=17, + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 6, + paf_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=38, + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 6, + heatmap_index=[0, 1, 2, 3, 4, 5], + paf_index=[6, 7, 8, 9, 10, 11], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 6 + [1] * 6, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py new file mode 100644 index 0000000000..3bd5ab8ea3 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py @@ -0,0 +1,182 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + out_channels_cm=17, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=17, + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=38, + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 5, + heatmap_index=[5], + paf_index=[0, 1, 2, 3, 4], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 5, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/mmpose/models/heads/paf_head.py b/mmpose/models/heads/paf_head.py index 563b770a78..f652df9729 100644 --- a/mmpose/models/heads/paf_head.py +++ b/mmpose/models/heads/paf_head.py @@ -72,7 +72,7 @@ def get_loss(self, outputs, targets, masks): paf_outputs = outputs['pafs'] paf_targets = targets[len(self.heatmap_heads_list):] - paf_masks = masks[:len(self.heatmap_heads_list)] + paf_masks = masks[len(self.heatmap_heads_list):] for idx, head in enumerate(self.paf_heads_list): paf_losses = head.get_loss(paf_outputs[idx], paf_targets[idx], paf_masks[idx]) From 8c0fadececf7db75b5a93f1db0a1359d0eb7d998 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 28 Jun 2021 14:24:37 +0800 Subject: [PATCH 42/98] add with_bg --- .../coco/hrnet_w32_coco_512x512.py | 9 +- .../coco/openpose_v1_coco_368x368.py | 13 +- .../coco/openpose_v1_coco_368x368_withbg.py | 181 +++++++++++++++++ .../coco/openpose_v2_coco_368x368.py | 13 +- .../coco/openpose_v2_coco_368x368_withbg.py | 184 ++++++++++++++++++ .../coco/res50_coco_512x512.py | 9 +- .../datasets/pipelines/bottom_up_transform.py | 30 ++- mmpose/models/detectors/paf.py | 13 +- mmpose/models/heads/deconv_head.py | 4 +- 9 files changed, 429 insertions(+), 27 deletions(-) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index 0828c5a393..44b2f63f5a 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -149,7 +149,12 @@ dict( type='MultitaskGatherTarget', pipeline_list=[ - [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], [dict( type='BottomUpGeneratePAFTarget', limb_width=1, @@ -177,7 +182,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton' + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py index 156b3b1c55..8267399105 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py @@ -63,8 +63,6 @@ heatmap_heads_cfg=[ dict( type='DeconvHead', - in_channels=32, - out_channels=17, num_deconv_layers=0, extra=dict(final_conv_kernel=0), loss_keypoint=dict(type='MaskedMSELoss', )), @@ -72,8 +70,6 @@ paf_heads_cfg=[ dict( type='DeconvHead', - in_channels=32, - out_channels=38, num_deconv_layers=0, extra=dict(final_conv_kernel=0), loss_keypoint=dict(type='MaskedMSELoss', )), @@ -120,7 +116,12 @@ dict( type='MultitaskGatherTarget', pipeline_list=[ - [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], [dict( type='BottomUpGeneratePAFTarget', limb_width=1, @@ -148,7 +149,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton' + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py new file mode 100644 index 0000000000..3bbaa9bdf1 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py @@ -0,0 +1,181 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV1', + in_channels=3, + # additional channel for bg + out_channels_cm=17 + 1, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 6, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 6, + heatmap_index=[0, 1, 2, 3, 4, 5], + paf_index=[6, 7, 8, 9, 10, 11], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=True) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 6 + [1] * 6, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py index 3bd5ab8ea3..5188013606 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py @@ -66,8 +66,6 @@ heatmap_heads_cfg=[ dict( type='DeconvHead', - in_channels=32, - out_channels=17, num_deconv_layers=0, extra=dict(final_conv_kernel=0), loss_keypoint=dict(type='MaskedMSELoss', )), @@ -75,8 +73,6 @@ paf_heads_cfg=[ dict( type='DeconvHead', - in_channels=32, - out_channels=38, num_deconv_layers=0, extra=dict(final_conv_kernel=0), loss_keypoint=dict(type='MaskedMSELoss', )), @@ -123,7 +119,12 @@ dict( type='MultitaskGatherTarget', pipeline_list=[ - [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], [dict( type='BottomUpGeneratePAFTarget', limb_width=1, @@ -151,7 +152,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton' + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py new file mode 100644 index 0000000000..e9eec7543e --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py @@ -0,0 +1,184 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + # additional channel for bg + out_channels_cm=17 + 1, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 5, + heatmap_index=[5], + paf_index=[0, 1, 2, 3, 4], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=True) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 5, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index ad20ea764e..54e3d047a8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -118,7 +118,12 @@ dict( type='MultitaskGatherTarget', pipeline_list=[ - [dict(type='BottomUpGenerateHeatmapTarget', sigma=2)], + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=True) + ], [dict( type='BottomUpGeneratePAFTarget', limb_width=1, @@ -146,7 +151,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton' + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' ]), ] diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index fc82116912..c5a1294f38 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -138,13 +138,21 @@ class HeatmapGenerator: Unbiased Data Processing for Human Pose Estimation (CVPR 2020). """ - def __init__(self, output_size, num_joints, sigma=-1, use_udp=False): + def __init__(self, + output_size, + num_joints, + sigma=-1, + use_udp=False, + with_bg=False): self.output_size = output_size self.num_joints = num_joints + self.with_bg = with_bg + if sigma < 0: sigma = self.output_size / 64 self.sigma = sigma size = 6 * sigma + 3 + self.use_udp = use_udp if use_udp: self.x = np.arange(0, size, 1, np.float32) @@ -157,8 +165,15 @@ def __init__(self, output_size, num_joints, sigma=-1, use_udp=False): def __call__(self, joints): """Generate heatmaps.""" - hms = np.zeros((self.num_joints, self.output_size, self.output_size), - dtype=np.float32) + if self.with_bg: + hms = np.zeros( + (self.num_joints + 1, self.output_size, self.output_size), + dtype=np.float32) + else: + hms = np.zeros( + (self.num_joints, self.output_size, self.output_size), + dtype=np.float32) + sigma = self.sigma for p in joints: for idx, pt in enumerate(p): @@ -189,6 +204,8 @@ def __call__(self, joints): hms[idx, aa:bb, cc:dd] = np.maximum(hms[idx, aa:bb, cc:dd], g[a:b, c:d]) + if self.with_bg: + hms[-1] = 1 - np.max(hms[:-1]) return hms @@ -520,15 +537,16 @@ class BottomUpGenerateHeatmapTarget: Unbiased Data Processing for Human Pose Estimation (CVPR 2020). """ - def __init__(self, sigma, use_udp=False): + def __init__(self, sigma, use_udp=False, with_bg=False): self.sigma = sigma self.use_udp = use_udp + self.with_bg = with_bg def _generate(self, num_joints, heatmap_size): """Get heatmap generator.""" heatmap_generator = [ - HeatmapGenerator(output_size, num_joints, self.sigma, self.use_udp) - for output_size in heatmap_size + HeatmapGenerator(output_size, num_joints, self.sigma, self.use_udp, + self.with_bg) for output_size in heatmap_size ] return heatmap_generator diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 33340fc266..87295a0881 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -233,7 +233,11 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): features = self.backbone(image_resized) if self.with_keypoint: outputs = self.keypoint_head(features) - heatmaps = outputs['heatmaps'][-1] + # ignore back-ground confidence maps + heatmaps = [ + hm[:, :img_metas['num_joints']] + for hm in outputs['heatmaps'][-1] + ] pafs = outputs['pafs'][-1] if self.test_cfg.get('flip_test', True): @@ -242,8 +246,11 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): torch.flip(image_resized, [3])) if self.with_keypoint: outputs_flipped = self.keypoint_head(features_flipped) - - heatmaps_flipped = outputs_flipped['heatmaps'][-1] + # ignore back-ground confidence maps + heatmaps_flipped = [ + hm[:, :img_metas['num_joints']] + for hm in outputs_flipped['heatmaps'][-1] + ] pafs_flipped = outputs_flipped['pafs'][-1] heatmaps_flipped = flip_feature_maps( diff --git a/mmpose/models/heads/deconv_head.py b/mmpose/models/heads/deconv_head.py index d2e27e2e22..5f1fd79f9e 100644 --- a/mmpose/models/heads/deconv_head.py +++ b/mmpose/models/heads/deconv_head.py @@ -36,8 +36,8 @@ class DeconvHead(nn.Module): """ def __init__(self, - in_channels, - out_channels, + in_channels=3, + out_channels=17, num_deconv_layers=3, num_deconv_filters=(256, 256, 256), num_deconv_kernels=(4, 4, 4), From f0643f2285b6fee2501dee8ee955e6b12f4aa08b Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 28 Jun 2021 17:26:54 +0800 Subject: [PATCH 43/98] allow different num_blocks and block_channels for different stages --- .../coco/openpose_sn_coco_368x368.py | 183 ++++++++++++++++++ mmpose/models/backbones/openpose_v2.py | 25 ++- 2 files changed, 202 insertions(+), 6 deletions(-) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py new file mode 100644 index 0000000000..3b3d6e4cba --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py @@ -0,0 +1,183 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + out_channels_cm=17, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=5, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=(8, 8, 8, 8, 5), + block_channels=(128, 128, 128, 256, 256)), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 4, + heatmap_index=[4], + paf_index=[0, 1, 2, 3], + ), + train_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + img_size=data_cfg['image_size']), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 4, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/mmpose/models/backbones/openpose_v2.py b/mmpose/models/backbones/openpose_v2.py index 7f09add08f..b5ee248eaa 100644 --- a/mmpose/models/backbones/openpose_v2.py +++ b/mmpose/models/backbones/openpose_v2.py @@ -130,7 +130,15 @@ class OpenPoseNetworkV2(BaseBackbone): part-affinity field). stem_feat_channels (int): Feature channel of the stem network. num_stages (int): Number of stages. + stage_types (list): Types can be 'CM' or 'PAF'. + num_blocks (int|list): Number of blocks in each stage. If + `num_blocks' is int, the same `num_blocks' will be used + for all stages. + block_channels (int|list): Number of block channels in each + stage. If `block_channels' is int, the same `block_channels' + will be used for all stages. norm_cfg (dict): Dictionary to construct and config norm layer. + act_cfg (dict): Config dict for activation layer. Example: >>> from mmpose.models import OpenPoseNetworkV2 @@ -167,6 +175,11 @@ def __init__(self, assert in_channels == 3 assert num_stages == len(stage_types) + if isinstance(num_blocks, int): + num_blocks = [num_blocks] * num_stages + if isinstance(block_channels, int): + block_channels = [block_channels] * num_stages + self.num_stages = num_stages assert self.num_stages >= 1 @@ -213,9 +226,9 @@ def __init__(self, MconvStage( input_channels, 256, - num_blocks=num_blocks, - block_channels=[block_channels] * num_blocks, - block_kernels=[3] * num_blocks, + num_blocks=num_blocks[i], + block_channels=[block_channels[i]] * num_blocks[i], + block_kernels=[3] * num_blocks[i], norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='PReLU'))) self.out_convs.append( @@ -226,9 +239,9 @@ def __init__(self, MconvStage( input_channels, 256, - num_blocks=num_blocks, - block_channels=[block_channels] * num_blocks, - block_kernels=[3] * num_blocks, + num_blocks=num_blocks[i], + block_channels=[block_channels[i]] * num_blocks[i], + block_kernels=[3] * num_blocks[i], norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='PReLU'))) self.out_convs.append( From cc116071c51a2d00fbceadbfe078672677422873 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Tue, 29 Jun 2021 23:05:36 +0800 Subject: [PATCH 44/98] remove redundant settings --- .../aic/higherhrnet_w32_aic_512x512.py | 4 +--- .../aic/higherhrnet_w32_aic_512x512_udp.py | 4 +--- .../associative_embedding/aic/hrnet_w32_aic_512x512.py | 4 +--- .../coco/higherhrnet_w32_coco_512x512.py | 4 +--- .../coco/higherhrnet_w32_coco_512x512_udp.py | 4 +--- .../coco/higherhrnet_w32_coco_640x640.py | 4 +--- .../coco/higherhrnet_w32_coco_640x640_udp.py | 4 +--- .../coco/higherhrnet_w48_coco_512x512.py | 4 +--- .../coco/higherhrnet_w48_coco_512x512_udp.py | 4 +--- .../associative_embedding/coco/hrnet_w32_coco_512x512.py | 4 +--- .../coco/hrnet_w32_coco_512x512_udp.py | 4 +--- .../associative_embedding/coco/hrnet_w32_coco_640x640.py | 4 +--- .../coco/hrnet_w32_coco_640x640_udp.py | 4 +--- .../associative_embedding/coco/hrnet_w48_coco_512x512.py | 4 +--- .../coco/hrnet_w48_coco_512x512_udp.py | 4 +--- .../associative_embedding/coco/hrnet_w48_coco_640x640.py | 4 +--- .../coco/hrnet_w48_coco_640x640_udp.py | 4 +--- .../associative_embedding/coco/mobilenetv2_coco_512x512.py | 4 +--- .../associative_embedding/coco/res101_coco_512x512.py | 4 +--- .../associative_embedding/coco/res101_coco_640x640.py | 4 +--- .../associative_embedding/coco/res152_coco_512x512.py | 4 +--- .../associative_embedding/coco/res152_coco_640x640.py | 4 +--- .../associative_embedding/coco/res50_coco_512x512.py | 4 +--- .../associative_embedding/coco/res50_coco_640x640.py | 4 +--- .../crowdpose/higherhrnet_w32_crowdpose_512x512.py | 4 +--- .../crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py | 4 +--- .../crowdpose/higherhrnet_w32_crowdpose_640x640.py | 4 +--- .../crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py | 4 +--- .../crowdpose/higherhrnet_w48_crowdpose_512x512.py | 4 +--- .../crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py | 4 +--- .../crowdpose/mobilenetv2_crowdpose_512x512.py | 4 +--- .../crowdpose/res101_crowdpose_512x512.py | 4 +--- .../crowdpose/res152_crowdpose_512x512.py | 4 +--- .../crowdpose/res50_crowdpose_512x512.py | 4 +--- .../associative_embedding/mhp/hrnet_w48_mhp_512x512.py | 4 +--- .../part_affinity_field/coco/hrnet_w32_coco_512x512.py | 6 ++---- .../part_affinity_field/coco/openpose_sn_coco_368x368.py | 6 ++---- .../part_affinity_field/coco/openpose_v1_coco_368x368.py | 6 ++---- .../coco/openpose_v1_coco_368x368_withbg.py | 6 ++---- .../part_affinity_field/coco/openpose_v2_coco_368x368.py | 6 ++---- .../coco/openpose_v2_coco_368x368_withbg.py | 6 ++---- .../part_affinity_field/coco/res50_coco_512x512.py | 6 ++---- mmpose/models/detectors/paf.py | 4 ++-- 43 files changed, 51 insertions(+), 135 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py index 03e6a87c49..d5cd34f8ee 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512_udp.py index b4ab95a9f7..cbe431a9a5 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_w32_aic_512x512_udp.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py index 5aa4cf7fbe..5178f2e634 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_w32_aic_512x512.py @@ -98,9 +98,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py index 17e8ce8179..96428ceb45 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512.py @@ -103,9 +103,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py index 710efa958e..eb4a405552 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_512x512_udp.py @@ -103,9 +103,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py index 5054ec5ffd..9b1d291bdd 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640.py @@ -103,9 +103,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py index 0255ca09aa..126bde9550 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w32_coco_640x640_udp.py @@ -103,9 +103,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py index d5e7a33e75..6f75ab50a4 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512.py @@ -103,9 +103,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py index 05e1cb3899..a0a6ffb3df 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_w48_coco_512x512_udp.py @@ -103,9 +103,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py index 674d5a5f92..e6e090d391 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py index a482b70269..a5f70806c7 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_512x512_udp.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py index 3c756f6c8d..f3daa0411d 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py index 4c52f5c433..5a320c2f34 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w32_coco_640x640_udp.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py index ddcff0b45a..1ccdf89e78 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py index 2297593ac2..f13132c114 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_512x512_udp.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py index 7cf4cfbec2..4fe7b44f05 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py index f71ac4e6e8..5d24f6f969 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_w48_coco_640x640_udp.py @@ -99,9 +99,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py index 7593f8f7e8..0c14892d25 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco_512x512.py @@ -68,9 +68,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py index 83926738be..4d4a34007e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_512x512.py @@ -68,9 +68,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py index 9036ded98f..3512603970 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res101_coco_640x640.py @@ -68,9 +68,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py index c3639afa6e..e2f8ab7f2d 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_512x512.py @@ -68,9 +68,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py index 6827e4e184..b2d43d4e9e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res152_coco_640x640.py @@ -68,9 +68,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py index a30e40f41f..a510c5aaa4 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_512x512.py @@ -69,9 +69,7 @@ with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0], )), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py index e023a1e8f6..100635bd07 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/res50_coco_640x640.py @@ -68,9 +68,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py index 0e91de073d..5bffcbc8fd 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py index a7aff7deee..9c54b293a1 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_512x512_udp.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py index 66b7510279..478d739270 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py index 274f60ec71..eef885cb39 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w32_crowdpose_640x640_udp.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py index f55083ebe0..a45f73129e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py index ef5ed914de..d31c636d60 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_w48_crowdpose_512x512_udp.py @@ -102,9 +102,7 @@ pull_loss_factor=[0.001, 0.001], with_heatmaps_loss=[True, True], heatmaps_loss_factor=[1.0, 1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py index fe38c94d5b..b4037a6871 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/mobilenetv2_crowdpose_512x512.py @@ -67,9 +67,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py index 340f8c04e9..65c32641fa 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res101_crowdpose_512x512.py @@ -67,9 +67,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py index 6378529d58..0680370f20 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res152_crowdpose_512x512.py @@ -67,9 +67,7 @@ pull_loss_factor=[0.001], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py index e87af8ce0b..bece913c60 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/res50_crowdpose_512x512.py @@ -68,9 +68,7 @@ with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0], )), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py index a4b5142882..5296a3136f 100644 --- a/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_w48_mhp_512x512.py @@ -97,9 +97,7 @@ pull_loss_factor=[0.01], with_heatmaps_loss=[True], heatmaps_loss_factor=[1.0])), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index 44b2f63f5a..a70a7aacc0 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -110,9 +110,7 @@ heatmap_index=[0], paf_index=[0], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -182,7 +180,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py index 3b3d6e4cba..2a8eee7a3e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py @@ -80,9 +80,7 @@ heatmap_index=[4], paf_index=[0, 1, 2, 3], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -152,7 +150,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py index 8267399105..a38dcd2c35 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py @@ -77,9 +77,7 @@ heatmap_index=[0, 1, 2, 3, 4, 5], paf_index=[6, 7, 8, 9, 10, 11], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -149,7 +147,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py index 3bbaa9bdf1..38bafbbf78 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py @@ -78,9 +78,7 @@ heatmap_index=[0, 1, 2, 3, 4, 5], paf_index=[6, 7, 8, 9, 10, 11], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -150,7 +148,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py index 5188013606..2e520fa0bd 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py @@ -80,9 +80,7 @@ heatmap_index=[5], paf_index=[0, 1, 2, 3, 4], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -152,7 +150,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py index e9eec7543e..9a651231ec 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py @@ -81,9 +81,7 @@ heatmap_index=[5], paf_index=[0, 1, 2, 3, 4], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -153,7 +151,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index 54e3d047a8..2696f920b1 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -79,9 +79,7 @@ heatmap_index=[0], paf_index=[0], ), - train_cfg=dict( - num_joints=channel_cfg['dataset_joints'], - img_size=data_cfg['image_size']), + train_cfg=dict(), test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, @@ -151,7 +149,7 @@ keys=['img'], meta_keys=[ 'image_file', 'aug_data', 'test_scale_factor', 'base_size', - 'center', 'scale', 'flip_index', 'skeleton', 'num_joints' + 'center', 'scale', 'flip_index', 'skeleton' ]), ] diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 87295a0881..05a2c4223f 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -235,7 +235,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): outputs = self.keypoint_head(features) # ignore back-ground confidence maps heatmaps = [ - hm[:, :img_metas['num_joints']] + hm[:, :self.test_cfg['num_joints']] for hm in outputs['heatmaps'][-1] ] pafs = outputs['pafs'][-1] @@ -248,7 +248,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): outputs_flipped = self.keypoint_head(features_flipped) # ignore back-ground confidence maps heatmaps_flipped = [ - hm[:, :img_metas['num_joints']] + hm[:, :self.test_cfg['num_joints']] for hm in outputs_flipped['heatmaps'][-1] ] pafs_flipped = outputs_flipped['pafs'][-1] From a97e2cc865624bf3d400f0693b337c35c309905d Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 19 Jul 2021 21:07:49 +0800 Subject: [PATCH 45/98] update lightweight openpose --- mmpose/models/backbones/__init__.py | 4 +- .../models/backbones/lightweight_openpose.py | 435 ++++++++++++++++++ .../test_lightweight_openpose.py | 25 + 3 files changed, 463 insertions(+), 1 deletion(-) create mode 100644 mmpose/models/backbones/lightweight_openpose.py create mode 100644 tests/test_backbones/test_lightweight_openpose.py diff --git a/mmpose/models/backbones/__init__.py b/mmpose/models/backbones/__init__.py index c3cf3cd6b8..45bb35fb24 100644 --- a/mmpose/models/backbones/__init__.py +++ b/mmpose/models/backbones/__init__.py @@ -2,6 +2,7 @@ from .cpm import CPM from .hourglass import HourglassNet from .hrnet import HRNet +from .lightweight_openpose import LightweightOpenPoseNetwork from .mobilenet_v2 import MobileNetV2 from .mobilenet_v3 import MobileNetV3 from .mspn import MSPN @@ -24,5 +25,6 @@ 'AlexNet', 'HourglassNet', 'HRNet', 'MobileNetV2', 'MobileNetV3', 'RegNet', 'ResNet', 'ResNetV1d', 'ResNeXt', 'SCNet', 'SEResNet', 'SEResNeXt', 'ShuffleNetV1', 'ShuffleNetV2', 'CPM', 'RSN', 'MSPN', 'ResNeSt', 'VGG', - 'TCN', 'OpenPoseNetworkV1', 'OpenPoseNetworkV2' + 'TCN', 'OpenPoseNetworkV1', 'OpenPoseNetworkV2', + 'LightweightOpenPoseNetwork' ] diff --git a/mmpose/models/backbones/lightweight_openpose.py b/mmpose/models/backbones/lightweight_openpose.py new file mode 100644 index 0000000000..112995d974 --- /dev/null +++ b/mmpose/models/backbones/lightweight_openpose.py @@ -0,0 +1,435 @@ +import copy + +import torch +import torch.nn as nn +from mmcv.cnn import ConvModule, constant_init, normal_init +from torch.nn.modules.batchnorm import _BatchNorm + +from mmpose.utils import get_root_logger +from ..builder import BACKBONES +from .base_backbone import BaseBackbone +from .utils import load_checkpoint + + +class CpmLayer(nn.Module): + """A CPM-type layer. + + Args: + in_channels (int): The input channels. + out_channels (int): The output channels. + """ + + def __init__(self, in_channels, out_channels): + super().__init__() + self.pre_conv = ConvModule( + in_channels, out_channels, 1, padding=0, norm_cfg=None) + self.feat = nn.Sequential( + ConvModule( + out_channels, + out_channels, + 3, + padding=1, + groups=out_channels, + bias=False, + act_cfg=dict(type='ELU'), + norm_cfg=None), + ConvModule( + out_channels, + out_channels, + 1, + padding=0, + bias=False, + act_cfg=dict(type='ELU'), + norm_cfg=None), + ConvModule( + out_channels, + out_channels, + 3, + padding=1, + groups=out_channels, + bias=False, + act_cfg=dict(type='ELU'), + norm_cfg=None), + ConvModule( + out_channels, + out_channels, + 1, + padding=0, + bias=False, + act_cfg=dict(type='ELU'), + norm_cfg=None), + ConvModule( + out_channels, + out_channels, + 3, + padding=1, + groups=out_channels, + bias=False, + act_cfg=dict(type='ELU'), + norm_cfg=None), + ConvModule( + out_channels, + out_channels, + 1, + padding=0, + bias=False, + act_cfg=dict(type='ELU'), + norm_cfg=None)) + self.out_conv = ConvModule( + out_channels, out_channels, 3, padding=1, norm_cfg=None) + + def forward(self, x): + x = self.pre_conv(x) + x = self.out_conv(x + self.feat(x)) + return x + + +class InitialStage(nn.Module): + """The initial stage. + + Args: + in_channels (int): The input channels. + mid_channels (int): The middle-layer channels. + out_channels_cm (int): The output channels for CM ( + confidence map, or heatmap). + out_channels_paf (int): The output channels for PAF ( + part-affinity field). + """ + + def __init__(self, in_channels, mid_channels, out_channels_cm, + out_channels_paf): + super().__init__() + self.feat = nn.Sequential( + ConvModule(in_channels, in_channels, 3, padding=1, norm_cfg=None), + ConvModule(in_channels, in_channels, 3, padding=1, norm_cfg=None), + ConvModule(in_channels, in_channels, 3, padding=1, norm_cfg=None)) + self.cm_out_conv = nn.Sequential( + ConvModule( + in_channels, + mid_channels, + kernel_size=1, + padding=0, + norm_cfg=None), + ConvModule( + mid_channels, + out_channels_cm, + kernel_size=1, + padding=0, + norm_cfg=None, + act_cfg=None)) + self.paf_out_conv = nn.Sequential( + ConvModule( + in_channels, + mid_channels, + kernel_size=1, + padding=0, + norm_cfg=None), + ConvModule( + mid_channels, + out_channels_paf, + kernel_size=1, + padding=0, + norm_cfg=None, + act_cfg=None)) + + def forward(self, x): + features = self.feat(x) + cm_output = self.cm_out_conv(features) + paf_output = self.paf_out_conv(features) + return [cm_output, paf_output] + + +class RefinementStageBlock(nn.Module): + """The block for the refinement stage. + + Args: + in_channels (int): The input channels. + out_channels (int): The output channels. + """ + + def __init__(self, in_channels, out_channels): + super().__init__() + self.pre_conv = ConvModule( + in_channels, out_channels, 1, padding=0, norm_cfg=None) + self.feat = nn.Sequential( + ConvModule( + out_channels, out_channels, 3, padding=1, norm_cfg=None), + ConvModule( + out_channels, + out_channels, + 3, + dilation=2, + padding=2, + norm_cfg=None)) + + def forward(self, x): + pre_features = self.pre_conv(x) + features = self.feat(pre_features) + return pre_features + features + + +class RefinementStage(nn.Module): + """The refinement stage. + + Args: + in_channels (int): The input channels. + mid_channels (int): The middle-layer channels. + out_channels_cm (int): The output channels for CM ( + confidence map, or heatmap). + out_channels_paf (int): The output channels for PAF ( + part-affinity field). + """ + + def __init__(self, in_channels, mid_channels, out_channels_cm, + out_channels_paf): + super().__init__() + self.feat = nn.Sequential( + RefinementStageBlock(in_channels, mid_channels), + RefinementStageBlock(mid_channels, mid_channels), + RefinementStageBlock(mid_channels, mid_channels), + RefinementStageBlock(mid_channels, mid_channels), + RefinementStageBlock(mid_channels, mid_channels)) + self.cm_out_conv = nn.Sequential( + ConvModule( + mid_channels, mid_channels, 1, padding=0, norm_cfg=None), + ConvModule( + mid_channels, + out_channels_cm, + 1, + padding=0, + norm_cfg=None, + act_cfg=None)) + self.paf_out_conv = nn.Sequential( + ConvModule( + mid_channels, mid_channels, 1, padding=0, norm_cfg=None), + ConvModule( + mid_channels, + out_channels_paf, + 1, + padding=0, + norm_cfg=None, + act_cfg=None)) + + def forward(self, x): + features = self.feat(x) + cm_output = self.cm_out_conv(features) + paf_output = self.paf_out_conv(features) + return [cm_output, paf_output] + + +@BACKBONES.register_module() +class LightweightOpenPoseNetwork(BaseBackbone): + """Lightweight OpenPose backbone Network. + + Real-time 2D Multi-Person Pose Estimation on + CPU: Lightweight OpenPose + + More details can be found in the `paper + `__ . + + Args: + in_channels (int): The input channels. + out_channels_cm (int): The output channels for CM ( + confidence map, or heatmap). + out_channels_paf (int): The output channels for PAF ( + part-affinity field). + stem_feat_channels (int): Feature channel of the stem network. + num_stages (int): Number of stages. + norm_cfg (dict): Dictionary to construct and config norm layer. + + Example: + >>> from mmpose.models import LightweightOpenPoseNetwork + >>> import torch + >>> self = LightweightOpenPoseNetwork(3, 19, 38) + >>> self.eval() + >>> inputs = torch.rand(1, 3, 368, 368) + >>> level_outputs = self.forward(inputs) + >>> for level_output in level_outputs: + ... print(tuple(level_output.shape)) + (1, 19, 46, 46) + (1, 19, 46, 46) + (1, 38, 46, 46) + (1, 38, 46, 46) + """ + + def __init__(self, + in_channels, + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2, + norm_cfg=dict(type='BN', requires_grad=True)): + # Protect mutable default arguments + norm_cfg = copy.deepcopy(norm_cfg) + super().__init__() + + assert in_channels == 3 + + self.num_stages = num_stages + assert self.num_stages >= 1 + + self.features = nn.Sequential( + ConvModule( + in_channels, + 32, + 3, + stride=2, + padding=1, + norm_cfg=norm_cfg, + bias=False), + # conv_dw(32, 64) + ConvModule( + 32, 32, 3, padding=1, groups=32, bias=False, + norm_cfg=norm_cfg), + ConvModule(32, 64, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(64, 128, stride=2) + ConvModule( + 64, + 64, + 3, + stride=2, + padding=1, + groups=64, + bias=False, + norm_cfg=norm_cfg), + ConvModule(64, 128, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(128, 128) + ConvModule( + 128, + 128, + 3, + padding=1, + groups=128, + bias=False, + norm_cfg=norm_cfg), + ConvModule(128, 128, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(128, 256, stride=2) + ConvModule( + 128, + 128, + 3, + stride=2, + padding=1, + groups=128, + bias=False, + norm_cfg=norm_cfg), + ConvModule(128, 256, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(256, 256) + ConvModule( + 256, + 256, + 3, + padding=1, + groups=256, + bias=False, + norm_cfg=norm_cfg), + ConvModule(256, 256, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(256, 512) + ConvModule( + 256, + 256, + 3, + padding=1, + groups=256, + bias=False, + norm_cfg=norm_cfg), + ConvModule(256, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(512, 512, dilation=2, padding=2) + ConvModule( + 512, + 512, + 3, + padding=2, + dilation=2, + groups=512, + bias=False, + norm_cfg=norm_cfg), + ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(512, 512) + ConvModule( + 512, + 512, + 3, + padding=1, + groups=512, + bias=False, + norm_cfg=norm_cfg), + ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(512, 512) + ConvModule( + 512, + 512, + 3, + padding=1, + groups=512, + bias=False, + norm_cfg=norm_cfg), + ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(512, 512) + ConvModule( + 512, + 512, + 3, + padding=1, + groups=512, + bias=False, + norm_cfg=norm_cfg), + ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), + # conv_dw(512, 512) + ConvModule( + 512, + 512, + 3, + padding=1, + groups=512, + bias=False, + norm_cfg=norm_cfg), + ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), + CpmLayer(512, stem_feat_channels)) + + self.initial_stage = InitialStage(stem_feat_channels, 512, + out_channels_cm, out_channels_paf) + self.refinement_stages = nn.ModuleList() + for idx in range(num_stages - 1): + self.refinement_stages.append( + RefinementStage( + stem_feat_channels + out_channels_cm + out_channels_paf, + stem_feat_channels, out_channels_cm, out_channels_paf)) + + def init_weights(self, pretrained=None): + """Initialize the weights in backbone. + + Args: + pretrained (str, optional): Path to pre-trained weights. + Defaults to None. + """ + if isinstance(pretrained, str): + logger = get_root_logger() + load_checkpoint(self, pretrained, strict=False, logger=logger) + elif pretrained is None: + for m in self.modules(): + if isinstance(m, nn.Conv2d): + normal_init(m, std=0.001) + elif isinstance(m, (_BatchNorm, nn.GroupNorm)): + constant_init(m, 1) + else: + raise TypeError('pretrained must be a str or None') + + def forward(self, x): + """Model forward function.""" + stem_feat = self.features(x) + + cm_outputs = [] + paf_outputs = [] + + cm_output, paf_output = self.initial_stage(stem_feat) + cm_outputs.append(cm_output) + paf_outputs.append(paf_output) + + for refinement_stage in self.refinement_stages: + cm_output, paf_output = refinement_stage( + torch.cat([stem_feat, cm_outputs[-1], paf_outputs[-1]], dim=1)) + cm_outputs.append(cm_output) + paf_outputs.append(paf_output) + + return [*cm_outputs, *paf_outputs] diff --git a/tests/test_backbones/test_lightweight_openpose.py b/tests/test_backbones/test_lightweight_openpose.py new file mode 100644 index 0000000000..18ac28c300 --- /dev/null +++ b/tests/test_backbones/test_lightweight_openpose.py @@ -0,0 +1,25 @@ +import pytest +import torch + +from mmpose.models import LightweightOpenPoseNetwork + + +def test_lightweight_openpose_network_backbone(): + with pytest.raises(AssertionError): + # OpenPoseNetwork's num_stacks should larger than 0 + LightweightOpenPoseNetwork(in_channels=3, num_stages=-1) + + with pytest.raises(AssertionError): + # OpenPoseNetwork's in_channels should be 3 + LightweightOpenPoseNetwork(in_channels=2) + + # Test OpenPoseNetwork + model = LightweightOpenPoseNetwork(in_channels=3) + model.init_weights() + model.train() + + imgs = torch.randn(1, 3, 368, 368) + feat = model(imgs) + assert len(feat) == 4 + assert feat[0].shape == torch.Size([1, 19, 46, 46]) + assert feat[-1].shape == torch.Size([1, 38, 46, 46]) From 2aa7ce95033a38c1e2ee5aaa7b63783346b69e20 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 19 Jul 2021 21:16:29 +0800 Subject: [PATCH 46/98] add lightopenpose config --- .../coco/lightweight_openpose_coco_368x368.py | 178 ++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py new file mode 100644 index 0000000000..e2af36fbfc --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py @@ -0,0 +1,178 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained=None, + backbone=dict( + type='LightweightOpenPoseNetwork', + in_channels=3, + out_channels_cm=17, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + heatmap_index=[0, 1], + paf_index=[2, 3], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 2 + [1] * 2, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 7fa866d51f363bd7a0ac15fff3f6e4e0c0e08b20 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Tue, 20 Jul 2021 15:48:59 +0800 Subject: [PATCH 47/98] update pretrained --- .../coco/lightweight_openpose_coco_368x368.py | 8 ++++---- .../models/backbones/lightweight_openpose.py | 20 +++++++++---------- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py index e2af36fbfc..739a649973 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py @@ -50,7 +50,7 @@ # model settings model = dict( type='PartAffinityField', - pretrained=None, + pretrained='models/mobilenetv1_sgd_68.848.pth', backbone=dict( type='LightweightOpenPoseNetwork', in_channels=3, @@ -153,10 +153,10 @@ test_pipeline = val_pipeline -data_root = 'data/coco' +data_root = '/data/mscoco2017/' data = dict( - samples_per_gpu=24, - workers_per_gpu=2, + samples_per_gpu=2, + workers_per_gpu=0, train=dict( type='BottomUpCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', diff --git a/mmpose/models/backbones/lightweight_openpose.py b/mmpose/models/backbones/lightweight_openpose.py index 112995d974..3a246305f2 100644 --- a/mmpose/models/backbones/lightweight_openpose.py +++ b/mmpose/models/backbones/lightweight_openpose.py @@ -384,8 +384,9 @@ def __init__(self, groups=512, bias=False, norm_cfg=norm_cfg), - ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg), - CpmLayer(512, stem_feat_channels)) + ConvModule(512, 512, 1, padding=0, bias=False, norm_cfg=norm_cfg)) + + self.cpm = CpmLayer(512, stem_feat_channels) self.initial_stage = InitialStage(stem_feat_channels, 512, out_channels_cm, out_channels_paf) @@ -403,21 +404,20 @@ def init_weights(self, pretrained=None): pretrained (str, optional): Path to pre-trained weights. Defaults to None. """ + for m in self.modules(): + if isinstance(m, nn.Conv2d): + normal_init(m, std=0.001) + elif isinstance(m, (_BatchNorm, nn.GroupNorm)): + constant_init(m, 1) if isinstance(pretrained, str): logger = get_root_logger() load_checkpoint(self, pretrained, strict=False, logger=logger) - elif pretrained is None: - for m in self.modules(): - if isinstance(m, nn.Conv2d): - normal_init(m, std=0.001) - elif isinstance(m, (_BatchNorm, nn.GroupNorm)): - constant_init(m, 1) - else: + elif pretrained is not None: raise TypeError('pretrained must be a str or None') def forward(self, x): """Model forward function.""" - stem_feat = self.features(x) + stem_feat = self.cpm(self.features(x)) cm_outputs = [] paf_outputs = [] From edd8be44eb44a49e0bdb1ec1b0245423e5f14635 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Tue, 20 Jul 2021 15:50:35 +0800 Subject: [PATCH 48/98] update config --- .../coco/lightweight_openpose_coco_368x368.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py index 739a649973..6cf7d4b883 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py @@ -153,10 +153,10 @@ test_pipeline = val_pipeline -data_root = '/data/mscoco2017/' +data_root = 'data/coco' data = dict( - samples_per_gpu=2, - workers_per_gpu=0, + samples_per_gpu=24, + workers_per_gpu=2, train=dict( type='BottomUpCocoDataset', ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', From 83e0d549bda5b84dac605f8467974916434c2018 Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 23 Jul 2021 15:38:55 +0800 Subject: [PATCH 49/98] add neck & modify skeleton --- ...htweight_openpose_coco_368x368_withneck.py | 180 ++++++++++++++++++ mmpose/core/post_processing/group.py | 41 ++-- .../datasets/bottom_up/bottom_up_coco.py | 109 +++++++++-- 3 files changed, 297 insertions(+), 33 deletions(-) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withneck.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withneck.py new file mode 100644 index 0000000000..f5735ad3ff --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withneck.py @@ -0,0 +1,180 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + add_neck=True, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/mobilenetv1_sgd_68.848.pth', + backbone=dict( + type='LightweightOpenPoseNetwork', + in_channels=3, + out_channels_cm=17, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + heatmap_index=[0, 1], + paf_index=[2, 3], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + add_neck=data_cfg['add_neck'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 2 + [1] * 2, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index d2ac173da9..4b91ccf98f 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -494,18 +494,35 @@ def __init__(self, cfg): super().__init__(cfg) self.paf_thr = 0.05 - # Heatmap indices to find each limb (joint connection). - self.limb2joint = [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], - [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], - [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], - [3, 5], [4, 6]] - - # PAF indices containing the x and y coordinates of the PAF for a - # given limb. - self.limb2paf = [[0, 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], [28, 29], [30, 31], - [32, 33], [34, 35], [36, 37]] + self.add_neck = cfg.get('add_neck', False) + + if self.add_neck: + # Heatmap indices to find each limb (joint connection). + self.limb2joint = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], + [1, 8], [8, 9], [9, 10], [1, 11], [11, 12], + [12, 13], [1, 0], [0, 14], [14, 16], [0, 15], + [15, 17], [2, 16], [5, 17]] + + # PAF indices containing the x and y coordinates of the PAF for a + # given limb. + self.limb2paf = [[12, 13], [20, 21], [14, 15], [16, 17], [22, 23], + [24, 25], [0, 1], [2, 3], [4, 5], [6, 7], [8, 9], + [10, 11], [28, 29], [30, 31], [34, 35], [32, 33], + [36, 37], [18, 19], [26, 27]] + + else: + # Heatmap indices to find each limb (joint connection). + self.limb2joint = [[15, 13], [13, 11], [16, 14], [14, 12], + [11, 12], [5, 11], [6, 12], [5, 6], [5, 7], + [6, 8], [7, 9], [8, 10], [1, 2], [0, 1], [0, 2], + [1, 3], [2, 4], [3, 5], [4, 6]] + + # PAF indices containing the x and y coordinates of the PAF for a + # given limb. + self.limb2paf = [[0, 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], [28, 29], [30, 31], + [32, 33], [34, 35], [36, 37]] self.NUM_LIMBS = len(self.limb2joint) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index 7f1ea14b4c..cb97c6f8bf 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -57,24 +57,48 @@ def __init__(self, test_mode=False): super().__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode) - self.ann_info['flip_index'] = [ - 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15 - ] + self.ann_info['add_neck'] = data_cfg.get('add_neck', False) + self.ann_info['use_different_joint_weights'] = False - # joint index starts from 0 - self.ann_info['skeleton'] = [[15, 13], [13, 11], [16, 14], [14, 12], - [11, 12], [5, 11], [6, 12], [5, 6], - [5, 7], [6, 8], [7, 9], [8, 10], [1, 2], - [0, 1], [0, 2], [1, 3], [2, 4], [3, 5], - [4, 6]] + if self.ann_info['add_neck']: + self.ann_info['flip_index'] = [ + 0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16 + ] - self.ann_info['use_different_joint_weights'] = False - self.ann_info['joint_weights'] = np.array( - [ - 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., 1.2, - 1.2, 1.5, 1.5 - ], - dtype=np.float32).reshape((self.ann_info['num_joints'], 1)) + # joint index starts from 0 + self.ann_info['skeleton'] = [[1, 8], [8, 9], [9, 10], [1, 11], + [11, 12], [12, 13], [1, 2], [2, 3], + [3, 4], [2, 16], [1, 5], [5, 6], + [6, 7], [5, 17], [1, 0], [0, 14], + [0, 15], [14, 16], [15, 17]] + + self.ann_info['joint_weights'] = np.array( + [ + 1., 1., 1., 1.2, 1.5, 1., 1.2, 1.5, 1., 1.2, 1.5, 1., 1.2, + 1.5, 1., 1., 1., 1. + ], + dtype=np.float32).reshape((self.ann_info['num_joints'] + 1, 1)) + + else: + self.ann_info['flip_index'] = [ + 0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15 + ] + + # joint index starts from 0 + self.ann_info['skeleton'] = [[15, 13], [13, 11], [16, + 14], [14, 12], + [11, 12], [5, 11], [6, 12], [5, 6], + [5, 7], [6, 8], [7, 9], [8, + 10], [1, 2], + [0, 1], [0, 2], [1, 3], [2, 4], + [3, 5], [4, 6]] + + self.ann_info['joint_weights'] = np.array( + [ + 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., + 1.2, 1.2, 1.5, 1.5 + ], + dtype=np.float32).reshape((self.ann_info['num_joints'], 1)) # 'https://github.com/cocodataset/cocoapi/blob/master/PythonAPI/' # 'pycocotools/cocoeval.py#L523' @@ -148,6 +172,36 @@ def _get_single(self, idx): if obj['iscrowd'] == 0 or obj['num_keypoints'] > 0 ] + if self.ann_info['add_neck']: + reorder_map = [ + 0, 6, 8, 10, 5, 7, 9, 12, 14, 16, 11, 13, 15, 2, 1, 4, 3 + ] + for obj in anno: + keypoints = np.array(obj['keypoints']).reshape( + self.ann_info['num_joints'], 3) + converted_keypoints = np.zeros( + (self.ann_info['num_joints'] + 1, 3)) + for i, idx in enumerate(reorder_map): + if i == 0: + converted_keypoints[i] = keypoints[idx] + else: + converted_keypoints[i + 1] = keypoints[idx] + + # Add neck as a mean of shoulders + converted_keypoints[1, 0] = (keypoints[5, 0] + + keypoints[6, 0]) / 2 + converted_keypoints[1, 1] = (keypoints[5, 1] + + keypoints[6, 1]) / 2 + if keypoints[5][2] == 2 and keypoints[6][2] == 2: + converted_keypoints[1][2] = 2 + elif keypoints[5][2] == 0 or keypoints[6][2] == 0: + converted_keypoints[1][2] = 0 + else: + converted_keypoints[1][2] = 1 + + keypoints = list(converted_keypoints.reshape(-1)) + obj['keypoints'] = keypoints + joints = self._get_joints(anno) mask_list = [mask.copy() for _ in range(self.ann_info['num_scales'])] joints_list = [ @@ -168,14 +222,24 @@ def _get_joints(self, anno): num_people = len(anno) if self.ann_info['scale_aware_sigma']: - joints = np.zeros((num_people, self.ann_info['num_joints'], 4), - dtype=np.float32) + if self.ann_info['add_neck']: + joints = np.zeros( + (num_people, self.ann_info['num_joints'] + 1, 4), + dtype=np.float32) + else: + joints = np.zeros((num_people, self.ann_info['num_joints'], 4), + dtype=np.float32) else: - joints = np.zeros((num_people, self.ann_info['num_joints'], 3), - dtype=np.float32) + if self.ann_info['add_neck']: + joints = np.zeros( + (num_people, self.ann_info['num_joints'] + 1, 3), + dtype=np.float32) + else: + joints = np.zeros((num_people, self.ann_info['num_joints'], 3), + dtype=np.float32) for i, obj in enumerate(anno): - joints[i, :self.ann_info['num_joints'], :3] = \ + joints[i, :, :3] = \ np.array(obj['keypoints']).reshape([-1, 3]) if self.ann_info['scale_aware_sigma']: # get person box @@ -255,11 +319,14 @@ def evaluate(self, outputs, res_folder, metric='mAP', **kwargs): kpts = defaultdict(list) # iterate over images + order_map = [0, 15, 14, 17, 16, 5, 2, 6, 3, 7, 4, 11, 8, 12, 9, 13, 10] for idx, _preds in enumerate(preds): str_image_path = image_paths[idx] image_id = self.name2id[os.path.basename(str_image_path)] # iterate over people for idx_person, kpt in enumerate(_preds): + if self.ann_info['add_neck']: + kpt = kpt[order_map] # use bbox area area = (np.max(kpt[:, 0]) - np.min(kpt[:, 0])) * ( np.max(kpt[:, 1]) - np.min(kpt[:, 1])) From cc30321b94a78f0a82b6e3747464ac92e38e72e3 Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 27 Jul 2021 14:23:05 +0800 Subject: [PATCH 50/98] rename addneck cfg --- ...8_withneck.py => lightweight_openpose_coco_368x368_addneck.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/{lightweight_openpose_coco_368x368_withneck.py => lightweight_openpose_coco_368x368_addneck.py} (100%) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py similarity index 100% rename from configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withneck.py rename to configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py From e33c1243d18ee5278643cd107ea33795a930dde1 Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 27 Jul 2021 17:18:14 +0800 Subject: [PATCH 51/98] BottomUpGenerateHeatmapTarget pipeline with add_neck --- .../coco/lightweight_openpose_coco_368x368_addneck.py | 3 ++- mmpose/datasets/pipelines/bottom_up_transform.py | 11 +++++++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py index f5735ad3ff..b1bc2ec9f8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py @@ -120,7 +120,8 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + add_neck=data_cfg['add_neck'], + with_bg=True) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index c5a1294f38..a486956586 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -143,11 +143,16 @@ def __init__(self, num_joints, sigma=-1, use_udp=False, + add_neck=False, with_bg=False): self.output_size = output_size self.num_joints = num_joints + self.add_neck = add_neck, self.with_bg = with_bg + if self.add_neck: + self.num_joints += 1 + if sigma < 0: sigma = self.output_size / 64 self.sigma = sigma @@ -537,16 +542,18 @@ class BottomUpGenerateHeatmapTarget: Unbiased Data Processing for Human Pose Estimation (CVPR 2020). """ - def __init__(self, sigma, use_udp=False, with_bg=False): + def __init__(self, sigma, use_udp=False, add_neck=False, with_bg=False): self.sigma = sigma self.use_udp = use_udp + self.add_neck = add_neck self.with_bg = with_bg def _generate(self, num_joints, heatmap_size): """Get heatmap generator.""" heatmap_generator = [ HeatmapGenerator(output_size, num_joints, self.sigma, self.use_udp, - self.with_bg) for output_size in heatmap_size + self.add_neck, self.with_bg) + for output_size in heatmap_size ] return heatmap_generator From 2b0cbd599883fddda7998c26c6933b12f0d1b85e Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 27 Jul 2021 17:32:34 +0800 Subject: [PATCH 52/98] BottomUpGenerateHeatmapTarget pipeline with add_neck --- mmpose/datasets/pipelines/bottom_up_transform.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index a486956586..b4996fa79e 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -656,9 +656,6 @@ def __call__(self, results): if self.skeleton is None: assert results['ann_info']['skeleton'] is not None self.skeleton = results['ann_info']['skeleton'] - else: - assert np.array( - self.skeleton).max() < results['ann_info']['num_joints'] paf_generator = \ self._generate(results['ann_info']['heatmap_size'], From 6b989d1c2adc4d08792e350658575a923e32f1aa Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 27 Jul 2021 17:44:21 +0800 Subject: [PATCH 53/98] update addneck cfg --- .../coco/lightweight_openpose_coco_368x368_addneck.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py index b1bc2ec9f8..98c27f2da5 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py @@ -55,7 +55,7 @@ backbone=dict( type='LightweightOpenPoseNetwork', in_channels=3, - out_channels_cm=17, + out_channels_cm=19, out_channels_paf=38, stem_feat_channels=128, num_stages=2), From 8b777cdcf69c107dd73f209ff7cbb9fc11e04d51 Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 27 Jul 2021 21:29:15 +0800 Subject: [PATCH 54/98] copy to keep self.coco unchanged --- mmpose/datasets/datasets/bottom_up/bottom_up_coco.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index cb97c6f8bf..929ce9278a 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -168,7 +168,7 @@ def _get_single(self, idx): mask = self._get_mask(anno, idx) anno = [ - obj for obj in anno + obj.copy() for obj in anno if obj['iscrowd'] == 0 or obj['num_keypoints'] > 0 ] From 94c9ec151c0bffd43b23b6236a81c4c3fd5eebed Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 27 Jul 2021 22:00:18 +0800 Subject: [PATCH 55/98] update pipeline with addneck --- mmpose/datasets/pipelines/bottom_up_transform.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index b4996fa79e..820379d7e6 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -147,7 +147,7 @@ def __init__(self, with_bg=False): self.output_size = output_size self.num_joints = num_joints - self.add_neck = add_neck, + self.add_neck = add_neck self.with_bg = with_bg if self.add_neck: From 43307854bdde36568190df55724f29c047324380 Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 28 Jul 2021 11:11:03 +0800 Subject: [PATCH 56/98] train paf wholebody --- .../openpose_v1_coco_wholebody_480x480.py | 176 ++++++++++++++++++ mmpose/core/post_processing/group.py | 80 +++++--- .../bottom_up/bottom_up_coco_wholebody.py | 38 ++++ mmpose/models/detectors/paf.py | 1 + 4 files changed, 264 insertions(+), 31 deletions(-) create mode 100644 configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py new file mode 100644 index 0000000000..f61b386959 --- /dev/null +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py @@ -0,0 +1,176 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=133, + dataset_channel=[ + list(range(133)), + ], + inference_channel=list(range(133))) + +data_cfg = dict( + image_size=480, + base_size=256, + base_sigma=2, + heatmap_size=[60], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV1', + in_channels=3, + out_channels_cm=133, + out_channels_paf=270, + stem_feat_channels=128, + num_stages=6), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 6, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 6, + heatmap_index=[0, 1, 2, 3, 4, 5], + paf_index=[6, 7, 8, 9, 10, 11], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True)) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=False) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 6 + [1] * 6, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_train_v1.0.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 4b91ccf98f..978276841c 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -496,36 +496,6 @@ def __init__(self, cfg): self.paf_thr = 0.05 self.add_neck = cfg.get('add_neck', False) - if self.add_neck: - # Heatmap indices to find each limb (joint connection). - self.limb2joint = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], - [1, 8], [8, 9], [9, 10], [1, 11], [11, 12], - [12, 13], [1, 0], [0, 14], [14, 16], [0, 15], - [15, 17], [2, 16], [5, 17]] - - # PAF indices containing the x and y coordinates of the PAF for a - # given limb. - self.limb2paf = [[12, 13], [20, 21], [14, 15], [16, 17], [22, 23], - [24, 25], [0, 1], [2, 3], [4, 5], [6, 7], [8, 9], - [10, 11], [28, 29], [30, 31], [34, 35], [32, 33], - [36, 37], [18, 19], [26, 27]] - - else: - # Heatmap indices to find each limb (joint connection). - self.limb2joint = [[15, 13], [13, 11], [16, 14], [14, 12], - [11, 12], [5, 11], [6, 12], [5, 6], [5, 7], - [6, 8], [7, 9], [8, 10], [1, 2], [0, 1], [0, 2], - [1, 3], [2, 4], [3, 5], [4, 6]] - - # PAF indices containing the x and y coordinates of the PAF for a - # given limb. - self.limb2paf = [[0, 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], [28, 29], [30, 31], - [32, 33], [34, 35], [36, 37]] - - self.NUM_LIMBS = len(self.limb2joint) - def output_format(self, all_keypoints, pose_entries): """Format transform. @@ -811,7 +781,53 @@ def get_keypoints(self, heatmaps): return all_keypoints_by_type - def parse(self, heatmaps, pafs, adjust=True, refine=True, filter=False): + def define_limb(self, skeleton): + if self.add_neck: + # Heatmap indices to find each limb (joint connection). + self.limb2joint = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], + [1, 8], [8, 9], [9, 10], [1, 11], [11, 12], + [12, 13], [1, 0], [0, 14], [14, 16], [0, 15], + [15, 17], [2, 16], [5, 17]] + + # PAF indices containing the x and y coordinates of the PAF for a + # given limb. + self.limb2paf = [[12, 13], [20, 21], [14, 15], [16, 17], [22, 23], + [24, 25], [0, 1], [2, 3], [4, 5], [6, 7], [8, 9], + [10, 11], [28, 29], [30, 31], [34, 35], [32, 33], + [36, 37], [18, 19], [26, 27]] + + elif skeleton is None: + # Heatmap indices to find each limb (joint connection). + self.limb2joint = [[15, 13], [13, 11], [16, 14], [14, 12], + [11, 12], [5, 11], [6, 12], [5, 6], [5, 7], + [6, 8], [7, 9], [8, 10], [1, 2], [0, 1], [0, 2], + [1, 3], [2, 4], [3, 5], [4, 6]] + + # PAF indices containing the x and y coordinates of the PAF for a + # given limb. + self.limb2paf = [[0, 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], [28, 29], [30, 31], + [32, 33], [34, 35], [36, 37]] + + else: + # Heatmap indices to find each limb (joint connection). + self.limb2joint = skeleton + + # PAF indices containing the x and y coordinates of the PAF for a + # given limb. + self.limb2paf = np.array(range(len(self.limb2joint * + 2))).reshape(-1, 2).tolist() + + self.NUM_LIMBS = len(self.limb2joint) + + def parse(self, + heatmaps, + pafs, + skeleton=None, + adjust=True, + refine=True, + filter=False): """Group keypoints into poses given heatmap and paf. Note: @@ -836,6 +852,8 @@ def parse(self, heatmaps, pafs, adjust=True, refine=True, filter=False): assert heatmaps.shape[0] == 1, 'The batch size is ' \ f'{heatmaps.shape[0]}, but we only support batch size==1.' + self.define_limb(skeleton) + all_keypoints_by_type = self.get_keypoints(heatmaps) pafs_np = np.transpose(pafs.detach().cpu().numpy()[0], [1, 2, 0]) ans, scores = self.group_keypoints(all_keypoints_by_type, pafs_np) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py index 8abccabbba..80769ba845 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py @@ -45,10 +45,48 @@ def __init__(self, self).__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode) + self.ann_info['add_neck'] = data_cfg.get('add_neck', False) self.ann_info['flip_pairs'] = self._make_flip_pairs() self.ann_info['flip_index'] = self.get_flip_index_from_flip_pairs( self.ann_info['flip_pairs']) + # joint index starts from 0 + skeleton_body = [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], + [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], + [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], + [3, 5], [4, 6]] + skeleton_foot = [[15, 17], [15, 18], [15, 19], [16, 20], [16, 21], + [16, 22]] + skeleton_face = [[0, 53], [53, 52], [52, 51], [51, 50], [50, 65], + [65, 66], [66, 67], [67, 68], [65, 70], [70, 69], + [50, 62], [62, 61], [61, 60], [60, 59], [62, 63], + [63, 64], [50, 45], [45, 46], [46, 47], [47, 48], + [48, 49], [50, 44], [44, 43], [43, 42], [42, 41], + [41, 40], [53, 56], [56, 57], [57, 58], [56, 55], + [55, 54], [56, 74], [74, 75], [75, 76], [76, 77], + [74, 73], [73, 72], [72, 71], [74, 85], [85, 86], + [86, 87], [85, 84], [84, 83], [85, 89], [89, 88], + [89, 90], [89, 80], [80, 79], [79, 78], [80, 81], + [81, 82], [80, 31], [31, 32], [32, 33], [33, 34], + [34, 35], [35, 36], [36, 37], [37, 38], [38, 39], + [31, 30], [30, 29], [29, 28], [28, 27], [27, 26], + [26, 25], [25, 24], [24, 23]] + skeleton_lefthand = [[9, 91], [91, 92], [92, 93], [93, 94], [94, 95], + [91, 96], [96, 97], [97, 98], [98, 99], [91, 100], + [100, 101], [101, 102], [102, 103], [91, 104], + [104, 105], [105, 106], [106, 107], [91, 108], + [108, 109], [109, 110], [110, 111]] + skeleton_righthand = [[10, 112], [112, 113], [113, 114], [114, 115], + [115, 116], [112, 117], [117, 118], [118, 119], + [119, 120], [112, 121], [121, 122], [122, 123], + [123, 124], [112, 125], [125, 126], [126, 127], + [127, 128], [112, 129], [129, 130], [130, 131], + [131, 132]] + + self.ann_info['skeleton'] = ( + skeleton_body + skeleton_foot + skeleton_face + skeleton_lefthand + + skeleton_righthand) + self.ann_info['use_different_joint_weights'] = False self.ann_info['joint_weights'] = \ np.ones((self.ann_info['num_joints'], 1), dtype=np.float32) diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index 05a2c4223f..c3db7a40ac 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -308,6 +308,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): # perform grouping grouped, scores = self.parser.parse(aggregated_heatmaps, aggregated_pafs, + img_metas['skeleton'], self.test_cfg['adjust'], self.test_cfg['refine'], self.test_cfg.get('filter', False)) From adb513ac09e92049bd5ea204ab4c81662d822bf2 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 28 Jul 2021 17:22:26 +0800 Subject: [PATCH 57/98] add bn --- mmpose/models/backbones/lightweight_openpose.py | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/mmpose/models/backbones/lightweight_openpose.py b/mmpose/models/backbones/lightweight_openpose.py index 3a246305f2..a25a76acdc 100644 --- a/mmpose/models/backbones/lightweight_openpose.py +++ b/mmpose/models/backbones/lightweight_openpose.py @@ -145,22 +145,26 @@ class RefinementStageBlock(nn.Module): Args: in_channels (int): The input channels. out_channels (int): The output channels. + norm_cfg (dict): Dictionary to construct and config norm layer. """ - def __init__(self, in_channels, out_channels): + def __init__(self, + in_channels, + out_channels, + norm_cfg=dict(type='BN', requires_grad=True)): super().__init__() self.pre_conv = ConvModule( in_channels, out_channels, 1, padding=0, norm_cfg=None) self.feat = nn.Sequential( ConvModule( - out_channels, out_channels, 3, padding=1, norm_cfg=None), + out_channels, out_channels, 3, padding=1, norm_cfg=norm_cfg), ConvModule( out_channels, out_channels, 3, dilation=2, padding=2, - norm_cfg=None)) + norm_cfg=norm_cfg)) def forward(self, x): pre_features = self.pre_conv(x) @@ -395,7 +399,10 @@ def __init__(self, self.refinement_stages.append( RefinementStage( stem_feat_channels + out_channels_cm + out_channels_paf, - stem_feat_channels, out_channels_cm, out_channels_paf)) + stem_feat_channels, + out_channels_cm, + out_channels_paf, + norm_cfg=norm_cfg)) def init_weights(self, pretrained=None): """Initialize the weights in backbone. From f1d347fe0b0733580f567ba9d04a1d8bd4d3be49 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Wed, 28 Jul 2021 17:23:40 +0800 Subject: [PATCH 58/98] add bn --- .../models/backbones/lightweight_openpose.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/mmpose/models/backbones/lightweight_openpose.py b/mmpose/models/backbones/lightweight_openpose.py index a25a76acdc..9e71ddadc0 100644 --- a/mmpose/models/backbones/lightweight_openpose.py +++ b/mmpose/models/backbones/lightweight_openpose.py @@ -182,17 +182,22 @@ class RefinementStage(nn.Module): confidence map, or heatmap). out_channels_paf (int): The output channels for PAF ( part-affinity field). + norm_cfg (dict): Dictionary to construct and config norm layer. """ - def __init__(self, in_channels, mid_channels, out_channels_cm, - out_channels_paf): + def __init__(self, + in_channels, + mid_channels, + out_channels_cm, + out_channels_paf, + norm_cfg=dict(type='BN', requires_grad=True)): super().__init__() self.feat = nn.Sequential( - RefinementStageBlock(in_channels, mid_channels), - RefinementStageBlock(mid_channels, mid_channels), - RefinementStageBlock(mid_channels, mid_channels), - RefinementStageBlock(mid_channels, mid_channels), - RefinementStageBlock(mid_channels, mid_channels)) + RefinementStageBlock(in_channels, mid_channels, norm_cfg), + RefinementStageBlock(mid_channels, mid_channels, norm_cfg), + RefinementStageBlock(mid_channels, mid_channels, norm_cfg), + RefinementStageBlock(mid_channels, mid_channels, norm_cfg), + RefinementStageBlock(mid_channels, mid_channels, norm_cfg)) self.cm_out_conv = nn.Sequential( ConvModule( mid_channels, mid_channels, 1, padding=0, norm_cfg=None), From 01e11088761acbc20c57df2f942276ca8397aa65 Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 28 Jul 2021 17:54:07 +0800 Subject: [PATCH 59/98] get add_neck on dataset --- mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py | 1 + mmpose/datasets/datasets/bottom_up/bottom_up_coco.py | 1 - mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py | 1 - 3 files changed, 1 insertion(+), 2 deletions(-) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py b/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py index 3941f25a39..42485493fc 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py @@ -52,6 +52,7 @@ def __init__(self, self.ann_info['inference_channel'] = data_cfg['inference_channel'] self.ann_info['dataset_channel'] = data_cfg['dataset_channel'] + self.ann_info['add_neck'] = data_cfg.get('add_neck', False) self.use_nms = data_cfg.get('use_nms', False) self.soft_nms = data_cfg.get('soft_nms', True) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index 929ce9278a..99354b84d7 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -57,7 +57,6 @@ def __init__(self, test_mode=False): super().__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode) - self.ann_info['add_neck'] = data_cfg.get('add_neck', False) self.ann_info['use_different_joint_weights'] = False if self.ann_info['add_neck']: diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py index 80769ba845..681329a4d0 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py @@ -45,7 +45,6 @@ def __init__(self, self).__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode) - self.ann_info['add_neck'] = data_cfg.get('add_neck', False) self.ann_info['flip_pairs'] = self._make_flip_pairs() self.ann_info['flip_index'] = self.get_flip_index_from_flip_pairs( self.ann_info['flip_pairs']) From b0b6c71c1759220b255b15b90c8e83070fb36dc0 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Thu, 29 Jul 2021 10:05:19 +0800 Subject: [PATCH 60/98] fix unittest --- mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py | 2 ++ mmpose/datasets/datasets/bottom_up/bottom_up_coco.py | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py b/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py index 3941f25a39..3babc9d55f 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_base_dataset.py @@ -44,6 +44,8 @@ def __init__(self, self.base_sigma = data_cfg['base_sigma'] self.int_sigma = False + self.ann_info['add_neck'] = data_cfg.get('add_neck', False) + self.ann_info['image_size'] = np.array(data_cfg['image_size']) self.ann_info['heatmap_size'] = np.array(data_cfg['heatmap_size']) self.ann_info['num_joints'] = data_cfg['num_joints'] diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py index 929ce9278a..99354b84d7 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco.py @@ -57,7 +57,6 @@ def __init__(self, test_mode=False): super().__init__(ann_file, img_prefix, data_cfg, pipeline, test_mode) - self.ann_info['add_neck'] = data_cfg.get('add_neck', False) self.ann_info['use_different_joint_weights'] = False if self.ann_info['add_neck']: From a16d11f2245fe4c076c6a9dc167b14257ad0ae2b Mon Sep 17 00:00:00 2001 From: luminxu Date: Thu, 29 Jul 2021 15:38:43 +0800 Subject: [PATCH 61/98] fix test with addneck --- .../part_affinity_field/coco/hrnet_w32_coco_512x512.py | 6 ++++-- .../coco/lightweight_openpose_coco_368x368.py | 7 ++++--- .../coco/lightweight_openpose_coco_368x368_addneck.py | 4 +++- .../part_affinity_field/coco/openpose_sn_coco_368x368.py | 7 ++++--- .../part_affinity_field/coco/openpose_v1_coco_368x368.py | 7 ++++--- .../coco/openpose_v1_coco_368x368_withbg.py | 7 ++++--- .../part_affinity_field/coco/openpose_v2_coco_368x368.py | 7 ++++--- .../coco/openpose_v2_coco_368x368_withbg.py | 7 ++++--- .../part_affinity_field/coco/res50_coco_512x512.py | 7 ++++--- mmpose/core/post_processing/group.py | 2 +- mmpose/models/detectors/paf.py | 4 ++-- 11 files changed, 38 insertions(+), 27 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py index a70a7aacc0..24d6b7d1b8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/hrnet_w32_coco_512x512.py @@ -44,6 +44,7 @@ dataset_channel=channel_cfg['dataset_channel'], inference_channel=channel_cfg['inference_channel'], num_scales=1, + with_bg=True, scale_aware_sigma=False, ) @@ -128,7 +129,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -151,7 +153,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py index 6cf7d4b883..6cab1f8e11 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -95,7 +95,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -118,7 +119,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py index 98c27f2da5..807bc88968 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py @@ -45,6 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, + with_bg=True, add_neck=True, ) @@ -97,6 +98,7 @@ adjust=True, refine=True, flip_test=True, + with_bg=data_cfg['with_bg'], add_neck=data_cfg['add_neck'])) train_pipeline = [ @@ -121,7 +123,7 @@ type='BottomUpGenerateHeatmapTarget', sigma=2, add_neck=data_cfg['add_neck'], - with_bg=True) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py index 2a8eee7a3e..953a8585b8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -98,7 +98,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -121,7 +122,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py index a38dcd2c35..bbbf0b653d 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -95,7 +95,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -118,7 +119,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py index 38bafbbf78..203bae17c9 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -96,7 +96,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -119,7 +120,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=True) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py index 2e520fa0bd..825631531e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -98,7 +98,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -121,7 +122,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py index 9a651231ec..d9b53131ac 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -99,7 +99,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -122,7 +123,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=True) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py index 2696f920b1..239901be51 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/res50_coco_512x512.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=True) # model settings model = dict( @@ -97,7 +97,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -120,7 +121,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=True) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 978276841c..d18c222950 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -756,7 +756,7 @@ def get_keypoints(self, heatmaps): """ keypoint_num = 0 - all_keypoints_by_type = [[] for _ in range(self.params.num_joints)] + all_keypoints_by_type = [[] for _ in range(heatmaps.size(1))] heatmaps = self.nms(heatmaps) N, K, H, W = heatmaps.size() diff --git a/mmpose/models/detectors/paf.py b/mmpose/models/detectors/paf.py index c3db7a40ac..2d06fb41f8 100644 --- a/mmpose/models/detectors/paf.py +++ b/mmpose/models/detectors/paf.py @@ -235,7 +235,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): outputs = self.keypoint_head(features) # ignore back-ground confidence maps heatmaps = [ - hm[:, :self.test_cfg['num_joints']] + hm[:, :-1] if self.test_cfg['with_bg'] else hm for hm in outputs['heatmaps'][-1] ] pafs = outputs['pafs'][-1] @@ -248,7 +248,7 @@ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs): outputs_flipped = self.keypoint_head(features_flipped) # ignore back-ground confidence maps heatmaps_flipped = [ - hm[:, :self.test_cfg['num_joints']] + hm[:, :-1] if self.test_cfg['with_bg'] else hm for hm in outputs_flipped['heatmaps'][-1] ] pafs_flipped = outputs_flipped['pafs'][-1] From 3537cac9d7b213e350c7c45f673aed640cb99808 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 30 Jul 2021 09:37:55 +0800 Subject: [PATCH 62/98] fix with bg --- mmpose/datasets/pipelines/bottom_up_transform.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index 820379d7e6..ca193fd3cb 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -210,7 +210,7 @@ def __call__(self, joints): cc:dd] = np.maximum(hms[idx, aa:bb, cc:dd], g[a:b, c:d]) if self.with_bg: - hms[-1] = 1 - np.max(hms[:-1]) + hms[-1] = 1 - np.max(hms[:-1], axis=0) return hms From 8aaee09ef8774c0f9951f48a8a437309444434e3 Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 30 Jul 2021 17:20:28 +0800 Subject: [PATCH 63/98] fix lightweight openpose with_bg=False --- .../coco/lightweight_openpose_coco_368x368.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py index 6cab1f8e11..6ae3959cd2 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, - with_bg=True) + with_bg=False) # model settings model = dict( @@ -156,12 +156,12 @@ data_root = 'data/coco' data = dict( - samples_per_gpu=24, - workers_per_gpu=2, + samples_per_gpu=1, + workers_per_gpu=0, train=dict( type='BottomUpCocoDataset', - ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', - img_prefix=f'{data_root}/train2017/', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', data_cfg=data_cfg, pipeline=train_pipeline), val=dict( From ab9b3ffe196c3ee303595178c246328691352658 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 30 Jul 2021 20:35:15 +0800 Subject: [PATCH 64/98] fix config --- .../coco/lightweight_openpose_coco_368x368.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py index 6ae3959cd2..c391cb7322 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368.py @@ -156,12 +156,12 @@ data_root = 'data/coco' data = dict( - samples_per_gpu=1, - workers_per_gpu=0, + samples_per_gpu=24, + workers_per_gpu=2, train=dict( type='BottomUpCocoDataset', - ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', - img_prefix=f'{data_root}/val2017/', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', data_cfg=data_cfg, pipeline=train_pipeline), val=dict( From 82794dc291c729d9e09b67c1026292647e43c893 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 30 Jul 2021 22:39:39 +0800 Subject: [PATCH 65/98] fix conv bias --- .../coco/openpose_sn_coco_368x368.py | 2 +- .../coco/openpose_v1_coco_368x368.py | 2 +- .../coco/openpose_v1_coco_368x368_withbg.py | 2 +- .../coco/openpose_v2_coco_368x368.py | 2 +- .../coco/openpose_v2_coco_368x368_withbg.py | 2 +- mmpose/.mim/configs | 1 + mmpose/.mim/demo | 1 + mmpose/.mim/model-index.yml | 1 + mmpose/.mim/tools | 1 + .../models/backbones/lightweight_openpose.py | 72 ++++++++++++++----- mmpose/models/backbones/openpose_v1.py | 30 ++++---- mmpose/models/backbones/openpose_v2.py | 38 ++++++---- 12 files changed, 109 insertions(+), 45 deletions(-) create mode 120000 mmpose/.mim/configs create mode 120000 mmpose/.mim/demo create mode 120000 mmpose/.mim/model-index.yml create mode 120000 mmpose/.mim/tools diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py index 953a8585b8..79652ca333 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py @@ -50,7 +50,7 @@ # model settings model = dict( type='PartAffinityField', - pretrained='mmcls://vgg16_bn', + pretrained='mmcls://vgg19_bn', backbone=dict( type='OpenPoseNetworkV2', in_channels=3, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py index bbbf0b653d..658abdb0be 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py @@ -50,7 +50,7 @@ # model settings model = dict( type='PartAffinityField', - pretrained='mmcls://vgg16_bn', + pretrained='mmcls://vgg19_bn', backbone=dict( type='OpenPoseNetworkV1', in_channels=3, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py index 203bae17c9..5d10a5b72b 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368_withbg.py @@ -50,7 +50,7 @@ # model settings model = dict( type='PartAffinityField', - pretrained='mmcls://vgg16_bn', + pretrained='mmcls://vgg19_bn', backbone=dict( type='OpenPoseNetworkV1', in_channels=3, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py index 825631531e..e85fb68d9e 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py @@ -50,7 +50,7 @@ # model settings model = dict( type='PartAffinityField', - pretrained='mmcls://vgg16_bn', + pretrained='mmcls://vgg19_bn', backbone=dict( type='OpenPoseNetworkV2', in_channels=3, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py index d9b53131ac..1af548613b 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py @@ -50,7 +50,7 @@ # model settings model = dict( type='PartAffinityField', - pretrained='mmcls://vgg16_bn', + pretrained='mmcls://vgg19_bn', backbone=dict( type='OpenPoseNetworkV2', in_channels=3, diff --git a/mmpose/.mim/configs b/mmpose/.mim/configs new file mode 120000 index 0000000000..5992d109cb --- /dev/null +++ b/mmpose/.mim/configs @@ -0,0 +1 @@ +../../configs \ No newline at end of file diff --git a/mmpose/.mim/demo b/mmpose/.mim/demo new file mode 120000 index 0000000000..bf71256cd3 --- /dev/null +++ b/mmpose/.mim/demo @@ -0,0 +1 @@ +../../demo \ No newline at end of file diff --git a/mmpose/.mim/model-index.yml b/mmpose/.mim/model-index.yml new file mode 120000 index 0000000000..a18c0b389b --- /dev/null +++ b/mmpose/.mim/model-index.yml @@ -0,0 +1 @@ +../../model-index.yml \ No newline at end of file diff --git a/mmpose/.mim/tools b/mmpose/.mim/tools new file mode 120000 index 0000000000..31941e941d --- /dev/null +++ b/mmpose/.mim/tools @@ -0,0 +1 @@ +../../tools \ No newline at end of file diff --git a/mmpose/models/backbones/lightweight_openpose.py b/mmpose/models/backbones/lightweight_openpose.py index 9e71ddadc0..3ca73ab22b 100644 --- a/mmpose/models/backbones/lightweight_openpose.py +++ b/mmpose/models/backbones/lightweight_openpose.py @@ -22,7 +22,7 @@ class CpmLayer(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.pre_conv = ConvModule( - in_channels, out_channels, 1, padding=0, norm_cfg=None) + in_channels, out_channels, 1, padding=0, norm_cfg=None, bias=True) self.feat = nn.Sequential( ConvModule( out_channels, @@ -76,7 +76,7 @@ def __init__(self, in_channels, out_channels): act_cfg=dict(type='ELU'), norm_cfg=None)) self.out_conv = ConvModule( - out_channels, out_channels, 3, padding=1, norm_cfg=None) + out_channels, out_channels, 3, padding=1, norm_cfg=None, bias=True) def forward(self, x): x = self.pre_conv(x) @@ -100,37 +100,59 @@ def __init__(self, in_channels, mid_channels, out_channels_cm, out_channels_paf): super().__init__() self.feat = nn.Sequential( - ConvModule(in_channels, in_channels, 3, padding=1, norm_cfg=None), - ConvModule(in_channels, in_channels, 3, padding=1, norm_cfg=None), - ConvModule(in_channels, in_channels, 3, padding=1, norm_cfg=None)) + ConvModule( + in_channels, + in_channels, + 3, + padding=1, + norm_cfg=None, + bias=True), + ConvModule( + in_channels, + in_channels, + 3, + padding=1, + norm_cfg=None, + bias=True), + ConvModule( + in_channels, + in_channels, + 3, + padding=1, + norm_cfg=None, + bias=True)) self.cm_out_conv = nn.Sequential( ConvModule( in_channels, mid_channels, kernel_size=1, padding=0, - norm_cfg=None), + norm_cfg=None, + bias=True), ConvModule( mid_channels, out_channels_cm, kernel_size=1, padding=0, norm_cfg=None, - act_cfg=None)) + act_cfg=None, + bias=True)) self.paf_out_conv = nn.Sequential( ConvModule( in_channels, mid_channels, kernel_size=1, padding=0, - norm_cfg=None), + norm_cfg=None, + bias=True), ConvModule( mid_channels, out_channels_paf, kernel_size=1, padding=0, norm_cfg=None, - act_cfg=None)) + act_cfg=None, + bias=True)) def forward(self, x): features = self.feat(x) @@ -154,17 +176,23 @@ def __init__(self, norm_cfg=dict(type='BN', requires_grad=True)): super().__init__() self.pre_conv = ConvModule( - in_channels, out_channels, 1, padding=0, norm_cfg=None) + in_channels, out_channels, 1, padding=0, norm_cfg=None, bias=True) self.feat = nn.Sequential( ConvModule( - out_channels, out_channels, 3, padding=1, norm_cfg=norm_cfg), + out_channels, + out_channels, + 3, + padding=1, + norm_cfg=norm_cfg, + bias=True), ConvModule( out_channels, out_channels, 3, dilation=2, padding=2, - norm_cfg=norm_cfg)) + norm_cfg=norm_cfg, + bias=True)) def forward(self, x): pre_features = self.pre_conv(x) @@ -200,24 +228,36 @@ def __init__(self, RefinementStageBlock(mid_channels, mid_channels, norm_cfg)) self.cm_out_conv = nn.Sequential( ConvModule( - mid_channels, mid_channels, 1, padding=0, norm_cfg=None), + mid_channels, + mid_channels, + 1, + padding=0, + norm_cfg=None, + bias=True), ConvModule( mid_channels, out_channels_cm, 1, padding=0, norm_cfg=None, - act_cfg=None)) + act_cfg=None, + bias=True)) self.paf_out_conv = nn.Sequential( ConvModule( - mid_channels, mid_channels, 1, padding=0, norm_cfg=None), + mid_channels, + mid_channels, + 1, + padding=0, + norm_cfg=None, + bias=True), ConvModule( mid_channels, out_channels_paf, 1, padding=0, norm_cfg=None, - act_cfg=None)) + act_cfg=None, + bias=True)) def forward(self, x): features = self.feat(x) diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index af06e1235b..3a49fbc0ef 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -74,22 +74,28 @@ def __init__(self, assert self.num_stages >= 1 self.features = nn.Sequential( - ConvModule(in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), + ConvModule( + in_channels, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), ConvModule( - 256, stem_feat_channels, 3, padding=1, norm_cfg=norm_cfg)) + 256, + stem_feat_channels, + 3, + padding=1, + norm_cfg=norm_cfg, + bias=True)) # stage 0 self.cm_stages = nn.ModuleList([ diff --git a/mmpose/models/backbones/openpose_v2.py b/mmpose/models/backbones/openpose_v2.py index b5ee248eaa..4166c698f7 100644 --- a/mmpose/models/backbones/openpose_v2.py +++ b/mmpose/models/backbones/openpose_v2.py @@ -184,29 +184,43 @@ def __init__(self, assert self.num_stages >= 1 self.features = nn.Sequential( - ConvModule(in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), + ConvModule( + in_channels, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), ConvModule( - 512, 512, 3, padding=1, norm_cfg=norm_cfg, act_cfg=act_cfg), + 512, + 512, + 3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + bias=True), ConvModule( - 512, 256, 3, padding=1, norm_cfg=norm_cfg, act_cfg=act_cfg), + 512, + 256, + 3, + padding=1, + norm_cfg=norm_cfg, + act_cfg=act_cfg, + bias=True), ConvModule( 256, stem_feat_channels, 3, padding=1, norm_cfg=norm_cfg, - act_cfg=act_cfg)) + act_cfg=act_cfg, + bias=True)) self.stages = nn.ModuleList() self.out_convs = nn.ModuleList() From d7fec8921c2f1260db522952cfde47cc4f1674f0 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Fri, 30 Jul 2021 22:53:36 +0800 Subject: [PATCH 66/98] fix with_bg config --- .../part_affinity_field/coco/openpose_sn_coco_368x368.py | 2 +- .../part_affinity_field/coco/openpose_v1_coco_368x368.py | 2 +- .../part_affinity_field/coco/openpose_v2_coco_368x368.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py index 79652ca333..3bf0c84b69 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_sn_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, - with_bg=True) + with_bg=False) # model settings model = dict( diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py index 658abdb0be..7e7156e8ca 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v1_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, - with_bg=True) + with_bg=False) # model settings model = dict( diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py index e85fb68d9e..fcda6a04f5 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368.py @@ -45,7 +45,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, - with_bg=True) + with_bg=False) # model settings model = dict( From 734152828cd6c4260b93aad00ae275a1b35b49bf Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sat, 31 Jul 2021 22:59:52 +0800 Subject: [PATCH 67/98] fix paf --- mmpose/apis/inference.py | 51 ++++++++++++++++++++-------- mmpose/core/post_processing/group.py | 5 ++- 2 files changed, 40 insertions(+), 16 deletions(-) diff --git a/mmpose/apis/inference.py b/mmpose/apis/inference.py index 77cb710048..2ba1b2eb47 100644 --- a/mmpose/apis/inference.py +++ b/mmpose/apis/inference.py @@ -460,22 +460,40 @@ def inference_bottom_up_pose_model(model, test_pipeline = Compose(test_pipeline) # prepare data - data = { - 'img_or_path': img_or_path, - 'dataset': 'coco', - 'ann_info': { - 'image_size': - cfg.data_cfg['image_size'], - 'num_joints': - cfg.data_cfg['num_joints'], - 'flip_index': - [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15], - 'skeleton': [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], - [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], - [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], - [3, 5], [4, 6]] + if 1: + data = { + 'img_or_path': img_or_path, + 'dataset': 'coco', + 'ann_info': { + 'image_size': + cfg.data_cfg['image_size'], + 'num_joints': + cfg.data_cfg['num_joints'], + 'flip_index': + [0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16], + 'skeleton': [[1, 8], [8, 9], [9, 10], [1, 11], [11, 12], + [12, 13], [1, 2], [2, 3], [3, 4], [2, 16], [1, 5], + [5, 6], [6, 7], [5, 17], [1, 0], [0, 14], [0, 15], + [14, 16], [15, 17]] + } + } + else: + data = { + 'img_or_path': img_or_path, + 'dataset': 'coco', + 'ann_info': { + 'image_size': + cfg.data_cfg['image_size'], + 'num_joints': + cfg.data_cfg['num_joints'], + 'flip_index': + [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15], + 'skeleton': [[15, 13], [13, 11], [16, 14], [14, 12], [11, 12], + [5, 11], [6, 12], [5, 6], [5, 7], [6, 8], [7, 9], + [8, 10], [1, 2], [0, 1], [0, 2], [1, 3], [2, 4], + [3, 5], [4, 6]] + } } - } data = test_pipeline(data) data = collate([data], samples_per_gpu=1) @@ -500,7 +518,10 @@ def inference_bottom_up_pose_model(model, returned_outputs.append(h.layer_outputs) + order_map = [0, 15, 14, 17, 16, 5, 2, 6, 3, 7, 4, 11, 8, 12, 9, 13, 10] for idx, pred in enumerate(result['preds']): + if cfg.data_cfg['add_neck']: + pred = pred[order_map] area = (np.max(pred[:, 0]) - np.min(pred[:, 0])) * ( np.max(pred[:, 1]) - np.min(pred[:, 1])) pose_results.append({ diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index d18c222950..3a9829869f 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -121,7 +121,10 @@ class _Params: """ def __init__(self, cfg): - self.num_joints = cfg['num_joints'] + if cfg['add_neck']: + self.num_joints = cfg['num_joints'] + 1 + else: + self.num_joints = cfg['num_joints'] self.max_num_people = cfg['max_num_people'] self.detection_threshold = cfg['detection_threshold'] self.ignore_too_much = cfg['ignore_too_much'] From e74650dcc00ae6857ff6533a95b6623da764aece Mon Sep 17 00:00:00 2001 From: jinsheng Date: Sat, 31 Jul 2021 23:01:58 +0800 Subject: [PATCH 68/98] update config --- ...openpose_coco_368x368_withbg_addneck_lr.py | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py new file mode 100644 index 0000000000..74255f5fd8 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py @@ -0,0 +1,183 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.00015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True, + add_neck=True, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/mobilenetv1_sgd_68.848.pth', + backbone=dict( + type='LightweightOpenPoseNetwork', + in_channels=3, + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + heatmap_index=[0, 1], + paf_index=[2, 3], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'], + add_neck=data_cfg['add_neck'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + add_neck=data_cfg['add_neck'], + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 2 + [1] * 2, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 3120eb335ab25898c9ce938ba68b99c4cccf0241 Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 2 Aug 2021 09:40:32 +0800 Subject: [PATCH 69/98] gamma 0.333 --- .../coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py | 1 + 1 file changed, 1 insertion(+) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py index 74255f5fd8..33cb1958e8 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py @@ -14,6 +14,7 @@ # learning policy lr_config = dict( policy='step', + gamma=0.333, warmup='linear', warmup_iters=500, warmup_ratio=0.001, From fcca84a5afebc80324789236d31da02f5af774ac Mon Sep 17 00:00:00 2001 From: jinsheng Date: Mon, 2 Aug 2021 09:50:03 +0800 Subject: [PATCH 70/98] sgd config --- .../openpose_v2_coco_368x368_withbg_sgd.py | 183 ++++++++++++++++++ 1 file changed, 183 insertions(+) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py new file mode 100644 index 0000000000..75e3d76d65 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py @@ -0,0 +1,183 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='SGD', + lr=0.01, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg19_bn', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + # additional channel for bg + out_channels_cm=17 + 1, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 5, + heatmap_index=[5], + paf_index=[0, 1, 2, 3, 4], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 5, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 6f302d757bb8bbdd875ac74d0b1ba13a22b7ec03 Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 2 Aug 2021 15:55:56 +0800 Subject: [PATCH 71/98] fix MaskedMSELoss & add supervise_empty --- mmpose/models/losses/mse_loss.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/mmpose/models/losses/mse_loss.py b/mmpose/models/losses/mse_loss.py index 693c723237..8586092059 100644 --- a/mmpose/models/losses/mse_loss.py +++ b/mmpose/models/losses/mse_loss.py @@ -159,21 +159,28 @@ class MaskedMSELoss(nn.Module): Args: use_mask (bool): Option to use mask of target. Default: True. loss_weight (float): Weight of the loss. Default: 1.0. + supervise_empty (bool): Whether to supervise empty channels. """ - def __init__(self, use_mask=True, loss_weight=1.): + def __init__(self, use_mask=True, loss_weight=1., supervise_empty=True): super().__init__() self.criterion = nn.MSELoss() self.use_mask = use_mask self.loss_weight = loss_weight + self.supervise_empty = supervise_empty def forward(self, output, target, mask): """Forward function.""" assert output.size() == target.size() if self.use_mask: - loss = self.criterion( - output, target) * mask[:, None, :, :].expand_as(output) + if not self.supervise_empty: + empty_mask = (target.sum(dim=[2, 3], keepdim=True) > 0).float() + mask = empty_mask.expand_as( + output) * mask[:, None, :, :].expand_as(output) + else: + mask = mask[:, None, :, :].expand_as(output) + loss = self.criterion(output * mask, target * mask) else: loss = self.criterion(output, target) From 842db4f22007fa530dd07e7d11bb2af29b002276 Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 2 Aug 2021 15:57:58 +0800 Subject: [PATCH 72/98] fix add_neck --- mmpose/core/post_processing/group.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/mmpose/core/post_processing/group.py b/mmpose/core/post_processing/group.py index 3a9829869f..2d443205c8 100644 --- a/mmpose/core/post_processing/group.py +++ b/mmpose/core/post_processing/group.py @@ -121,7 +121,8 @@ class _Params: """ def __init__(self, cfg): - if cfg['add_neck']: + self.add_neck = cfg.get('add_neck', False) + if self.add_neck: self.num_joints = cfg['num_joints'] + 1 else: self.num_joints = cfg['num_joints'] From 0aea67b391918714b508921b87c764f63953740c Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 2 Aug 2021 16:10:56 +0800 Subject: [PATCH 73/98] cfg of paf wholebody withbg + pretrain + supervise_empty --- ...enpose_v1_coco_wholebody_480x480_withbg.py | 179 ++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py new file mode 100644 index 0000000000..14f28b88d9 --- /dev/null +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py @@ -0,0 +1,179 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + # dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=133, + dataset_channel=[ + list(range(133)), + ], + inference_channel=list(range(133))) + +data_cfg = dict( + image_size=480, + base_size=256, + base_sigma=2, + heatmap_size=[60], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/openpose_v1_coco_368x368/best.pth', + backbone=dict( + type='OpenPoseNetworkV1', + in_channels=3, + out_channels_cm=133, + out_channels_paf=270, + stem_feat_channels=128, + num_stages=6), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=False)), + ] * 6, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=False)), + ] * 6, + heatmap_index=[0, 1, 2, 3, 4, 5], + paf_index=[6, 7, 8, 9, 10, 11], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 6 + [1] * 6, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=8, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_train_v1.0.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From a4dedbdaa1af790d60a452ab8e43a8efe206cae8 Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 2 Aug 2021 16:41:28 +0800 Subject: [PATCH 74/98] update lr --- .../openpose_v1_coco_wholebody_480x480_withbg.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py index 14f28b88d9..3b9031a297 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py @@ -8,7 +8,7 @@ optimizer = dict( type='Adam', - lr=0.0015, + lr=0.00015, ) optimizer_config = dict(grad_clip=None) # learning policy @@ -156,7 +156,7 @@ data_root = 'data/coco' data = dict( - samples_per_gpu=8, + samples_per_gpu=24, workers_per_gpu=2, train=dict( type='BottomUpCocoWholeBodyDataset', From 43b887cb74378e3cda4960e81c75450d3fba8da6 Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 2 Aug 2021 16:51:33 +0800 Subject: [PATCH 75/98] fix cfg --- .../openpose_v1_coco_wholebody_480x480_withbg.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py index 3b9031a297..c34bee8388 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py @@ -14,6 +14,7 @@ # learning policy lr_config = dict( policy='step', + gamma=0.333, warmup='linear', warmup_iters=500, warmup_ratio=0.001, @@ -52,7 +53,7 @@ backbone=dict( type='OpenPoseNetworkV1', in_channels=3, - out_channels_cm=133, + out_channels_cm=134, out_channels_paf=270, stem_feat_channels=128, num_stages=6), @@ -156,7 +157,7 @@ data_root = 'data/coco' data = dict( - samples_per_gpu=24, + samples_per_gpu=8, workers_per_gpu=2, train=dict( type='BottomUpCocoWholeBodyDataset', From ebfa42f5738e8c0d6a3eedd740f325754e3dd4f1 Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 2 Aug 2021 17:00:18 +0800 Subject: [PATCH 76/98] fix cfg --- .../coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py index c34bee8388..020bc9e611 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py @@ -157,7 +157,7 @@ data_root = 'data/coco' data = dict( - samples_per_gpu=8, + samples_per_gpu=24, workers_per_gpu=2, train=dict( type='BottomUpCocoWholeBodyDataset', From c64d0ce8a43ddd17417a1bc5d7a22e99ec91651f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=91=E6=99=9F?= Date: Tue, 3 Aug 2021 14:05:16 +0800 Subject: [PATCH 77/98] update configs --- ...k.py => lightweight_openpose_coco_368x368_withbg_addneck.py} | 2 +- .../coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py | 2 +- .../coco/openpose_v2_coco_368x368_withbg_sgd.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) rename configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/{lightweight_openpose_coco_368x368_addneck.py => lightweight_openpose_coco_368x368_withbg_addneck.py} (99%) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck.py similarity index 99% rename from configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py rename to configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck.py index 807bc88968..af29f3d682 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_addneck.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck.py @@ -23,7 +23,7 @@ interval=50, hooks=[ dict(type='TextLoggerHook'), - # dict(type='TensorboardLoggerHook') + dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py index 33cb1958e8..0b25b0830f 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py @@ -24,7 +24,7 @@ interval=50, hooks=[ dict(type='TextLoggerHook'), - # dict(type='TensorboardLoggerHook') + dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py index 75e3d76d65..a33e52098d 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_sgd.py @@ -23,7 +23,7 @@ interval=50, hooks=[ dict(type='TextLoggerHook'), - # dict(type='TensorboardLoggerHook') + dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( From 8884ddd7a03b39f91708bcd7f87d17ad5937f053 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=87=91=E6=99=9F?= Date: Tue, 3 Aug 2021 14:11:45 +0800 Subject: [PATCH 78/98] update configs --- .../coco/openpose_v2_coco_368x368_withbg.py | 2 +- ...openpose_v2_coco_368x368_withbg_addneck.py | 187 ++++++++++++++++++ 2 files changed, 188 insertions(+), 1 deletion(-) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_addneck.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py index 1af548613b..0b1020d6bd 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg.py @@ -23,7 +23,7 @@ interval=50, hooks=[ dict(type='TextLoggerHook'), - # dict(type='TensorboardLoggerHook') + dict(type='TensorboardLoggerHook') ]) channel_cfg = dict( diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_addneck.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_addneck.py new file mode 100644 index 0000000000..aa3f470da0 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/openpose_v2_coco_368x368_withbg_addneck.py @@ -0,0 +1,187 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[ + dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook') + ]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True, + add_neck=True +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg19_bn', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + # additional channel for bg + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 5, + heatmap_index=[5], + paf_index=[0, 1, 2, 3, 4], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'], + add_neck=data_cfg['add_neck'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + add_neck=data_cfg['add_neck'], + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 5, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 7a0b86d76bb01b57c075117893116e726cb8b483 Mon Sep 17 00:00:00 2001 From: Jas Date: Tue, 3 Aug 2021 19:58:42 +0800 Subject: [PATCH 79/98] add configs --- ...se_coco_368x368_withbg_addneck_lr00015.py} | 6 +- ...npose_coco_368x368_withbg_addneck_lr015.py | 181 ++++++++++++++++++ ...ose_coco_368x368_withbg_addneck_meanstd.py | 180 +++++++++++++++++ 3 files changed, 363 insertions(+), 4 deletions(-) rename configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/{lightweight_openpose_coco_368x368_withbg_addneck_lr.py => lightweight_openpose_coco_368x368_withbg_addneck_lr00015.py} (98%) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr015.py create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr00015.py similarity index 98% rename from configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py rename to configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr00015.py index 0b25b0830f..7e91e6f004 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr00015.py @@ -22,10 +22,8 @@ total_epochs = 300 log_config = dict( interval=50, - hooks=[ - dict(type='TextLoggerHook'), - dict(type='TensorboardLoggerHook') - ]) + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) channel_cfg = dict( dataset_joints=17, diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr015.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr015.py new file mode 100644 index 0000000000..00f11dd14e --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_lr015.py @@ -0,0 +1,181 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True, + add_neck=True, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/mobilenetv1_sgd_68.848.pth', + backbone=dict( + type='LightweightOpenPoseNetwork', + in_channels=3, + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + heatmap_index=[0, 1], + paf_index=[2, 3], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'], + add_neck=data_cfg['add_neck'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + add_neck=data_cfg['add_neck'], + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 2 + [1] * 2, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py new file mode 100644 index 0000000000..e80831f607 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py @@ -0,0 +1,180 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True, + add_neck=True, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/mobilenetv1_sgd_68.848.pth', + backbone=dict( + type='LightweightOpenPoseNetwork', + in_channels=3, + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + heatmap_index=[0, 1], + paf_index=[2, 3], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'], + add_neck=data_cfg['add_neck'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + add_neck=data_cfg['add_neck'], + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 2 + [1] * 2, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', mean=[0.5, 0.5, 0.5], std=[1., 1., + 1.]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 4cdaa416ac96c5b4a3c50602ed45314c45f8beb6 Mon Sep 17 00:00:00 2001 From: Jas Date: Tue, 3 Aug 2021 20:51:49 +0800 Subject: [PATCH 80/98] update configs --- ...oco_368x368_withbg_addneck_rgb_meanstd.py} | 9 +- ...68x368_withbg_addneck_rgb_meanstd_lr015.py | 177 ++++++++++++++++++ 2 files changed, 180 insertions(+), 6 deletions(-) rename configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/{lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py => lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py} (96%) create mode 100644 configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py similarity index 96% rename from configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py rename to configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py index e80831f607..32c2800b07 100644 --- a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_meanstd.py +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py @@ -100,7 +100,7 @@ add_neck=data_cfg['add_neck'])) train_pipeline = [ - dict(type='LoadImageFromFile'), + dict(type='LoadImageFromFile', channel_order='bgr'), dict( type='BottomUpRandomAffine', rot_factor=30, @@ -109,10 +109,7 @@ trans_factor=40), dict(type='BottomUpRandomFlip', flip_prob=0.5), dict(type='ToTensor'), - dict( - type='NormalizeTensor', - mean=[0.485, 0.456, 0.406], - std=[0.229, 0.224, 0.225]), + dict(type='NormalizeTensor', mean=[0.5, 0.5, 0.5], std=[1., 1., 1.]), dict( type='MultitaskGatherTarget', pipeline_list=[ @@ -134,7 +131,7 @@ ] val_pipeline = [ - dict(type='LoadImageFromFile'), + dict(type='LoadImageFromFile', channel_order='bgr'), dict(type='BottomUpGetImgSize', test_scale_factor=[1]), dict( type='BottomUpResizeAlign', diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py new file mode 100644 index 0000000000..eb4c160478 --- /dev/null +++ b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py @@ -0,0 +1,177 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=17, + dataset_channel=[ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + ], + inference_channel=[ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 + ]) + +data_cfg = dict( + image_size=368, + base_size=256, + base_sigma=2, + heatmap_size=[46], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True, + add_neck=True, +) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/mobilenetv1_sgd_68.848.pth', + backbone=dict( + type='LightweightOpenPoseNetwork', + in_channels=3, + out_channels_cm=19, + out_channels_paf=38, + stem_feat_channels=128, + num_stages=2), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict(type='MaskedMSELoss', )), + ] * 2, + heatmap_index=[0, 1], + paf_index=[2, 3], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'], + add_neck=data_cfg['add_neck'])) + +train_pipeline = [ + dict(type='LoadImageFromFile', channel_order='bgr'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict(type='NormalizeTensor', mean=[0.5, 0.5, 0.5], std=[1., 1., 1.]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + add_neck=data_cfg['add_neck'], + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] * 2 + [1] * 2, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile', channel_order='bgr'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', mean=[0.5, 0.5, 0.5], std=[1., 1., + 1.]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_train2017.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoDataset', + ann_file=f'{data_root}/annotations/person_keypoints_val2017.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 03a9e62eb943ca3193a60e287be9794f514dfa7a Mon Sep 17 00:00:00 2001 From: Jas Date: Tue, 3 Aug 2021 20:52:55 +0800 Subject: [PATCH 81/98] update configs --- ...ghtweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd.py} | 0 ...ght_openpose_coco_368x368_withbg_addneck_bgr_meanstd_lr015.py} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/{lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py => lightweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd.py} (100%) rename configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/{lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py => lightweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd_lr015.py} (100%) diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd.py similarity index 100% rename from configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd.py rename to configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd.py diff --git a/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py b/configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd_lr015.py similarity index 100% rename from configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_rgb_meanstd_lr015.py rename to configs/body/2d_kpt_sview_rgb_img/part_affinity_field/coco/lightweight_openpose_coco_368x368_withbg_addneck_bgr_meanstd_lr015.py From 7efc779fedcfe32a0e20166c0e3bb6f2258a5758 Mon Sep 17 00:00:00 2001 From: Jas Date: Tue, 3 Aug 2021 22:52:18 +0800 Subject: [PATCH 82/98] fix unittest --- mmpose/apis/inference.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mmpose/apis/inference.py b/mmpose/apis/inference.py index 2ba1b2eb47..0cd989c18e 100644 --- a/mmpose/apis/inference.py +++ b/mmpose/apis/inference.py @@ -460,7 +460,7 @@ def inference_bottom_up_pose_model(model, test_pipeline = Compose(test_pipeline) # prepare data - if 1: + if cfg.data_cfg.get('add_neck', False): data = { 'img_or_path': img_or_path, 'dataset': 'coco', From 21990540de20aa294d28ba434fe4fbc12869692f Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 6 Aug 2021 17:26:24 +0800 Subject: [PATCH 83/98] paf wholebody with hrnet/openposev2 backone --- ...hrnet_w32_coco_wholebody_480x480_withbg.py | 210 ++++++++++++++++++ ...enpose_v2_coco_wholebody_480x480_withbg.py | 182 +++++++++++++++ 2 files changed, 392 insertions(+) create mode 100644 configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py create mode 100644 configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py new file mode 100644 index 0000000000..e6ffee4887 --- /dev/null +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py @@ -0,0 +1,210 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + gamma=0.333, + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=133, + dataset_channel=[ + list(range(133)), + ], + inference_channel=list(range(133))) + +data_cfg = dict( + image_size=480, + base_size=256, + base_sigma=2, + heatmap_size=[120], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/hrnet_w32_coco_512x512/best.pth', + backbone=dict( + type='HRNet', + in_channels=3, + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + ), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=134, + num_deconv_layers=0, + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=False)), + ], + paf_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=270, + num_deconv_layers=0, + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=False)), + ], + heatmap_index=[0], + paf_index=[0], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0, 1], + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_train_v1.0.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py new file mode 100644 index 0000000000..17829579fc --- /dev/null +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py @@ -0,0 +1,182 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + gamma=0.333, + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=133, + dataset_channel=[ + list(range(133)), + ], + inference_channel=list(range(133))) + +data_cfg = dict( + image_size=480, + base_size=256, + base_sigma=2, + heatmap_size=[60], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=True) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='models/openpose_v2_coco_368x368/best.pth', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + # additional channel for bg + out_channels_cm=134, + out_channels_paf=270, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=False)), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=False)), + ] * 5, + heatmap_index=[5], + paf_index=[0, 1, 2, 3, 4], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 5, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_train_v1.0.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From 954a982245f2b72a80aebe71343c94bc4c1b52ad Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 6 Aug 2021 17:44:58 +0800 Subject: [PATCH 84/98] update cfg --- .../coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py index 17829579fc..e83f4aa6b7 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py @@ -159,7 +159,7 @@ data_root = 'data/coco' data = dict( - samples_per_gpu=24, + samples_per_gpu=16, workers_per_gpu=2, train=dict( type='BottomUpCocoWholeBodyDataset', From 55308cd1fee09e58d5e96a9e2eaf6dc65984a4b0 Mon Sep 17 00:00:00 2001 From: luminxu Date: Sun, 15 Aug 2021 16:47:40 +0800 Subject: [PATCH 85/98] preserve kpt score & wholebody part score --- .../core/post_processing/post_transforms.py | 2 +- .../bottom_up/bottom_up_coco_wholebody.py | 28 ++++++++++++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/mmpose/core/post_processing/post_transforms.py b/mmpose/core/post_processing/post_transforms.py index ba6594f778..96091daa3e 100644 --- a/mmpose/core/post_processing/post_transforms.py +++ b/mmpose/core/post_processing/post_transforms.py @@ -186,7 +186,7 @@ def transform_preds(coords, center, scale, output_size, use_udp=False): scale_x = scale[0] / output_size[0] scale_y = scale[1] / output_size[1] - target_coords = np.ones_like(coords) + target_coords = coords.copy() target_coords[:, 0] = coords[:, 0] * scale_x + center[0] - scale[0] * 0.5 target_coords[:, 1] = coords[:, 1] * scale_y + center[1] - scale[1] * 0.5 diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py index 681329a4d0..48cec77d6a 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py @@ -203,6 +203,22 @@ def _get_joints(self, anno): return joints + def _get_part_score(self, keypoints): + """Get part score for new evaluation tools.""" + kpt_score = 0 + valid_num = 0 + num_joints = int(len(keypoints) / 3) + for n_jt in range(0, num_joints): + t_s = keypoints[n_jt * 3 + 2] + if t_s > 0: + kpt_score = kpt_score + t_s + valid_num = valid_num + 1 + if valid_num != 0: + kpt_score = kpt_score / valid_num + part_score = kpt_score + + return float(part_score) + def _coco_keypoint_results_one_category_kernel(self, data_pack): """Get coco keypoint results.""" cat_id = data_pack['cat_id'] @@ -247,7 +263,17 @@ def _coco_keypoint_results_one_category_kernel(self, data_pack): 'righthand_kpts': key_point[cuts[4]:cuts[5]].tolist(), 'score': - img_kpt['score'], + self._get_part_score(key_point[cuts[0]:cuts[1]]), + 'foot_score': + self._get_part_score(key_point[cuts[1]:cuts[2]]), + 'face_score': + self._get_part_score(key_point[cuts[2]:cuts[3]]), + 'lefthand_score': + self._get_part_score(key_point[cuts[3]:cuts[4]]), + 'righthand_score': + self._get_part_score(key_point[cuts[4]:cuts[5]]), + 'wholebody_score': + self._get_part_score(key_point), 'bbox': [left_top[0], left_top[1], w, h] }) From 2b73bc9b6c7a39814b418fa5c007200fa596b6cb Mon Sep 17 00:00:00 2001 From: luminxu Date: Sun, 15 Aug 2021 17:24:02 +0800 Subject: [PATCH 86/98] remove bias in openpose v1 --- .../openpose_v1_coco_wholebody_480x480.py | 7 +++--- mmpose/models/backbones/openpose_v1.py | 25 +++++++++---------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py index f61b386959..b52a113dfa 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py @@ -43,7 +43,7 @@ inference_channel=channel_cfg['inference_channel'], num_scales=1, scale_aware_sigma=False, -) + with_bg=False) # model settings model = dict( @@ -93,7 +93,8 @@ ignore_too_much=False, adjust=True, refine=True, - flip_test=True)) + flip_test=True, + with_bg=data_cfg['with_bg'])) train_pipeline = [ dict(type='LoadImageFromFile'), @@ -116,7 +117,7 @@ dict( type='BottomUpGenerateHeatmapTarget', sigma=2, - with_bg=False) + with_bg=data_cfg['with_bg']) ], [dict( type='BottomUpGeneratePAFTarget', diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index 3a49fbc0ef..a109791458 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -75,27 +75,26 @@ def __init__(self, self.features = nn.Sequential( ConvModule( - in_channels, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), + in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), ConvModule( 256, stem_feat_channels, 3, padding=1, - norm_cfg=norm_cfg, - bias=True)) + norm_cfg=norm_cfg)) # stage 0 self.cm_stages = nn.ModuleList([ From e1d442bc533bd00dd0b7a194038c303e562bc994 Mon Sep 17 00:00:00 2001 From: luminxu Date: Sun, 15 Aug 2021 17:35:28 +0800 Subject: [PATCH 87/98] add bias in openpose v1 --- mmpose/models/backbones/openpose_v1.py | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index a109791458..3a49fbc0ef 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -75,26 +75,27 @@ def __init__(self, self.features = nn.Sequential( ConvModule( - in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), + in_channels, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), ConvModule( 256, stem_feat_channels, 3, padding=1, - norm_cfg=norm_cfg)) + norm_cfg=norm_cfg, + bias=True)) # stage 0 self.cm_stages = nn.ModuleList([ From d428f63738f4afde4b45e09d9e40167ecf31a16e Mon Sep 17 00:00:00 2001 From: luminxu Date: Sun, 15 Aug 2021 23:47:49 +0800 Subject: [PATCH 88/98] update part score --- .../bottom_up/bottom_up_coco_wholebody.py | 4 +-- mmpose/models/backbones/openpose_v1.py | 25 +++++++++---------- 2 files changed, 14 insertions(+), 15 deletions(-) diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py index 48cec77d6a..a65da206c0 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py @@ -210,7 +210,7 @@ def _get_part_score(self, keypoints): num_joints = int(len(keypoints) / 3) for n_jt in range(0, num_joints): t_s = keypoints[n_jt * 3 + 2] - if t_s > 0: + if t_s > 0.2: kpt_score = kpt_score + t_s valid_num = valid_num + 1 if valid_num != 0: @@ -273,7 +273,7 @@ def _coco_keypoint_results_one_category_kernel(self, data_pack): 'righthand_score': self._get_part_score(key_point[cuts[4]:cuts[5]]), 'wholebody_score': - self._get_part_score(key_point), + img_kpt['score'], 'bbox': [left_top[0], left_top[1], w, h] }) diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index 3a49fbc0ef..a109791458 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -75,27 +75,26 @@ def __init__(self, self.features = nn.Sequential( ConvModule( - in_channels, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), + in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), - ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), ConvModule( 256, stem_feat_channels, 3, padding=1, - norm_cfg=norm_cfg, - bias=True)) + norm_cfg=norm_cfg)) # stage 0 self.cm_stages = nn.ModuleList([ From cd758516fddc38db516c12c59500f0eddceac76e Mon Sep 17 00:00:00 2001 From: luminxu Date: Mon, 16 Aug 2021 10:39:27 +0800 Subject: [PATCH 89/98] multi scale test --- .../openpose_v1_coco_wholebody_480x480.py | 4 ++-- .../bottom_up/bottom_up_coco_wholebody.py | 22 ++++++++++--------- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py index b52a113dfa..cd34eb9f3a 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480.py @@ -79,7 +79,7 @@ test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, - scale_factor=[1], + scale_factor=[0.5, 1, 1.5, 2, 2.5], with_heatmaps=[True], with_pafs=[True], project2image=True, @@ -131,7 +131,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5]), dict( type='BottomUpResizeAlign', transforms=[ diff --git a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py index a65da206c0..0aac6f1c38 100644 --- a/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py +++ b/mmpose/datasets/datasets/bottom_up/bottom_up_coco_wholebody.py @@ -263,17 +263,19 @@ def _coco_keypoint_results_one_category_kernel(self, data_pack): 'righthand_kpts': key_point[cuts[4]:cuts[5]].tolist(), 'score': - self._get_part_score(key_point[cuts[0]:cuts[1]]), - 'foot_score': - self._get_part_score(key_point[cuts[1]:cuts[2]]), - 'face_score': - self._get_part_score(key_point[cuts[2]:cuts[3]]), - 'lefthand_score': - self._get_part_score(key_point[cuts[3]:cuts[4]]), - 'righthand_score': - self._get_part_score(key_point[cuts[4]:cuts[5]]), - 'wholebody_score': img_kpt['score'], + # 'score': + # self._get_part_score(key_point[cuts[0]:cuts[1]]), + # 'foot_score': + # self._get_part_score(key_point[cuts[1]:cuts[2]]), + # 'face_score': + # self._get_part_score(key_point[cuts[2]:cuts[3]]), + # 'lefthand_score': + # self._get_part_score(key_point[cuts[3]:cuts[4]]), + # 'righthand_score': + # self._get_part_score(key_point[cuts[4]:cuts[5]]), + # 'wholebody_score': + # img_kpt['score'], 'bbox': [left_top[0], left_top[1], w, h] }) From 6f7b9a1ae538e211d44e0ee20ab95a0457340e35 Mon Sep 17 00:00:00 2001 From: luminxu Date: Tue, 17 Aug 2021 11:11:51 +0800 Subject: [PATCH 90/98] multi scale test --- ...hrnet_w32_coco_wholebody_480x480_withbg.py | 4 +-- ...enpose_v1_coco_wholebody_480x480_withbg.py | 4 +-- ...enpose_v2_coco_wholebody_480x480_withbg.py | 4 +-- mmpose/models/backbones/openpose_v1.py | 25 ++++++++++--------- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py index e6ffee4887..2aa4f9ed0e 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480_withbg.py @@ -112,7 +112,7 @@ test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, - scale_factor=[1], + scale_factor=[0.5, 1, 1.5, 2, 2.5], with_heatmaps=[True], with_pafs=[True], project2image=True, @@ -164,7 +164,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5]), dict( type='BottomUpResizeAlign', transforms=[ diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py index 020bc9e611..2fd5fc4d28 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v1_coco_wholebody_480x480_withbg.py @@ -82,7 +82,7 @@ test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, - scale_factor=[1], + scale_factor=[0.5, 1, 1.5, 2, 2.5], with_heatmaps=[True], with_pafs=[True], project2image=True, @@ -134,7 +134,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5]), dict( type='BottomUpResizeAlign', transforms=[ diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py index e83f4aa6b7..46f39ad716 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py @@ -84,7 +84,7 @@ test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, - scale_factor=[1], + scale_factor=[0.5, 1, 1.5, 2, 2.5], with_heatmaps=[True], with_pafs=[True], project2image=True, @@ -136,7 +136,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5]), dict( type='BottomUpResizeAlign', transforms=[ diff --git a/mmpose/models/backbones/openpose_v1.py b/mmpose/models/backbones/openpose_v1.py index a109791458..3a49fbc0ef 100644 --- a/mmpose/models/backbones/openpose_v1.py +++ b/mmpose/models/backbones/openpose_v1.py @@ -75,26 +75,27 @@ def __init__(self, self.features = nn.Sequential( ConvModule( - in_channels, 64, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg), + in_channels, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(64, 64, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(128, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(256, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), nn.MaxPool2d(kernel_size=2, stride=2, padding=0), - ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg), - ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg), + ConvModule(256, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(512, 512, 3, padding=1, norm_cfg=norm_cfg, bias=True), + ConvModule(512, 256, 3, padding=1, norm_cfg=norm_cfg, bias=True), ConvModule( 256, stem_feat_channels, 3, padding=1, - norm_cfg=norm_cfg)) + norm_cfg=norm_cfg, + bias=True)) # stage 0 self.cm_stages = nn.ModuleList([ From 531032a0fbb9b3c2b301493cc093abf52127fd24 Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 18 Aug 2021 11:25:11 +0800 Subject: [PATCH 91/98] openpose v2 wholebody --- .../openpose_v2_coco_wholebody_480x480.py | 180 ++++++++++++++++++ mmpose/models/losses/mse_loss.py | 16 +- 2 files changed, 189 insertions(+), 7 deletions(-) create mode 100644 configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py new file mode 100644 index 0000000000..03e1ce69a5 --- /dev/null +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py @@ -0,0 +1,180 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=133, + dataset_channel=[ + list(range(133)), + ], + inference_channel=list(range(133))) + +data_cfg = dict( + image_size=480, + base_size=256, + base_sigma=2, + heatmap_size=[60], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=False) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='mmcls://vgg16_bn', + backbone=dict( + type='OpenPoseNetworkV2', + in_channels=3, + out_channels_cm=133, + out_channels_paf=270, + stem_feat_channels=128, + num_stages=6, + stage_types=('PAF', 'PAF', 'PAF', 'PAF', 'PAF', 'CM'), + num_blocks=5, + block_channels=96), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=True)), + ] * 1, + paf_heads_cfg=[ + dict( + type='DeconvHead', + num_deconv_layers=0, + extra=dict(final_conv_kernel=0), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=True)), + ] * 5, + heatmap_index=[5], + paf_index=[0, 1, 2, 3, 4], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0] + [1] * 5, + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=16, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_train_v1.0.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) diff --git a/mmpose/models/losses/mse_loss.py b/mmpose/models/losses/mse_loss.py index 8586092059..910d97fcf5 100644 --- a/mmpose/models/losses/mse_loss.py +++ b/mmpose/models/losses/mse_loss.py @@ -174,13 +174,15 @@ def forward(self, output, target, mask): assert output.size() == target.size() if self.use_mask: - if not self.supervise_empty: - empty_mask = (target.sum(dim=[2, 3], keepdim=True) > 0).float() - mask = empty_mask.expand_as( - output) * mask[:, None, :, :].expand_as(output) - else: - mask = mask[:, None, :, :].expand_as(output) - loss = self.criterion(output * mask, target * mask) + loss = self.criterion( + output, target) * mask[:, None, :, :].expand_as(output) + # if not self.supervise_empty: + # empty_mask = (target.sum(dim=[2, 3], keepdim=True) > 0).float() + # mask = empty_mask.expand_as( + # output) * mask[:, None, :, :].expand_as(output) + # else: + # mask = mask[:, None, :, :].expand_as(output) + # loss = self.criterion(output * mask, target * mask) else: loss = self.criterion(output, target) From c200435666ed872823c9e7d542f687d15338bf0a Mon Sep 17 00:00:00 2001 From: luminxu Date: Wed, 18 Aug 2021 11:45:45 +0800 Subject: [PATCH 92/98] hrnet wholebody --- .../hrnet_w32_coco_wholebody_480x480.py | 210 ++++++++++++++++++ 1 file changed, 210 insertions(+) create mode 100644 configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py new file mode 100644 index 0000000000..dea7290571 --- /dev/null +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py @@ -0,0 +1,210 @@ +log_level = 'INFO' +load_from = None +resume_from = None +dist_params = dict(backend='nccl') +workflow = [('train', 1)] +checkpoint_config = dict(interval=50) +evaluation = dict(interval=50, metric='mAP', key_indicator='AP') + +optimizer = dict( + type='Adam', + lr=0.0015, +) +optimizer_config = dict(grad_clip=None) +# learning policy +lr_config = dict( + policy='step', + warmup='linear', + warmup_iters=500, + warmup_ratio=0.001, + step=[200, 260]) +total_epochs = 300 +log_config = dict( + interval=50, + hooks=[dict(type='TextLoggerHook'), + dict(type='TensorboardLoggerHook')]) + +channel_cfg = dict( + dataset_joints=133, + dataset_channel=[ + list(range(133)), + ], + inference_channel=list(range(133))) + +data_cfg = dict( + image_size=480, + base_size=256, + base_sigma=2, + heatmap_size=[120], + num_joints=channel_cfg['dataset_joints'], + dataset_channel=channel_cfg['dataset_channel'], + inference_channel=channel_cfg['inference_channel'], + num_scales=1, + scale_aware_sigma=False, + with_bg=False) + +# model settings +model = dict( + type='PartAffinityField', + pretrained='https://download.openmmlab.com/mmpose/' + 'pretrain_models/hrnet_w32-36af842e.pth', + backbone=dict( + type='HRNet', + in_channels=3, + extra=dict( + stage1=dict( + num_modules=1, + num_branches=1, + block='BOTTLENECK', + num_blocks=(4, ), + num_channels=(64, )), + stage2=dict( + num_modules=1, + num_branches=2, + block='BASIC', + num_blocks=(4, 4), + num_channels=(32, 64)), + stage3=dict( + num_modules=4, + num_branches=3, + block='BASIC', + num_blocks=(4, 4, 4), + num_channels=(32, 64, 128)), + stage4=dict( + num_modules=3, + num_branches=4, + block='BASIC', + num_blocks=(4, 4, 4, 4), + num_channels=(32, 64, 128, 256))), + ), + keypoint_head=dict( + type='PAFHead', + heatmap_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=133, + num_deconv_layers=0, + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=True)), + ], + paf_heads_cfg=[ + dict( + type='DeconvHead', + in_channels=32, + out_channels=270, + num_deconv_layers=0, + extra=dict( + final_conv_kernel=1, + num_conv_layers=1, + num_conv_kernels=(1, )), + loss_keypoint=dict( + type='MaskedMSELoss', supervise_empty=True)), + ], + heatmap_index=[0], + paf_index=[0], + ), + train_cfg=dict(), + test_cfg=dict( + num_joints=channel_cfg['dataset_joints'], + max_num_people=30, + scale_factor=[1], + with_heatmaps=[True], + with_pafs=[True], + project2image=True, + align_corners=False, + nms_kernel=5, + nms_padding=2, + tag_per_joint=True, + detection_threshold=0.1, + tag_threshold=1, + use_detection_val=True, + ignore_too_much=False, + adjust=True, + refine=True, + flip_test=True, + with_bg=data_cfg['with_bg'])) + +train_pipeline = [ + dict(type='LoadImageFromFile'), + dict( + type='BottomUpRandomAffine', + rot_factor=30, + scale_factor=[0.75, 1.5], + scale_type='short', + trans_factor=40), + dict(type='BottomUpRandomFlip', flip_prob=0.5), + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + dict( + type='MultitaskGatherTarget', + pipeline_list=[ + [ + dict( + type='BottomUpGenerateHeatmapTarget', + sigma=2, + with_bg=data_cfg['with_bg']) + ], + [dict( + type='BottomUpGeneratePAFTarget', + limb_width=1, + )], + ], + pipeline_indices=[0, 1], + keys=['targets', 'masks']), + dict(type='Collect', keys=['img', 'targets', 'masks'], meta_keys=[]), +] + +val_pipeline = [ + dict(type='LoadImageFromFile'), + dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict( + type='BottomUpResizeAlign', + transforms=[ + dict(type='ToTensor'), + dict( + type='NormalizeTensor', + mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]), + ]), + dict( + type='Collect', + keys=['img'], + meta_keys=[ + 'image_file', 'aug_data', 'test_scale_factor', 'base_size', + 'center', 'scale', 'flip_index', 'skeleton' + ]), +] + +test_pipeline = val_pipeline + +data_root = 'data/coco' +data = dict( + samples_per_gpu=24, + workers_per_gpu=2, + train=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_train_v1.0.json', + img_prefix=f'{data_root}/train2017/', + data_cfg=data_cfg, + pipeline=train_pipeline), + val=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), + test=dict( + type='BottomUpCocoWholeBodyDataset', + ann_file=f'{data_root}/annotations/coco_wholebody_val_v1.0.json', + img_prefix=f'{data_root}/val2017/', + data_cfg=data_cfg, + pipeline=val_pipeline), +) From d923291adc5b79de543bceb4538e38f4e1dc0c7f Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 20 Aug 2021 14:48:09 +0800 Subject: [PATCH 93/98] add max_input_size --- ...enpose_v2_coco_wholebody_480x480_withbg.py | 3 ++- .../datasets/pipelines/bottom_up_transform.py | 20 ++++++++++++++++--- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py index 46f39ad716..fbde8969d0 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py @@ -136,7 +136,8 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5], + max_input_size=1440), dict( type='BottomUpResizeAlign', transforms=[ diff --git a/mmpose/datasets/pipelines/bottom_up_transform.py b/mmpose/datasets/pipelines/bottom_up_transform.py index ca193fd3cb..461959483d 100644 --- a/mmpose/datasets/pipelines/bottom_up_transform.py +++ b/mmpose/datasets/pipelines/bottom_up_transform.py @@ -681,16 +681,19 @@ class BottomUpGetImgSize: `results['ann_info']['image_size']×current_scale`. Args: - test_scale_factor (List[float]): Multi scale + test_scale_factor (List[float]): Multi scale. + max_input_size (int): Constraint of the max input size. current_scale (int): default 1 use_udp (bool): To use unbiased data processing. Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased Data Processing for Human Pose Estimation (CVPR 2020). """ - def __init__(self, test_scale_factor, current_scale=1, use_udp=False): + def __init__(self, test_scale_factor, max_input_size=None, + current_scale=1, use_udp=False): self.test_scale_factor = test_scale_factor self.min_scale = min(test_scale_factor) + self.max_input_size = max_input_size self.current_scale = current_scale self.use_udp = use_udp @@ -731,7 +734,18 @@ def __call__(self, results): center = (scale_w / 2.0, scale_h / 2.0) else: center = np.array([round(w / 2.0), round(h / 2.0)]) - results['ann_info']['test_scale_factor'] = self.test_scale_factor + + # calculate the test scale factor + if self.max_input_size is not None: + test_scale_factor = np.array(self.test_scale_factor) + accept_scale_w = (test_scale_factor * w_resized) < self.max_input_size + accept_scale_h = (test_scale_factor * h_resized) < self.max_input_size + keep = (accept_scale_w * accept_scale_h) > 0 + test_scale_factor = test_scale_factor[keep].tolist() + else: + test_scale_factor = self.test_scale_factor + + results['ann_info']['test_scale_factor'] = test_scale_factor results['ann_info']['base_size'] = (w_resized, h_resized) results['ann_info']['center'] = center results['ann_info']['scale'] = np.array([scale_w, scale_h]) From b50eabf4b5dfa2819b4a57d66513f68e84d2857f Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 20 Aug 2021 17:00:35 +0800 Subject: [PATCH 94/98] add max_input_size --- .../coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py index fbde8969d0..1ea565cb54 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480_withbg.py @@ -137,7 +137,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5], - max_input_size=1440), + max_input_size=1800), dict( type='BottomUpResizeAlign', transforms=[ From 88ae596cbd0aaac21bffb3c32b68cb17003d2b65 Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 20 Aug 2021 17:08:20 +0800 Subject: [PATCH 95/98] resume training --- .../coco-wholebody/hrnet_w32_coco_wholebody_480x480.py | 2 +- .../coco-wholebody/openpose_v2_coco_wholebody_480x480.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py index dea7290571..f7e33f592d 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py @@ -1,6 +1,6 @@ log_level = 'INFO' load_from = None -resume_from = None +resume_from = 'work_dirs/hrnet_w32_coco_wholebody_480x480/epoch_150.pth' dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=50) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py index 03e1ce69a5..11d3a0f913 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py @@ -1,6 +1,6 @@ log_level = 'INFO' load_from = None -resume_from = None +resume_from = 'work_dirs/openpose_v2_coco_wholebody_480x480/epoch_150.pth' dist_params = dict(backend='nccl') workflow = [('train', 1)] checkpoint_config = dict(interval=50) From 5dcf0abf3af21166d7ec48c018b261f700838906 Mon Sep 17 00:00:00 2001 From: luminxu Date: Thu, 26 Aug 2021 12:00:46 +0800 Subject: [PATCH 96/98] test multi-scale wholebody --- .../coco-wholebody/hrnet_w32_coco_wholebody_480x480.py | 4 ++-- .../coco-wholebody/openpose_v2_coco_wholebody_480x480.py | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py index f7e33f592d..80d3768834 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/hrnet_w32_coco_wholebody_480x480.py @@ -112,7 +112,7 @@ test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, - scale_factor=[1], + scale_factor=[0.5, 1, 1.5, 2, 2.5], with_heatmaps=[True], with_pafs=[True], project2image=True, @@ -164,7 +164,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5]), dict( type='BottomUpResizeAlign', transforms=[ diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py index 11d3a0f913..b4336cf688 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py @@ -82,7 +82,7 @@ test_cfg=dict( num_joints=channel_cfg['dataset_joints'], max_num_people=30, - scale_factor=[1], + scale_factor=[0.5, 1, 1.5, 2, 2.5], with_heatmaps=[True], with_pafs=[True], project2image=True, @@ -134,7 +134,8 @@ val_pipeline = [ dict(type='LoadImageFromFile'), - dict(type='BottomUpGetImgSize', test_scale_factor=[1]), + dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5], + max_input_size=2000), dict( type='BottomUpResizeAlign', transforms=[ From 9dc9436bf6b9bf79d746d4da7c46da47c3bde9b9 Mon Sep 17 00:00:00 2001 From: luminxu Date: Thu, 26 Aug 2021 12:56:36 +0800 Subject: [PATCH 97/98] test multi-scale wholebody --- .../coco-wholebody/openpose_v2_coco_wholebody_480x480.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py index b4336cf688..f283c2fbfc 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py @@ -135,7 +135,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5], - max_input_size=2000), + max_input_size=1800), dict( type='BottomUpResizeAlign', transforms=[ From 84671abe5dabe89e8a40c19d1a86f86fa566e693 Mon Sep 17 00:00:00 2001 From: luminxu Date: Fri, 27 Aug 2021 09:16:38 +0800 Subject: [PATCH 98/98] test multi-scale wholebody --- .../coco-wholebody/openpose_v2_coco_wholebody_480x480.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py index f283c2fbfc..b4336cf688 100644 --- a/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py +++ b/configs/wholebody/2d_kpt_sview_rgb_img/part_affinity_field/coco-wholebody/openpose_v2_coco_wholebody_480x480.py @@ -135,7 +135,7 @@ val_pipeline = [ dict(type='LoadImageFromFile'), dict(type='BottomUpGetImgSize', test_scale_factor=[0.5, 1, 1.5, 2, 2.5], - max_input_size=1800), + max_input_size=2000), dict( type='BottomUpResizeAlign', transforms=[