We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
ImportError: cannot import name '_xywh2xyxy' from 'mmpose.apis.inference' 
https://github.com/open-mmlab/mmpose/blob/04e57f8765c9489390e4af58f81085d383083da5/demo/body3d_two_stage_img_demo.py#L130

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `demo/body3d_two_stage_img_demo.py`
Content:
```
1 # Copyright (c) OpenMMLab. All rights reserved.
2 import os
3 import os.path as osp
4 import warnings
5 from argparse import ArgumentParser
6 
7 import mmcv
8 import numpy as np
9 from xtcocotools.coco import COCO
10 
11 from mmpose.apis import (inference_pose_lifter_model,
12                          inference_top_down_pose_model, vis_3d_pose_result)
13 from mmpose.apis.inference import init_pose_model
14 from mmpose.core import SimpleCamera
15 from mmpose.datasets import DatasetInfo
16 
17 
18 def _keypoint_camera_to_world(keypoints,
19                               camera_params,
20                               image_name=None,
21                               dataset='Body3DH36MDataset'):
22     """Project 3D keypoints from the camera space to the world space.
23 
24     Args:
25         keypoints (np.ndarray): 3D keypoints in shape [..., 3]
26         camera_params (dict): Parameters for all cameras.
27         image_name (str): The image name to specify the camera.
28         dataset (str): The dataset type, e.g. Body3DH36MDataset.
29     """
30     cam_key = None
31     if dataset == 'Body3DH36MDataset':
32         subj, rest = osp.basename(image_name).split('_', 1)
33         _, rest = rest.split('.', 1)
34         camera, rest = rest.split('_', 1)
35         cam_key = (subj, camera)
36     else:
37         raise NotImplementedError
38 
39     camera = SimpleCamera(camera_params[cam_key])
40     keypoints_world = keypoints.copy()
41     keypoints_world[..., :3] = camera.camera_to_world(keypoints[..., :3])
42 
43     return keypoints_world
44 
45 
46 def main():
47     parser = ArgumentParser()
48     parser.add_argument(
49         'pose_lifter_config',
50         help='Config file for the 2nd stage pose lifter model')
51     parser.add_argument(
52         'pose_lifter_checkpoint',
53         help='Checkpoint file for the 2nd stage pose lifter model')
54     parser.add_argument(
55         '--pose-detector-config',
56         type=str,
57         default=None,
58         help='Config file for the 1st stage 2D pose detector')
59     parser.add_argument(
60         '--pose-detector-checkpoint',
61         type=str,
62         default=None,
63         help='Checkpoint file for the 1st stage 2D pose detector')
64     parser.add_argument('--img-root', type=str, default='', help='Image root')
65     parser.add_argument(
66         '--json-file',
67         type=str,
68         default=None,
69         help='Json file containing image and bbox information. Optionally,'
70         'The Json file can also contain 2D pose information. See'
71         '"only-second-stage"')
72     parser.add_argument(
73         '--camera-param-file',
74         type=str,
75         default=None,
76         help='Camera parameter file for converting 3D pose predictions from '
77         ' the camera space to to world space. If None, no conversion will be '
78         'applied.')
79     parser.add_argument(
80         '--only-second-stage',
81         action='store_true',
82         help='If true, load 2D pose detection result from the Json file and '
83         'skip the 1st stage. The pose detection model will be ignored.')
84     parser.add_argument(
85         '--rebase-keypoint-height',
86         action='store_true',
87         help='Rebase the predicted 3D pose so its lowest keypoint has a '
88         'height of 0 (landing on the ground). This is useful for '
89         'visualization when the model do not predict the global position '
90         'of the 3D pose.')
91     parser.add_argument(
92         '--show-ground-truth',
93         action='store_true',
94         help='If True, show ground truth if it is available. The ground truth '
95         'should be contained in the annotations in the Json file with the key '
96         '"keypoints_3d" for each instance.')
97     parser.add_argument(
98         '--show',
99         action='store_true',
100         default=False,
101         help='whether to show img')
102     parser.add_argument(
103         '--out-img-root',
104         type=str,
105         default=None,
106         help='Root of the output visualization images. '
107         'Default not saving the visualization images.')
108     parser.add_argument(
109         '--device', default='cuda:0', help='Device for inference')
110     parser.add_argument('--kpt-thr', type=float, default=0.3)
111     parser.add_argument(
112         '--radius',
113         type=int,
114         default=4,
115         help='Keypoint radius for visualization')
116     parser.add_argument(
117         '--thickness',
118         type=int,
119         default=1,
120         help='Link thickness for visualization')
121 
122     args = parser.parse_args()
123     assert args.show or (args.out_img_root != '')
124 
125     coco = COCO(args.json_file)
126 
127     # First stage: 2D pose detection
128     pose_det_results_list = []
129     if args.only_second_stage:
130         from mmpose.apis.inference import _xywh2xyxy
131 
132         print('Stage 1: load 2D pose results from Json file.')
133         for image_id, image in coco.imgs.items():
134             image_name = osp.join(args.img_root, image['file_name'])
135             ann_ids = coco.getAnnIds(image_id)
136             pose_det_results = []
137             for ann_id in ann_ids:
138                 ann = coco.anns[ann_id]
139                 keypoints = np.array(ann['keypoints']).reshape(-1, 3)
140                 keypoints[..., 2] = keypoints[..., 2] >= 1
141                 keypoints_3d = np.array(ann['keypoints_3d']).reshape(-1, 4)
142                 keypoints_3d[..., 3] = keypoints_3d[..., 3] >= 1
143                 bbox = np.array(ann['bbox']).reshape(1, -1)
144 
145                 pose_det_result = {
146                     'image_name': image_name,
147                     'bbox': _xywh2xyxy(bbox),
148                     'keypoints': keypoints,
149                     'keypoints_3d': keypoints_3d
150                 }
151                 pose_det_results.append(pose_det_result)
152             pose_det_results_list.append(pose_det_results)
153 
154     else:
155         print('Stage 1: 2D pose detection.')
156 
157         pose_det_model = init_pose_model(
158             args.pose_detector_config,
159             args.pose_detector_checkpoint,
160             device=args.device.lower())
161 
162         assert pose_det_model.cfg.model.type == 'TopDown', 'Only "TopDown"' \
163             'model is supported for the 1st stage (2D pose detection)'
164 
165         dataset = pose_det_model.cfg.data['test']['type']
166         dataset_info = pose_det_model.cfg.data['test'].get(
167             'dataset_info', None)
168         if dataset_info is None:
169             warnings.warn(
170                 'Please set `dataset_info` in the config.'
171                 'Check https://github.com/open-mmlab/mmpose/pull/663 '
172                 'for details.', DeprecationWarning)
173         else:
174             dataset_info = DatasetInfo(dataset_info)
175 
176         img_keys = list(coco.imgs.keys())
177 
178         for i in mmcv.track_iter_progress(range(len(img_keys))):
179             # get bounding box annotations
180             image_id = img_keys[i]
181             image = coco.loadImgs(image_id)[0]
182             image_name = osp.join(args.img_root, image['file_name'])
183             ann_ids = coco.getAnnIds(image_id)
184 
185             # make person results for single image
186             person_results = []
187             for ann_id in ann_ids:
188                 person = {}
189                 ann = coco.anns[ann_id]
190                 person['bbox'] = ann['bbox']
191                 person_results.append(person)
192 
193             pose_det_results, _ = inference_top_down_pose_model(
194                 pose_det_model,
195                 image_name,
196                 person_results,
197                 bbox_thr=None,
198                 format='xywh',
199                 dataset=dataset,
200                 dataset_info=dataset_info,
201                 return_heatmap=False,
202                 outputs=None)
203 
204             for res in pose_det_results:
205                 res['image_name'] = image_name
206             pose_det_results_list.append(pose_det_results)
207 
208     # Second stage: Pose lifting
209     print('Stage 2: 2D-to-3D pose lifting.')
210 
211     pose_lift_model = init_pose_model(
212         args.pose_lifter_config,
213         args.pose_lifter_checkpoint,
214         device=args.device.lower())
215 
216     assert pose_lift_model.cfg.model.type == 'PoseLifter', 'Only' \
217         '"PoseLifter" model is supported for the 2nd stage ' \
218         '(2D-to-3D lifting)'
219     dataset = pose_lift_model.cfg.data['test']['type']
220     dataset_info = pose_lift_model.cfg.data['test'].get('dataset_info', None)
221     if dataset_info is None:
222         warnings.warn(
223             'Please set `dataset_info` in the config.'
224             'Check https://github.com/open-mmlab/mmpose/pull/663 for details.',
225             DeprecationWarning)
226     else:
227         dataset_info = DatasetInfo(dataset_info)
228 
229     camera_params = None
230     if args.camera_param_file is not None:
231         camera_params = mmcv.load(args.camera_param_file)
232 
233     for i, pose_det_results in enumerate(
234             mmcv.track_iter_progress(pose_det_results_list)):
235         # 2D-to-3D pose lifting
236         # Note that the pose_det_results are regarded as a single-frame pose
237         # sequence
238         pose_lift_results = inference_pose_lifter_model(
239             pose_lift_model,
240             pose_results_2d=[pose_det_results],
241             dataset=dataset,
242             dataset_info=dataset_info,
243             with_track_id=False)
244 
245         image_name = pose_det_results[0]['image_name']
246 
247         # Pose processing
248         pose_lift_results_vis = []
249         for idx, res in enumerate(pose_lift_results):
250             keypoints_3d = res['keypoints_3d']
251             # project to world space
252             if camera_params is not None:
253                 keypoints_3d = _keypoint_camera_to_world(
254                     keypoints_3d,
255                     camera_params=camera_params,
256                     image_name=image_name,
257                     dataset=dataset)
258             # rebase height (z-axis)
259             if args.rebase_keypoint_height:
260                 keypoints_3d[..., 2] -= np.min(
261                     keypoints_3d[..., 2], axis=-1, keepdims=True)
262             res['keypoints_3d'] = keypoints_3d
263             # Add title
264             det_res = pose_det_results[idx]
265             instance_id = det_res.get('track_id', idx)
266             res['title'] = f'Prediction ({instance_id})'
267             pose_lift_results_vis.append(res)
268             # Add ground truth
269             if args.show_ground_truth:
270                 if 'keypoints_3d' not in det_res:
271                     print('Fail to show ground truth. Please make sure that'
272                           ' the instance annotations from the Json file'
273                           ' contain "keypoints_3d".')
274                 else:
275                     gt = res.copy()
276                     gt['keypoints_3d'] = det_res['keypoints_3d']
277                     gt['title'] = f'Ground truth ({instance_id})'
278                     pose_lift_results_vis.append(gt)
279 
280         # Visualization
281         if args.out_img_root is None:
282             out_file = None
283         else:
284             os.makedirs(args.out_img_root, exist_ok=True)
285             out_file = osp.join(args.out_img_root, f'vis_{i}.jpg')
286 
287         vis_3d_pose_result(
288             pose_lift_model,
289             result=pose_lift_results_vis,
290             img=image_name,
291             dataset_info=dataset_info,
292             out_file=out_file)
293 
294 
295 if __name__ == '__main__':
296     main()
297
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/demo/body3d_two_stage_img_demo.py b/demo/body3d_two_stage_img_demo.py
--- a/demo/body3d_two_stage_img_demo.py
+++ b/demo/body3d_two_stage_img_demo.py
@@ -11,7 +11,8 @@
 from mmpose.apis import (inference_pose_lifter_model,
                          inference_top_down_pose_model, vis_3d_pose_result)
 from mmpose.apis.inference import init_pose_model
-from mmpose.core import SimpleCamera
+from mmpose.core.bbox import bbox_xywh2xyxy
+from mmpose.core.camera import SimpleCamera
 from mmpose.datasets import DatasetInfo
 
 
@@ -127,7 +128,6 @@
     # First stage: 2D pose detection
     pose_det_results_list = []
     if args.only_second_stage:
-        from mmpose.apis.inference import _xywh2xyxy
 
         print('Stage 1: load 2D pose results from Json file.')
         for image_id, image in coco.imgs.items():
@@ -144,7 +144,7 @@
 
                 pose_det_result = {
                     'image_name': image_name,
-                    'bbox': _xywh2xyxy(bbox),
+                    'bbox': bbox_xywh2xyxy(bbox),
                     'keypoints': keypoints,
                     'keypoints_3d': keypoints_3d
                 }

{"golden_diff": "diff --git a/demo/body3d_two_stage_img_demo.py b/demo/body3d_two_stage_img_demo.py\n--- a/demo/body3d_two_stage_img_demo.py\n+++ b/demo/body3d_two_stage_img_demo.py\n@@ -11,7 +11,8 @@\n from mmpose.apis import (inference_pose_lifter_model,\n                          inference_top_down_pose_model, vis_3d_pose_result)\n from mmpose.apis.inference import init_pose_model\n-from mmpose.core import SimpleCamera\n+from mmpose.core.bbox import bbox_xywh2xyxy\n+from mmpose.core.camera import SimpleCamera\n from mmpose.datasets import DatasetInfo\n \n \n@@ -127,7 +128,6 @@\n     # First stage: 2D pose detection\n     pose_det_results_list = []\n     if args.only_second_stage:\n-        from mmpose.apis.inference import _xywh2xyxy\n \n         print('Stage 1: load 2D pose results from Json file.')\n         for image_id, image in coco.imgs.items():\n@@ -144,7 +144,7 @@\n \n                 pose_det_result = {\n                     'image_name': image_name,\n-                    'bbox': _xywh2xyxy(bbox),\n+                    'bbox': bbox_xywh2xyxy(bbox),\n                     'keypoints': keypoints,\n                     'keypoints_3d': keypoints_3d\n                 }\n", "issue": "ImportError: cannot import name '_xywh2xyxy' from 'mmpose.apis.inference' \nhttps://github.com/open-mmlab/mmpose/blob/04e57f8765c9489390e4af58f81085d383083da5/demo/body3d_two_stage_img_demo.py#L130\n", "before_files": [{"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport os\nimport os.path as osp\nimport warnings\nfrom argparse import ArgumentParser\n\nimport mmcv\nimport numpy as np\nfrom xtcocotools.coco import COCO\n\nfrom mmpose.apis import (inference_pose_lifter_model,\n                         inference_top_down_pose_model, vis_3d_pose_result)\nfrom mmpose.apis.inference import init_pose_model\nfrom mmpose.core import SimpleCamera\nfrom mmpose.datasets import DatasetInfo\n\n\ndef _keypoint_camera_to_world(keypoints,\n                              camera_params,\n                              image_name=None,\n                              dataset='Body3DH36MDataset'):\n    \"\"\"Project 3D keypoints from the camera space to the world space.\n\n    Args:\n        keypoints (np.ndarray): 3D keypoints in shape [..., 3]\n        camera_params (dict): Parameters for all cameras.\n        image_name (str): The image name to specify the camera.\n        dataset (str): The dataset type, e.g. Body3DH36MDataset.\n    \"\"\"\n    cam_key = None\n    if dataset == 'Body3DH36MDataset':\n        subj, rest = osp.basename(image_name).split('_', 1)\n        _, rest = rest.split('.', 1)\n        camera, rest = rest.split('_', 1)\n        cam_key = (subj, camera)\n    else:\n        raise NotImplementedError\n\n    camera = SimpleCamera(camera_params[cam_key])\n    keypoints_world = keypoints.copy()\n    keypoints_world[..., :3] = camera.camera_to_world(keypoints[..., :3])\n\n    return keypoints_world\n\n\ndef main():\n    parser = ArgumentParser()\n    parser.add_argument(\n        'pose_lifter_config',\n        help='Config file for the 2nd stage pose lifter model')\n    parser.add_argument(\n        'pose_lifter_checkpoint',\n        help='Checkpoint file for the 2nd stage pose lifter model')\n    parser.add_argument(\n        '--pose-detector-config',\n        type=str,\n        default=None,\n        help='Config file for the 1st stage 2D pose detector')\n    parser.add_argument(\n        '--pose-detector-checkpoint',\n        type=str,\n        default=None,\n        help='Checkpoint file for the 1st stage 2D pose detector')\n    parser.add_argument('--img-root', type=str, default='', help='Image root')\n    parser.add_argument(\n        '--json-file',\n        type=str,\n        default=None,\n        help='Json file containing image and bbox information. Optionally,'\n        'The Json file can also contain 2D pose information. See'\n        '\"only-second-stage\"')\n    parser.add_argument(\n        '--camera-param-file',\n        type=str,\n        default=None,\n        help='Camera parameter file for converting 3D pose predictions from '\n        ' the camera space to to world space. If None, no conversion will be '\n        'applied.')\n    parser.add_argument(\n        '--only-second-stage',\n        action='store_true',\n        help='If true, load 2D pose detection result from the Json file and '\n        'skip the 1st stage. The pose detection model will be ignored.')\n    parser.add_argument(\n        '--rebase-keypoint-height',\n        action='store_true',\n        help='Rebase the predicted 3D pose so its lowest keypoint has a '\n        'height of 0 (landing on the ground). This is useful for '\n        'visualization when the model do not predict the global position '\n        'of the 3D pose.')\n    parser.add_argument(\n        '--show-ground-truth',\n        action='store_true',\n        help='If True, show ground truth if it is available. The ground truth '\n        'should be contained in the annotations in the Json file with the key '\n        '\"keypoints_3d\" for each instance.')\n    parser.add_argument(\n        '--show',\n        action='store_true',\n        default=False,\n        help='whether to show img')\n    parser.add_argument(\n        '--out-img-root',\n        type=str,\n        default=None,\n        help='Root of the output visualization images. '\n        'Default not saving the visualization images.')\n    parser.add_argument(\n        '--device', default='cuda:0', help='Device for inference')\n    parser.add_argument('--kpt-thr', type=float, default=0.3)\n    parser.add_argument(\n        '--radius',\n        type=int,\n        default=4,\n        help='Keypoint radius for visualization')\n    parser.add_argument(\n        '--thickness',\n        type=int,\n        default=1,\n        help='Link thickness for visualization')\n\n    args = parser.parse_args()\n    assert args.show or (args.out_img_root != '')\n\n    coco = COCO(args.json_file)\n\n    # First stage: 2D pose detection\n    pose_det_results_list = []\n    if args.only_second_stage:\n        from mmpose.apis.inference import _xywh2xyxy\n\n        print('Stage 1: load 2D pose results from Json file.')\n        for image_id, image in coco.imgs.items():\n            image_name = osp.join(args.img_root, image['file_name'])\n            ann_ids = coco.getAnnIds(image_id)\n            pose_det_results = []\n            for ann_id in ann_ids:\n                ann = coco.anns[ann_id]\n                keypoints = np.array(ann['keypoints']).reshape(-1, 3)\n                keypoints[..., 2] = keypoints[..., 2] >= 1\n                keypoints_3d = np.array(ann['keypoints_3d']).reshape(-1, 4)\n                keypoints_3d[..., 3] = keypoints_3d[..., 3] >= 1\n                bbox = np.array(ann['bbox']).reshape(1, -1)\n\n                pose_det_result = {\n                    'image_name': image_name,\n                    'bbox': _xywh2xyxy(bbox),\n                    'keypoints': keypoints,\n                    'keypoints_3d': keypoints_3d\n                }\n                pose_det_results.append(pose_det_result)\n            pose_det_results_list.append(pose_det_results)\n\n    else:\n        print('Stage 1: 2D pose detection.')\n\n        pose_det_model = init_pose_model(\n            args.pose_detector_config,\n            args.pose_detector_checkpoint,\n            device=args.device.lower())\n\n        assert pose_det_model.cfg.model.type == 'TopDown', 'Only \"TopDown\"' \\\n            'model is supported for the 1st stage (2D pose detection)'\n\n        dataset = pose_det_model.cfg.data['test']['type']\n        dataset_info = pose_det_model.cfg.data['test'].get(\n            'dataset_info', None)\n        if dataset_info is None:\n            warnings.warn(\n                'Please set `dataset_info` in the config.'\n                'Check https://github.com/open-mmlab/mmpose/pull/663 '\n                'for details.', DeprecationWarning)\n        else:\n            dataset_info = DatasetInfo(dataset_info)\n\n        img_keys = list(coco.imgs.keys())\n\n        for i in mmcv.track_iter_progress(range(len(img_keys))):\n            # get bounding box annotations\n            image_id = img_keys[i]\n            image = coco.loadImgs(image_id)[0]\n            image_name = osp.join(args.img_root, image['file_name'])\n            ann_ids = coco.getAnnIds(image_id)\n\n            # make person results for single image\n            person_results = []\n            for ann_id in ann_ids:\n                person = {}\n                ann = coco.anns[ann_id]\n                person['bbox'] = ann['bbox']\n                person_results.append(person)\n\n            pose_det_results, _ = inference_top_down_pose_model(\n                pose_det_model,\n                image_name,\n                person_results,\n                bbox_thr=None,\n                format='xywh',\n                dataset=dataset,\n                dataset_info=dataset_info,\n                return_heatmap=False,\n                outputs=None)\n\n            for res in pose_det_results:\n                res['image_name'] = image_name\n            pose_det_results_list.append(pose_det_results)\n\n    # Second stage: Pose lifting\n    print('Stage 2: 2D-to-3D pose lifting.')\n\n    pose_lift_model = init_pose_model(\n        args.pose_lifter_config,\n        args.pose_lifter_checkpoint,\n        device=args.device.lower())\n\n    assert pose_lift_model.cfg.model.type == 'PoseLifter', 'Only' \\\n        '\"PoseLifter\" model is supported for the 2nd stage ' \\\n        '(2D-to-3D lifting)'\n    dataset = pose_lift_model.cfg.data['test']['type']\n    dataset_info = pose_lift_model.cfg.data['test'].get('dataset_info', None)\n    if dataset_info is None:\n        warnings.warn(\n            'Please set `dataset_info` in the config.'\n            'Check https://github.com/open-mmlab/mmpose/pull/663 for details.',\n            DeprecationWarning)\n    else:\n        dataset_info = DatasetInfo(dataset_info)\n\n    camera_params = None\n    if args.camera_param_file is not None:\n        camera_params = mmcv.load(args.camera_param_file)\n\n    for i, pose_det_results in enumerate(\n            mmcv.track_iter_progress(pose_det_results_list)):\n        # 2D-to-3D pose lifting\n        # Note that the pose_det_results are regarded as a single-frame pose\n        # sequence\n        pose_lift_results = inference_pose_lifter_model(\n            pose_lift_model,\n            pose_results_2d=[pose_det_results],\n            dataset=dataset,\n            dataset_info=dataset_info,\n            with_track_id=False)\n\n        image_name = pose_det_results[0]['image_name']\n\n        # Pose processing\n        pose_lift_results_vis = []\n        for idx, res in enumerate(pose_lift_results):\n            keypoints_3d = res['keypoints_3d']\n            # project to world space\n            if camera_params is not None:\n                keypoints_3d = _keypoint_camera_to_world(\n                    keypoints_3d,\n                    camera_params=camera_params,\n                    image_name=image_name,\n                    dataset=dataset)\n            # rebase height (z-axis)\n            if args.rebase_keypoint_height:\n                keypoints_3d[..., 2] -= np.min(\n                    keypoints_3d[..., 2], axis=-1, keepdims=True)\n            res['keypoints_3d'] = keypoints_3d\n            # Add title\n            det_res = pose_det_results[idx]\n            instance_id = det_res.get('track_id', idx)\n            res['title'] = f'Prediction ({instance_id})'\n            pose_lift_results_vis.append(res)\n            # Add ground truth\n            if args.show_ground_truth:\n                if 'keypoints_3d' not in det_res:\n                    print('Fail to show ground truth. Please make sure that'\n                          ' the instance annotations from the Json file'\n                          ' contain \"keypoints_3d\".')\n                else:\n                    gt = res.copy()\n                    gt['keypoints_3d'] = det_res['keypoints_3d']\n                    gt['title'] = f'Ground truth ({instance_id})'\n                    pose_lift_results_vis.append(gt)\n\n        # Visualization\n        if args.out_img_root is None:\n            out_file = None\n        else:\n            os.makedirs(args.out_img_root, exist_ok=True)\n            out_file = osp.join(args.out_img_root, f'vis_{i}.jpg')\n\n        vis_3d_pose_result(\n            pose_lift_model,\n            result=pose_lift_results_vis,\n            img=image_name,\n            dataset_info=dataset_info,\n            out_file=out_file)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "demo/body3d_two_stage_img_demo.py"}], "after_files": [{"content": "# Copyright (c) OpenMMLab. All rights reserved.\nimport os\nimport os.path as osp\nimport warnings\nfrom argparse import ArgumentParser\n\nimport mmcv\nimport numpy as np\nfrom xtcocotools.coco import COCO\n\nfrom mmpose.apis import (inference_pose_lifter_model,\n                         inference_top_down_pose_model, vis_3d_pose_result)\nfrom mmpose.apis.inference import init_pose_model\nfrom mmpose.core.bbox import bbox_xywh2xyxy\nfrom mmpose.core.camera import SimpleCamera\nfrom mmpose.datasets import DatasetInfo\n\n\ndef _keypoint_camera_to_world(keypoints,\n                              camera_params,\n                              image_name=None,\n                              dataset='Body3DH36MDataset'):\n    \"\"\"Project 3D keypoints from the camera space to the world space.\n\n    Args:\n        keypoints (np.ndarray): 3D keypoints in shape [..., 3]\n        camera_params (dict): Parameters for all cameras.\n        image_name (str): The image name to specify the camera.\n        dataset (str): The dataset type, e.g. Body3DH36MDataset.\n    \"\"\"\n    cam_key = None\n    if dataset == 'Body3DH36MDataset':\n        subj, rest = osp.basename(image_name).split('_', 1)\n        _, rest = rest.split('.', 1)\n        camera, rest = rest.split('_', 1)\n        cam_key = (subj, camera)\n    else:\n        raise NotImplementedError\n\n    camera = SimpleCamera(camera_params[cam_key])\n    keypoints_world = keypoints.copy()\n    keypoints_world[..., :3] = camera.camera_to_world(keypoints[..., :3])\n\n    return keypoints_world\n\n\ndef main():\n    parser = ArgumentParser()\n    parser.add_argument(\n        'pose_lifter_config',\n        help='Config file for the 2nd stage pose lifter model')\n    parser.add_argument(\n        'pose_lifter_checkpoint',\n        help='Checkpoint file for the 2nd stage pose lifter model')\n    parser.add_argument(\n        '--pose-detector-config',\n        type=str,\n        default=None,\n        help='Config file for the 1st stage 2D pose detector')\n    parser.add_argument(\n        '--pose-detector-checkpoint',\n        type=str,\n        default=None,\n        help='Checkpoint file for the 1st stage 2D pose detector')\n    parser.add_argument('--img-root', type=str, default='', help='Image root')\n    parser.add_argument(\n        '--json-file',\n        type=str,\n        default=None,\n        help='Json file containing image and bbox information. Optionally,'\n        'The Json file can also contain 2D pose information. See'\n        '\"only-second-stage\"')\n    parser.add_argument(\n        '--camera-param-file',\n        type=str,\n        default=None,\n        help='Camera parameter file for converting 3D pose predictions from '\n        ' the camera space to to world space. If None, no conversion will be '\n        'applied.')\n    parser.add_argument(\n        '--only-second-stage',\n        action='store_true',\n        help='If true, load 2D pose detection result from the Json file and '\n        'skip the 1st stage. The pose detection model will be ignored.')\n    parser.add_argument(\n        '--rebase-keypoint-height',\n        action='store_true',\n        help='Rebase the predicted 3D pose so its lowest keypoint has a '\n        'height of 0 (landing on the ground). This is useful for '\n        'visualization when the model do not predict the global position '\n        'of the 3D pose.')\n    parser.add_argument(\n        '--show-ground-truth',\n        action='store_true',\n        help='If True, show ground truth if it is available. The ground truth '\n        'should be contained in the annotations in the Json file with the key '\n        '\"keypoints_3d\" for each instance.')\n    parser.add_argument(\n        '--show',\n        action='store_true',\n        default=False,\n        help='whether to show img')\n    parser.add_argument(\n        '--out-img-root',\n        type=str,\n        default=None,\n        help='Root of the output visualization images. '\n        'Default not saving the visualization images.')\n    parser.add_argument(\n        '--device', default='cuda:0', help='Device for inference')\n    parser.add_argument('--kpt-thr', type=float, default=0.3)\n    parser.add_argument(\n        '--radius',\n        type=int,\n        default=4,\n        help='Keypoint radius for visualization')\n    parser.add_argument(\n        '--thickness',\n        type=int,\n        default=1,\n        help='Link thickness for visualization')\n\n    args = parser.parse_args()\n    assert args.show or (args.out_img_root != '')\n\n    coco = COCO(args.json_file)\n\n    # First stage: 2D pose detection\n    pose_det_results_list = []\n    if args.only_second_stage:\n\n        print('Stage 1: load 2D pose results from Json file.')\n        for image_id, image in coco.imgs.items():\n            image_name = osp.join(args.img_root, image['file_name'])\n            ann_ids = coco.getAnnIds(image_id)\n            pose_det_results = []\n            for ann_id in ann_ids:\n                ann = coco.anns[ann_id]\n                keypoints = np.array(ann['keypoints']).reshape(-1, 3)\n                keypoints[..., 2] = keypoints[..., 2] >= 1\n                keypoints_3d = np.array(ann['keypoints_3d']).reshape(-1, 4)\n                keypoints_3d[..., 3] = keypoints_3d[..., 3] >= 1\n                bbox = np.array(ann['bbox']).reshape(1, -1)\n\n                pose_det_result = {\n                    'image_name': image_name,\n                    'bbox': bbox_xywh2xyxy(bbox),\n                    'keypoints': keypoints,\n                    'keypoints_3d': keypoints_3d\n                }\n                pose_det_results.append(pose_det_result)\n            pose_det_results_list.append(pose_det_results)\n\n    else:\n        print('Stage 1: 2D pose detection.')\n\n        pose_det_model = init_pose_model(\n            args.pose_detector_config,\n            args.pose_detector_checkpoint,\n            device=args.device.lower())\n\n        assert pose_det_model.cfg.model.type == 'TopDown', 'Only \"TopDown\"' \\\n            'model is supported for the 1st stage (2D pose detection)'\n\n        dataset = pose_det_model.cfg.data['test']['type']\n        dataset_info = pose_det_model.cfg.data['test'].get(\n            'dataset_info', None)\n        if dataset_info is None:\n            warnings.warn(\n                'Please set `dataset_info` in the config.'\n                'Check https://github.com/open-mmlab/mmpose/pull/663 '\n                'for details.', DeprecationWarning)\n        else:\n            dataset_info = DatasetInfo(dataset_info)\n\n        img_keys = list(coco.imgs.keys())\n\n        for i in mmcv.track_iter_progress(range(len(img_keys))):\n            # get bounding box annotations\n            image_id = img_keys[i]\n            image = coco.loadImgs(image_id)[0]\n            image_name = osp.join(args.img_root, image['file_name'])\n            ann_ids = coco.getAnnIds(image_id)\n\n            # make person results for single image\n            person_results = []\n            for ann_id in ann_ids:\n                person = {}\n                ann = coco.anns[ann_id]\n                person['bbox'] = ann['bbox']\n                person_results.append(person)\n\n            pose_det_results, _ = inference_top_down_pose_model(\n                pose_det_model,\n                image_name,\n                person_results,\n                bbox_thr=None,\n                format='xywh',\n                dataset=dataset,\n                dataset_info=dataset_info,\n                return_heatmap=False,\n                outputs=None)\n\n            for res in pose_det_results:\n                res['image_name'] = image_name\n            pose_det_results_list.append(pose_det_results)\n\n    # Second stage: Pose lifting\n    print('Stage 2: 2D-to-3D pose lifting.')\n\n    pose_lift_model = init_pose_model(\n        args.pose_lifter_config,\n        args.pose_lifter_checkpoint,\n        device=args.device.lower())\n\n    assert pose_lift_model.cfg.model.type == 'PoseLifter', 'Only' \\\n        '\"PoseLifter\" model is supported for the 2nd stage ' \\\n        '(2D-to-3D lifting)'\n    dataset = pose_lift_model.cfg.data['test']['type']\n    dataset_info = pose_lift_model.cfg.data['test'].get('dataset_info', None)\n    if dataset_info is None:\n        warnings.warn(\n            'Please set `dataset_info` in the config.'\n            'Check https://github.com/open-mmlab/mmpose/pull/663 for details.',\n            DeprecationWarning)\n    else:\n        dataset_info = DatasetInfo(dataset_info)\n\n    camera_params = None\n    if args.camera_param_file is not None:\n        camera_params = mmcv.load(args.camera_param_file)\n\n    for i, pose_det_results in enumerate(\n            mmcv.track_iter_progress(pose_det_results_list)):\n        # 2D-to-3D pose lifting\n        # Note that the pose_det_results are regarded as a single-frame pose\n        # sequence\n        pose_lift_results = inference_pose_lifter_model(\n            pose_lift_model,\n            pose_results_2d=[pose_det_results],\n            dataset=dataset,\n            dataset_info=dataset_info,\n            with_track_id=False)\n\n        image_name = pose_det_results[0]['image_name']\n\n        # Pose processing\n        pose_lift_results_vis = []\n        for idx, res in enumerate(pose_lift_results):\n            keypoints_3d = res['keypoints_3d']\n            # project to world space\n            if camera_params is not None:\n                keypoints_3d = _keypoint_camera_to_world(\n                    keypoints_3d,\n                    camera_params=camera_params,\n                    image_name=image_name,\n                    dataset=dataset)\n            # rebase height (z-axis)\n            if args.rebase_keypoint_height:\n                keypoints_3d[..., 2] -= np.min(\n                    keypoints_3d[..., 2], axis=-1, keepdims=True)\n            res['keypoints_3d'] = keypoints_3d\n            # Add title\n            det_res = pose_det_results[idx]\n            instance_id = det_res.get('track_id', idx)\n            res['title'] = f'Prediction ({instance_id})'\n            pose_lift_results_vis.append(res)\n            # Add ground truth\n            if args.show_ground_truth:\n                if 'keypoints_3d' not in det_res:\n                    print('Fail to show ground truth. Please make sure that'\n                          ' the instance annotations from the Json file'\n                          ' contain \"keypoints_3d\".')\n                else:\n                    gt = res.copy()\n                    gt['keypoints_3d'] = det_res['keypoints_3d']\n                    gt['title'] = f'Ground truth ({instance_id})'\n                    pose_lift_results_vis.append(gt)\n\n        # Visualization\n        if args.out_img_root is None:\n            out_file = None\n        else:\n            os.makedirs(args.out_img_root, exist_ok=True)\n            out_file = osp.join(args.out_img_root, f'vis_{i}.jpg')\n\n        vis_3d_pose_result(\n            pose_lift_model,\n            result=pose_lift_results_vis,\n            img=image_name,\n            dataset_info=dataset_info,\n            out_file=out_file)\n\n\nif __name__ == '__main__':\n    main()\n", "path": "demo/body3d_two_stage_img_demo.py"}]}