Spaces:
Running
Running
jhj0517
commited on
Commit
•
0a9bdfb
1
Parent(s):
2c51e62
initial commit
Browse files- .gitignore +12 -0
- LICENSE +107 -0
- assets/images/images_will_be_saved_here.txt +0 -0
- assets/videos/videos_will_be_saved_here.txt +0 -0
- configs/inference_v2.yaml +35 -0
- configs/test_stage.yaml +21 -0
- downloading_weights.py +38 -0
- draw_dwpose.py +112 -0
- gradio_app.py +77 -0
- musepose_inference.py +254 -0
- pose/config/dwpose-l_384x288.py +257 -0
- pose/config/yolox_l_8xb8-300e_coco.py +245 -0
- pose/script/dwpose.py +143 -0
- pose/script/tool.py +130 -0
- pose/script/util.py +153 -0
- pose/script/wholebody.py +121 -0
- pose_align.py +557 -0
- requirements.txt +25 -0
- test_stage.py +60 -0
.gitignore
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
.DS_Store
|
7 |
+
pretrained_weights
|
8 |
+
output
|
9 |
+
|
10 |
+
venv/
|
11 |
+
pretrained_weights/
|
12 |
+
.idea/
|
LICENSE
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
MIT License
|
3 |
+
|
4 |
+
Copyright (c) 2024 Tencent Music Entertainment Group
|
5 |
+
|
6 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
7 |
+
of this software and associated documentation files (the "Software"), to deal
|
8 |
+
in the Software without restriction, including without limitation the rights
|
9 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
10 |
+
copies of the Software, and to permit persons to whom the Software is
|
11 |
+
furnished to do so, subject to the following conditions:
|
12 |
+
|
13 |
+
The above copyright notice and this permission notice shall be included in all
|
14 |
+
copies or substantial portions of the Software.
|
15 |
+
|
16 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
17 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
18 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
19 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
20 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
21 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
22 |
+
SOFTWARE.
|
23 |
+
|
24 |
+
|
25 |
+
Other dependencies and licenses:
|
26 |
+
|
27 |
+
|
28 |
+
Open Source Software Licensed under the MIT License:
|
29 |
+
--------------------------------------------------------------------
|
30 |
+
1. sd-vae-ft-mse
|
31 |
+
Files:https://huggingface.co/stabilityai/sd-vae-ft-mse/tree/main
|
32 |
+
License:MIT license
|
33 |
+
For details:https://choosealicense.com/licenses/mit/
|
34 |
+
|
35 |
+
|
36 |
+
|
37 |
+
|
38 |
+
Open Source Software Licensed under the Apache License Version 2.0:
|
39 |
+
--------------------------------------------------------------------
|
40 |
+
1. DWpose
|
41 |
+
Files:https://huggingface.co/yzd-v/DWPose/tree/main
|
42 |
+
License:Apache-2.0
|
43 |
+
For details:https://choosealicense.com/licenses/apache-2.0/
|
44 |
+
|
45 |
+
2. Moore-AnimateAnyone
|
46 |
+
Files:https://github.com/MooreThreads/Moore-AnimateAnyone
|
47 |
+
License:Apache-2.0
|
48 |
+
For details:https://github.com/MooreThreads/Moore-AnimateAnyone/blob/master/LICENSE
|
49 |
+
|
50 |
+
Terms of the Apache License Version 2.0:
|
51 |
+
--------------------------------------------------------------------
|
52 |
+
Apache License
|
53 |
+
|
54 |
+
Version 2.0, January 2004
|
55 |
+
|
56 |
+
http://www.apache.org/licenses/
|
57 |
+
|
58 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
59 |
+
1. Definitions.
|
60 |
+
|
61 |
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
62 |
+
|
63 |
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
64 |
+
|
65 |
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
66 |
+
|
67 |
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
68 |
+
|
69 |
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
70 |
+
|
71 |
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
72 |
+
|
73 |
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
74 |
+
|
75 |
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
76 |
+
|
77 |
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
78 |
+
|
79 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
80 |
+
|
81 |
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
82 |
+
|
83 |
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
84 |
+
|
85 |
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
86 |
+
|
87 |
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
88 |
+
|
89 |
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
90 |
+
|
91 |
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
92 |
+
|
93 |
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
94 |
+
|
95 |
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
96 |
+
|
97 |
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
98 |
+
|
99 |
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
100 |
+
|
101 |
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
102 |
+
|
103 |
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
104 |
+
|
105 |
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
106 |
+
|
107 |
+
END OF TERMS AND CONDITIONS
|
assets/images/images_will_be_saved_here.txt
ADDED
File without changes
|
assets/videos/videos_will_be_saved_here.txt
ADDED
File without changes
|
configs/inference_v2.yaml
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
unet_additional_kwargs:
|
2 |
+
use_inflated_groupnorm: true
|
3 |
+
unet_use_cross_frame_attention: false
|
4 |
+
unet_use_temporal_attention: false
|
5 |
+
use_motion_module: true
|
6 |
+
motion_module_resolutions:
|
7 |
+
- 1
|
8 |
+
- 2
|
9 |
+
- 4
|
10 |
+
- 8
|
11 |
+
motion_module_mid_block: true
|
12 |
+
motion_module_decoder_only: false
|
13 |
+
motion_module_type: Vanilla
|
14 |
+
motion_module_kwargs:
|
15 |
+
num_attention_heads: 8
|
16 |
+
num_transformer_block: 1
|
17 |
+
attention_block_types:
|
18 |
+
- Temporal_Self
|
19 |
+
- Temporal_Self
|
20 |
+
temporal_position_encoding: true
|
21 |
+
temporal_position_encoding_max_len: 128
|
22 |
+
temporal_attention_dim_div: 1
|
23 |
+
|
24 |
+
noise_scheduler_kwargs:
|
25 |
+
beta_start: 0.00085
|
26 |
+
beta_end: 0.012
|
27 |
+
beta_schedule: "linear"
|
28 |
+
clip_sample: false
|
29 |
+
steps_offset: 1
|
30 |
+
### Zero-SNR params
|
31 |
+
prediction_type: "v_prediction"
|
32 |
+
rescale_betas_zero_snr: True
|
33 |
+
timestep_spacing: "trailing"
|
34 |
+
|
35 |
+
sampler: DDIM
|
configs/test_stage.yaml
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pretrained_base_model_path: './pretrained_weights/sd-image-variations-diffusers'
|
2 |
+
pretrained_vae_path: './pretrained_weights/sd-vae-ft-mse'
|
3 |
+
image_encoder_path: './pretrained_weights/image_encoder'
|
4 |
+
|
5 |
+
|
6 |
+
|
7 |
+
denoising_unet_path: "./pretrained_weights/MusePose/denoising_unet.pth"
|
8 |
+
reference_unet_path: "./pretrained_weights/MusePose/reference_unet.pth"
|
9 |
+
pose_guider_path: "./pretrained_weights/MusePose/pose_guider.pth"
|
10 |
+
motion_module_path: "./pretrained_weights/MusePose/motion_module.pth"
|
11 |
+
|
12 |
+
|
13 |
+
|
14 |
+
inference_config: "./configs/inference_v2.yaml"
|
15 |
+
weight_dtype: 'fp16'
|
16 |
+
|
17 |
+
|
18 |
+
|
19 |
+
test_cases:
|
20 |
+
"./assets/images/ref.png":
|
21 |
+
- "./assets/poses/align/img_ref_video_dance.mp4"
|
downloading_weights.py
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import wget
|
3 |
+
from tqdm import tqdm
|
4 |
+
|
5 |
+
os.makedirs('pretrained_weights', exist_ok=True)
|
6 |
+
|
7 |
+
urls = ['https://download.openmmlab.com/mmdetection/v2.0/yolox/yolox_l_8x8_300e_coco/yolox_l_8x8_300e_coco_20211126_140236-d3bd2b23.pth',
|
8 |
+
'https://huggingface.co/yzd-v/DWPose/resolve/main/dw-ll_ucoco_384.pth',
|
9 |
+
'https://huggingface.co/TMElyralab/MusePose/resolve/main/MusePose/denoising_unet.pth',
|
10 |
+
'https://huggingface.co/TMElyralab/MusePose/resolve/main/MusePose/motion_module.pth',
|
11 |
+
'https://huggingface.co/TMElyralab/MusePose/resolve/main/MusePose/pose_guider.pth',
|
12 |
+
'https://huggingface.co/TMElyralab/MusePose/resolve/main/MusePose/reference_unet.pth',
|
13 |
+
'https://huggingface.co/lambdalabs/sd-image-variations-diffusers/resolve/main/unet/diffusion_pytorch_model.bin',
|
14 |
+
'https://huggingface.co/lambdalabs/sd-image-variations-diffusers/resolve/main/image_encoder/pytorch_model.bin',
|
15 |
+
'https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/main/diffusion_pytorch_model.bin'
|
16 |
+
]
|
17 |
+
|
18 |
+
paths = ['dwpose', 'dwpose', 'MusePose', 'MusePose', 'MusePose', 'MusePose', 'sd-image-variations-diffusers/unet', 'image_encoder', 'sd-vae-ft-mse']
|
19 |
+
|
20 |
+
for path in paths:
|
21 |
+
os.makedirs(f'pretrained_weights/{path}', exist_ok=True)
|
22 |
+
|
23 |
+
# saving weights
|
24 |
+
for url, path in tqdm(zip(urls, paths)):
|
25 |
+
filename = wget.download(url, f'pretrained_weights/{path}')
|
26 |
+
|
27 |
+
config_urls = ['https://huggingface.co/lambdalabs/sd-image-variations-diffusers/resolve/main/unet/config.json',
|
28 |
+
'https://huggingface.co/lambdalabs/sd-image-variations-diffusers/resolve/main/image_encoder/config.json',
|
29 |
+
'https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/main/config.json']
|
30 |
+
|
31 |
+
config_paths = ['sd-image-variations-diffusers/unet', 'image_encoder', 'sd-vae-ft-mse']
|
32 |
+
|
33 |
+
# saving config files
|
34 |
+
for url, path in tqdm(zip(config_urls, config_paths)):
|
35 |
+
filename = wget.download(url, f'pretrained_weights/{path}')
|
36 |
+
|
37 |
+
# renaming model name as given in readme
|
38 |
+
os.rename('pretrained_weights/dwpose/yolox_l_8x8_300e_coco_20211126_140236-d3bd2b23.pth', 'pretrained_weights/dwpose/yolox_l_8x8_300e_coco.pth')
|
draw_dwpose.py
ADDED
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import cv2
|
3 |
+
import argparse
|
4 |
+
import numpy as np
|
5 |
+
from tqdm import tqdm
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
from pose.script.tool import save_videos_from_pil
|
9 |
+
from pose.script.dwpose import draw_pose
|
10 |
+
|
11 |
+
|
12 |
+
|
13 |
+
def draw_dwpose(video_path, pose_path, out_path, draw_face):
|
14 |
+
|
15 |
+
# capture video info
|
16 |
+
cap = cv2.VideoCapture(video_path)
|
17 |
+
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
18 |
+
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
19 |
+
fps = cap.get(cv2.CAP_PROP_FPS)
|
20 |
+
fps = int(np.around(fps))
|
21 |
+
# fps = get_fps(video_path)
|
22 |
+
cap.release()
|
23 |
+
|
24 |
+
# render resolution, short edge = 1024
|
25 |
+
k = float(1024) / min(width, height)
|
26 |
+
h_render = int(k*height//2 * 2)
|
27 |
+
w_render = int(k*width//2 * 2)
|
28 |
+
|
29 |
+
# save resolution, short edge = 768
|
30 |
+
k = float(768) / min(width, height)
|
31 |
+
h_save = int(k*height//2 * 2)
|
32 |
+
w_save = int(k*width//2 * 2)
|
33 |
+
|
34 |
+
poses = np.load(pose_path, allow_pickle=True)
|
35 |
+
poses = poses.tolist()
|
36 |
+
|
37 |
+
frames = []
|
38 |
+
for pose in tqdm(poses):
|
39 |
+
detected_map = draw_pose(pose, h_render, w_render, draw_face)
|
40 |
+
detected_map = cv2.resize(detected_map, (w_save, h_save), interpolation=cv2.INTER_AREA)
|
41 |
+
# cv2.imshow('', detected_map)
|
42 |
+
# cv2.waitKey(0)
|
43 |
+
detected_map = cv2.cvtColor(detected_map, cv2.COLOR_BGR2RGB)
|
44 |
+
detected_map = Image.fromarray(detected_map)
|
45 |
+
frames.append(detected_map)
|
46 |
+
|
47 |
+
save_videos_from_pil(frames, out_path, fps)
|
48 |
+
|
49 |
+
|
50 |
+
|
51 |
+
if __name__ == "__main__":
|
52 |
+
|
53 |
+
parser = argparse.ArgumentParser()
|
54 |
+
parser.add_argument("--video_dir", type=str, default="./UBC_fashion/test", help='dance video dir')
|
55 |
+
parser.add_argument("--pose_dir", type=str, default=None, help='auto makedir')
|
56 |
+
parser.add_argument("--save_dir", type=str, default=None, help='auto makedir')
|
57 |
+
parser.add_argument("--draw_face", type=bool, default=False, help='whether draw face or not')
|
58 |
+
args = parser.parse_args()
|
59 |
+
|
60 |
+
|
61 |
+
# video dir
|
62 |
+
video_dir = args.video_dir
|
63 |
+
|
64 |
+
# pose dir
|
65 |
+
if args.pose_dir is None:
|
66 |
+
pose_dir = args.video_dir + "_dwpose_keypoints"
|
67 |
+
else:
|
68 |
+
pose_dir = args.pose_dir
|
69 |
+
|
70 |
+
# save dir
|
71 |
+
if args.save_dir is None:
|
72 |
+
if args.draw_face == True:
|
73 |
+
save_dir = args.video_dir + "_dwpose"
|
74 |
+
else:
|
75 |
+
save_dir = args.video_dir + "_dwpose_without_face"
|
76 |
+
else:
|
77 |
+
save_dir = args.save_dir
|
78 |
+
if not os.path.exists(save_dir):
|
79 |
+
os.makedirs(save_dir)
|
80 |
+
|
81 |
+
|
82 |
+
# collect all video_folder paths
|
83 |
+
video_mp4_paths = set()
|
84 |
+
for root, dirs, files in os.walk(args.video_dir):
|
85 |
+
for name in files:
|
86 |
+
if name.endswith(".mp4"):
|
87 |
+
video_mp4_paths.add(os.path.join(root, name))
|
88 |
+
video_mp4_paths = list(video_mp4_paths)
|
89 |
+
# random.shuffle(video_mp4_paths)
|
90 |
+
video_mp4_paths.sort()
|
91 |
+
print("Num of videos:", len(video_mp4_paths))
|
92 |
+
|
93 |
+
|
94 |
+
# draw dwpose
|
95 |
+
for i in range(len(video_mp4_paths)):
|
96 |
+
video_path = video_mp4_paths[i]
|
97 |
+
video_name = os.path.relpath(video_path, video_dir)
|
98 |
+
base_name = os.path.splitext(video_name)[0]
|
99 |
+
|
100 |
+
pose_path = os.path.join(pose_dir, base_name + '.npy')
|
101 |
+
if not os.path.exists(pose_path):
|
102 |
+
print('no keypoint file:', pose_path)
|
103 |
+
|
104 |
+
out_path = os.path.join(save_dir, base_name + '.mp4')
|
105 |
+
if os.path.exists(out_path):
|
106 |
+
print('already have rendered pose:', out_path)
|
107 |
+
continue
|
108 |
+
|
109 |
+
draw_dwpose(video_path, pose_path, out_path, args.draw_face)
|
110 |
+
print(f"Process {i+1}/{len(video_mp4_paths)} video")
|
111 |
+
|
112 |
+
print('all done!')
|
gradio_app.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from musepose_inference import MusePoseInference
|
3 |
+
from pose_align import PoseAlignmentInference
|
4 |
+
|
5 |
+
class App:
|
6 |
+
def __init__(self):
|
7 |
+
self.pose_alignment_infer = MusePoseInference()
|
8 |
+
self.musepose_infer = PoseAlignmentInference()
|
9 |
+
|
10 |
+
def musepose_demo(self):
|
11 |
+
with gr.Blocks() as demo:
|
12 |
+
with gr.Tabs():
|
13 |
+
with gr.TabItem('Step1: Pose Alignment'):
|
14 |
+
with gr.Row():
|
15 |
+
with gr.Column(scale=3):
|
16 |
+
img_input = gr.Image(label="Input Image here", type="filepath", scale=5)
|
17 |
+
vid_dance_input = gr.Video(label="Input Dance Video", scale=5)
|
18 |
+
with gr.Column(scale=3):
|
19 |
+
vid_dance_output = gr.Video(label="Aligned pose output will be displayed here", scale=5)
|
20 |
+
vid_dance_output_demo = gr.Video(label="Output demo video will be displayed here", scale=5)
|
21 |
+
with gr.Column(scale=3):
|
22 |
+
with gr.Column():
|
23 |
+
nb_detect_resolution = gr.Number(label="Detect Resolution", value=512, precision=0)
|
24 |
+
nb_image_resolution = gr.Number(label="Image Resolution.", value=720, precision=0)
|
25 |
+
nb_align_frame = gr.Number(label="Align Frame", value=0, precision=0)
|
26 |
+
nb_max_frame = gr.Number(label="Max Frame", value=300, precision=0)
|
27 |
+
|
28 |
+
with gr.Row():
|
29 |
+
btn_algin_pose = gr.Button("ALIGN POSE", variant="primary")
|
30 |
+
|
31 |
+
btn_algin_pose.click(fn=self.pose_alignment_infer.align_pose,
|
32 |
+
inputs=[vid_dance_input, img_input, nb_detect_resolution, nb_image_resolution,
|
33 |
+
nb_align_frame, nb_max_frame],
|
34 |
+
outputs=[vid_dance_output, vid_dance_output_demo])
|
35 |
+
|
36 |
+
with gr.TabItem('Step2: MusePose Inference'):
|
37 |
+
with gr.Row():
|
38 |
+
with gr.Column(scale=3):
|
39 |
+
img_input = gr.Image(label="Input Image here", type="filepath", scale=5)
|
40 |
+
vid_pose_input = gr.Video(label="Input Aligned Pose Video here", scale=5)
|
41 |
+
with gr.Column(scale=3):
|
42 |
+
vid_output = gr.Video(label="Output Video will be displayed here", scale=5)
|
43 |
+
vid_output_demo = gr.Video(label="Output demo video will be displayed here", scale=5)
|
44 |
+
|
45 |
+
with gr.Column(scale=3):
|
46 |
+
with gr.Column():
|
47 |
+
weight_dtype = gr.Dropdown(label="Compute Type", choices=["fp16", "fp32"],
|
48 |
+
value="fp16")
|
49 |
+
nb_width = gr.Number(label="Width.", value=512, precision=0)
|
50 |
+
nb_height = gr.Number(label="Height.", value=512, precision=0)
|
51 |
+
nb_video_frame_length = gr.Number(label="Video Frame Length", value=300, precision=0)
|
52 |
+
nb_video_slice_frame_length = gr.Number(label="Video Slice Frame Number", value=48,
|
53 |
+
precision=0)
|
54 |
+
nb_video_slice_overlap_frame_number = gr.Number(
|
55 |
+
label="Video Slice Overlap Frame Number", value=4, precision=0)
|
56 |
+
nb_cfg = gr.Number(label="CFG (Classifier Free Guidance)", value=3.5, precision=0)
|
57 |
+
nb_seed = gr.Number(label="Seed", value=99, precision=0)
|
58 |
+
nb_steps = gr.Number(label="DDIM Sampling Steps", value=20, precision=0)
|
59 |
+
nb_fps = gr.Number(label="FPS (Frames Per Second) ", value=-1, precision=0,
|
60 |
+
info="Set to '-1' to use same FPS with pose's")
|
61 |
+
nb_skip = gr.Number(label="SKIP (Frame Sample Rate = SKIP+1)", value=1, precision=0)
|
62 |
+
|
63 |
+
with gr.Row():
|
64 |
+
btn_generate = gr.Button("GENERATE", variant="primary")
|
65 |
+
|
66 |
+
btn_generate.click(fn=self.musepose_infer.infer_musepose,
|
67 |
+
inputs=[img_input, vid_pose_input, weight_dtype, nb_width, nb_height,
|
68 |
+
nb_video_frame_length,
|
69 |
+
nb_video_slice_frame_length, nb_video_slice_overlap_frame_number, nb_cfg,
|
70 |
+
nb_seed,
|
71 |
+
nb_steps, nb_fps, nb_skip],
|
72 |
+
outputs=[vid_output, vid_output_demo])
|
73 |
+
return demo
|
74 |
+
|
75 |
+
def launch(self):
|
76 |
+
demo = self.musepose_demo()
|
77 |
+
demo.queue().launch()
|
musepose_inference.py
ADDED
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from datetime import datetime
|
3 |
+
from pathlib import Path
|
4 |
+
|
5 |
+
import torch
|
6 |
+
from diffusers import AutoencoderKL, DDIMScheduler
|
7 |
+
from einops import repeat
|
8 |
+
from omegaconf import OmegaConf
|
9 |
+
from PIL import Image
|
10 |
+
from torchvision import transforms
|
11 |
+
from transformers import CLIPVisionModelWithProjection
|
12 |
+
import torch.nn.functional as F
|
13 |
+
import gc
|
14 |
+
from huggingface_hub import hf_hub_download
|
15 |
+
|
16 |
+
from musepose.models.pose_guider import PoseGuider
|
17 |
+
from musepose.models.unet_2d_condition import UNet2DConditionModel
|
18 |
+
from musepose.models.unet_3d import UNet3DConditionModel
|
19 |
+
from musepose.pipelines.pipeline_pose2vid_long import Pose2VideoPipeline
|
20 |
+
from musepose.utils.util import get_fps, read_frames, save_videos_grid
|
21 |
+
|
22 |
+
|
23 |
+
class MusePoseInference:
|
24 |
+
def __init__(self):
|
25 |
+
self.image_gen_model_paths = {
|
26 |
+
"pretrained_base_model": "lambdalabs/sd-image-variations-diffusers/unet",
|
27 |
+
"pretrained_vae": "stabilityai/sd-vae-ft-mse",
|
28 |
+
"image_encoder": "lambdalabs/sd-image-variations-diffusers/image_encoder",
|
29 |
+
}
|
30 |
+
self.musepose_model_paths = {
|
31 |
+
"denoising_unet": os.path.join("pretrained_weights", "MusePose", "denoising_unet.pth"),
|
32 |
+
"reference_unet": os.path.join("pretrained_weights", "MusePose", "reference_unet.pth"),
|
33 |
+
"pose_guider": os.path.join("pretrained_weights", "MusePose", "pose_guider.pth"),
|
34 |
+
"motion_module": os.path.join("pretrained_weights", "MusePose", "pose_guider.pth"),
|
35 |
+
}
|
36 |
+
self.inference_config_path = os.path.join("configs", "inference_v2.yaml")
|
37 |
+
self.vae = None
|
38 |
+
self.reference_unet = None
|
39 |
+
self.denoising_unet = None
|
40 |
+
self.pose_guider = None
|
41 |
+
self.image_enc = None
|
42 |
+
self.pipe = None
|
43 |
+
self.output_dir = os.path.join("assets", "video")
|
44 |
+
#self.download_models()
|
45 |
+
|
46 |
+
def infer_musepose(
|
47 |
+
self,
|
48 |
+
ref_image_path: str,
|
49 |
+
pose_video_path: str,
|
50 |
+
weight_dtype: str,
|
51 |
+
W: int,
|
52 |
+
H: int,
|
53 |
+
L: int,
|
54 |
+
S: int,
|
55 |
+
O: int,
|
56 |
+
cfg: float,
|
57 |
+
seed: int,
|
58 |
+
steps: int,
|
59 |
+
fps: int,
|
60 |
+
skip: int
|
61 |
+
):
|
62 |
+
print(f"Model Paths: {self.musepose_model_paths}\n{self.image_gen_model_paths}\n{self.inference_config_path}")
|
63 |
+
print(f"Input Image Path: {ref_image_path}")
|
64 |
+
print(f"Pose Video Path: {pose_video_path}")
|
65 |
+
print(f"Dtype: {weight_dtype}")
|
66 |
+
print(f"Width: {W}")
|
67 |
+
print(f"Height: {H}")
|
68 |
+
print(f"Video Frame Length: {L}")
|
69 |
+
print(f"VIDEO SLICE FRAME LENGTH:: {S}")
|
70 |
+
print(f"VIDEO SLICE OVERLAP_FRAME NUMBER: {O}")
|
71 |
+
print(f"CFG: {cfg}")
|
72 |
+
print(f"Seed: {seed}")
|
73 |
+
print(f"Steps: {steps}")
|
74 |
+
print(f"FPS: {fps}")
|
75 |
+
print(f"Skip: {skip}")
|
76 |
+
|
77 |
+
image_file_name = os.path.splitext(os.path.basename(ref_image_path))[0]
|
78 |
+
pose_video_file_name = os.path.splitext(os.path.basename(pose_video_path))[0]
|
79 |
+
output_file_name = f"img_{image_file_name}_pose_{pose_video_file_name}"
|
80 |
+
output_path = os.path.abspath(os.path.join(self.output_dir, f'{output_file_name}.mp4'))
|
81 |
+
output_path_demo = os.path.abspath(os.path.join(self.output_dir, f'{output_file_name}_demo.mp4'))
|
82 |
+
|
83 |
+
if weight_dtype == "fp16":
|
84 |
+
weight_dtype = torch.float16
|
85 |
+
else:
|
86 |
+
weight_dtype = torch.float32
|
87 |
+
|
88 |
+
self.vae = AutoencoderKL.from_pretrained(
|
89 |
+
self.image_gen_model_paths["pretrained_vae"],
|
90 |
+
).to("cuda", dtype=weight_dtype)
|
91 |
+
|
92 |
+
self.reference_unet = UNet2DConditionModel.from_pretrained(
|
93 |
+
self.image_gen_model_paths["pretrained_base_model"],
|
94 |
+
subfolder="unet",
|
95 |
+
).to(dtype=weight_dtype, device="cuda")
|
96 |
+
|
97 |
+
inference_config_path = self.inference_config_path
|
98 |
+
infer_config = OmegaConf.load(inference_config_path)
|
99 |
+
|
100 |
+
self.denoising_unet = UNet3DConditionModel.from_pretrained_2d(
|
101 |
+
Path(self.image_gen_model_paths["pretrained_base_model"]),
|
102 |
+
Path(self.musepose_model_paths["motion_module"]),
|
103 |
+
subfolder="unet",
|
104 |
+
unet_additional_kwargs=infer_config.unet_additional_kwargs,
|
105 |
+
).to(dtype=weight_dtype, device="cuda")
|
106 |
+
|
107 |
+
self.pose_guider = PoseGuider(320, block_out_channels=(16, 32, 96, 256)).to(
|
108 |
+
dtype=weight_dtype, device="cuda"
|
109 |
+
)
|
110 |
+
|
111 |
+
self.image_enc = CLIPVisionModelWithProjection.from_pretrained(
|
112 |
+
self.image_gen_model_paths["image_encoder"]
|
113 |
+
).to(dtype=weight_dtype, device="cuda")
|
114 |
+
|
115 |
+
sched_kwargs = OmegaConf.to_container(infer_config.noise_scheduler_kwargs)
|
116 |
+
scheduler = DDIMScheduler(**sched_kwargs)
|
117 |
+
|
118 |
+
generator = torch.manual_seed(seed)
|
119 |
+
|
120 |
+
width, height = W, H
|
121 |
+
|
122 |
+
# load pretrained weights
|
123 |
+
self.denoising_unet.load_state_dict(
|
124 |
+
torch.load(self.musepose_model_paths["denoising_unet"], map_location="cpu"),
|
125 |
+
strict=False,
|
126 |
+
)
|
127 |
+
self.reference_unet.load_state_dict(
|
128 |
+
torch.load(self.musepose_model_paths["reference_unet"], map_location="cpu"),
|
129 |
+
)
|
130 |
+
self.pose_guider.load_state_dict(
|
131 |
+
torch.load(self.musepose_model_paths["pose_guider"], map_location="cpu"),
|
132 |
+
)
|
133 |
+
self.pipe = Pose2VideoPipeline(
|
134 |
+
vae=self.vae,
|
135 |
+
image_encoder=self.image_enc,
|
136 |
+
reference_unet=self.reference_unet,
|
137 |
+
denoising_unet=self.denoising_unet,
|
138 |
+
pose_guider=self.pose_guider,
|
139 |
+
scheduler=scheduler,
|
140 |
+
)
|
141 |
+
self.pipe = self.pipe.to("cuda", dtype=weight_dtype)
|
142 |
+
|
143 |
+
print("image: ", ref_image_path, "pose_video: ", pose_video_path)
|
144 |
+
|
145 |
+
ref_image_pil = Image.open(ref_image_path).convert("RGB")
|
146 |
+
|
147 |
+
pose_list = []
|
148 |
+
pose_tensor_list = []
|
149 |
+
pose_images = read_frames(pose_video_path)
|
150 |
+
src_fps = get_fps(pose_video_path)
|
151 |
+
print(f"pose video has {len(pose_images)} frames, with {src_fps} fps")
|
152 |
+
L = min(L, len(pose_images))
|
153 |
+
pose_transform = transforms.Compose(
|
154 |
+
[transforms.Resize((height, width)), transforms.ToTensor()]
|
155 |
+
)
|
156 |
+
original_width, original_height = 0, 0
|
157 |
+
|
158 |
+
pose_images = pose_images[::skip + 1]
|
159 |
+
print("processing length:", len(pose_images))
|
160 |
+
src_fps = src_fps // (skip + 1)
|
161 |
+
print("fps", src_fps)
|
162 |
+
L = L // ((skip + 1))
|
163 |
+
|
164 |
+
for pose_image_pil in pose_images[: L]:
|
165 |
+
pose_tensor_list.append(pose_transform(pose_image_pil))
|
166 |
+
pose_list.append(pose_image_pil)
|
167 |
+
original_width, original_height = pose_image_pil.size
|
168 |
+
pose_image_pil = pose_image_pil.resize((width, height))
|
169 |
+
|
170 |
+
# repeart the last segment
|
171 |
+
last_segment_frame_num = (L - S) % (S - O)
|
172 |
+
repeart_frame_num = (S - O - last_segment_frame_num) % (S - O)
|
173 |
+
for i in range(repeart_frame_num):
|
174 |
+
pose_list.append(pose_list[-1])
|
175 |
+
pose_tensor_list.append(pose_tensor_list[-1])
|
176 |
+
|
177 |
+
ref_image_tensor = pose_transform(ref_image_pil) # (c, h, w)
|
178 |
+
ref_image_tensor = ref_image_tensor.unsqueeze(1).unsqueeze(0) # (1, c, 1, h, w)
|
179 |
+
ref_image_tensor = repeat(ref_image_tensor, "b c f h w -> b c (repeat f) h w", repeat=L)
|
180 |
+
|
181 |
+
pose_tensor = torch.stack(pose_tensor_list, dim=0) # (f, c, h, w)
|
182 |
+
pose_tensor = pose_tensor.transpose(0, 1)
|
183 |
+
pose_tensor = pose_tensor.unsqueeze(0)
|
184 |
+
|
185 |
+
video = self.pipe(
|
186 |
+
ref_image_pil,
|
187 |
+
pose_list,
|
188 |
+
width,
|
189 |
+
height,
|
190 |
+
len(pose_list),
|
191 |
+
steps,
|
192 |
+
cfg,
|
193 |
+
generator=generator,
|
194 |
+
context_frames=S,
|
195 |
+
context_stride=1,
|
196 |
+
context_overlap=O,
|
197 |
+
).videos
|
198 |
+
|
199 |
+
result = self.scale_video(video[:, :, :L], original_width, original_height)
|
200 |
+
save_videos_grid(
|
201 |
+
result,
|
202 |
+
output_path,
|
203 |
+
n_rows=1,
|
204 |
+
fps=src_fps if fps is None or fps < 0 else fps,
|
205 |
+
)
|
206 |
+
|
207 |
+
video = torch.cat([ref_image_tensor, pose_tensor[:, :, :L], video[:, :, :L]], dim=0)
|
208 |
+
video = self.scale_video(video, original_width, original_height)
|
209 |
+
save_videos_grid(
|
210 |
+
video,
|
211 |
+
output_path_demo,
|
212 |
+
n_rows=3,
|
213 |
+
fps=src_fps if fps is None or fps < 0 else fps,
|
214 |
+
)
|
215 |
+
self.release_vram()
|
216 |
+
return output_path, output_path_demo
|
217 |
+
|
218 |
+
def download_models(self):
|
219 |
+
repo_id = 'jhj0517/MusePose'
|
220 |
+
for name, file_path in self.musepose_model_paths.items():
|
221 |
+
local_dir, filename = os.path.dirname(file_path), os.path.basename(file_path)
|
222 |
+
if not os.path.exists(local_dir):
|
223 |
+
os.makedirs(local_dir)
|
224 |
+
|
225 |
+
remote_filepath = os.path.join("MusePose", filename)
|
226 |
+
if not os.path.exists(file_path):
|
227 |
+
hf_hub_download(repo_id=repo_id, filename=remote_filepath,
|
228 |
+
local_dir=local_dir,
|
229 |
+
local_dir_use_symlinks=False)
|
230 |
+
|
231 |
+
def release_vram(self):
|
232 |
+
models = [
|
233 |
+
'vae', 'reference_unet', 'denoising_unet',
|
234 |
+
'pose_guider', 'image_enc', 'pipe'
|
235 |
+
]
|
236 |
+
|
237 |
+
for model_name in models:
|
238 |
+
model = getattr(self, model_name, None)
|
239 |
+
if model is not None:
|
240 |
+
del model
|
241 |
+
setattr(self, model_name, None)
|
242 |
+
|
243 |
+
if torch.cuda.is_available():
|
244 |
+
torch.cuda.empty_cache()
|
245 |
+
gc.collect()
|
246 |
+
|
247 |
+
@staticmethod
|
248 |
+
def scale_video(video, width, height):
|
249 |
+
video_reshaped = video.view(-1, *video.shape[2:]) # [batch*frames, channels, height, width]
|
250 |
+
scaled_video = F.interpolate(video_reshaped, size=(height, width), mode='bilinear', align_corners=False)
|
251 |
+
scaled_video = scaled_video.view(*video.shape[:2], scaled_video.shape[1], height,
|
252 |
+
width) # [batch, frames, channels, height, width]
|
253 |
+
|
254 |
+
return scaled_video
|
pose/config/dwpose-l_384x288.py
ADDED
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# runtime
|
2 |
+
max_epochs = 270
|
3 |
+
stage2_num_epochs = 30
|
4 |
+
base_lr = 4e-3
|
5 |
+
|
6 |
+
train_cfg = dict(max_epochs=max_epochs, val_interval=10)
|
7 |
+
randomness = dict(seed=21)
|
8 |
+
|
9 |
+
# optimizer
|
10 |
+
optim_wrapper = dict(
|
11 |
+
type='OptimWrapper',
|
12 |
+
optimizer=dict(type='AdamW', lr=base_lr, weight_decay=0.05),
|
13 |
+
paramwise_cfg=dict(
|
14 |
+
norm_decay_mult=0, bias_decay_mult=0, bypass_duplicate=True))
|
15 |
+
|
16 |
+
# learning rate
|
17 |
+
param_scheduler = [
|
18 |
+
dict(
|
19 |
+
type='LinearLR',
|
20 |
+
start_factor=1.0e-5,
|
21 |
+
by_epoch=False,
|
22 |
+
begin=0,
|
23 |
+
end=1000),
|
24 |
+
dict(
|
25 |
+
# use cosine lr from 150 to 300 epoch
|
26 |
+
type='CosineAnnealingLR',
|
27 |
+
eta_min=base_lr * 0.05,
|
28 |
+
begin=max_epochs // 2,
|
29 |
+
end=max_epochs,
|
30 |
+
T_max=max_epochs // 2,
|
31 |
+
by_epoch=True,
|
32 |
+
convert_to_iter_based=True),
|
33 |
+
]
|
34 |
+
|
35 |
+
# automatically scaling LR based on the actual training batch size
|
36 |
+
auto_scale_lr = dict(base_batch_size=512)
|
37 |
+
|
38 |
+
# codec settings
|
39 |
+
codec = dict(
|
40 |
+
type='SimCCLabel',
|
41 |
+
input_size=(288, 384),
|
42 |
+
sigma=(6., 6.93),
|
43 |
+
simcc_split_ratio=2.0,
|
44 |
+
normalize=False,
|
45 |
+
use_dark=False)
|
46 |
+
|
47 |
+
# model settings
|
48 |
+
model = dict(
|
49 |
+
type='TopdownPoseEstimator',
|
50 |
+
data_preprocessor=dict(
|
51 |
+
type='PoseDataPreprocessor',
|
52 |
+
mean=[123.675, 116.28, 103.53],
|
53 |
+
std=[58.395, 57.12, 57.375],
|
54 |
+
bgr_to_rgb=True),
|
55 |
+
backbone=dict(
|
56 |
+
_scope_='mmdet',
|
57 |
+
type='CSPNeXt',
|
58 |
+
arch='P5',
|
59 |
+
expand_ratio=0.5,
|
60 |
+
deepen_factor=1.,
|
61 |
+
widen_factor=1.,
|
62 |
+
out_indices=(4, ),
|
63 |
+
channel_attention=True,
|
64 |
+
norm_cfg=dict(type='SyncBN'),
|
65 |
+
act_cfg=dict(type='SiLU'),
|
66 |
+
init_cfg=dict(
|
67 |
+
type='Pretrained',
|
68 |
+
prefix='backbone.',
|
69 |
+
checkpoint='https://download.openmmlab.com/mmpose/v1/projects/'
|
70 |
+
'rtmpose/cspnext-l_udp-aic-coco_210e-256x192-273b7631_20230130.pth' # noqa
|
71 |
+
)),
|
72 |
+
head=dict(
|
73 |
+
type='RTMCCHead',
|
74 |
+
in_channels=1024,
|
75 |
+
out_channels=133,
|
76 |
+
input_size=codec['input_size'],
|
77 |
+
in_featuremap_size=(9, 12),
|
78 |
+
simcc_split_ratio=codec['simcc_split_ratio'],
|
79 |
+
final_layer_kernel_size=7,
|
80 |
+
gau_cfg=dict(
|
81 |
+
hidden_dims=256,
|
82 |
+
s=128,
|
83 |
+
expansion_factor=2,
|
84 |
+
dropout_rate=0.,
|
85 |
+
drop_path=0.,
|
86 |
+
act_fn='SiLU',
|
87 |
+
use_rel_bias=False,
|
88 |
+
pos_enc=False),
|
89 |
+
loss=dict(
|
90 |
+
type='KLDiscretLoss',
|
91 |
+
use_target_weight=True,
|
92 |
+
beta=10.,
|
93 |
+
label_softmax=True),
|
94 |
+
decoder=codec),
|
95 |
+
test_cfg=dict(flip_test=True, ))
|
96 |
+
|
97 |
+
# base dataset settings
|
98 |
+
dataset_type = 'CocoWholeBodyDataset'
|
99 |
+
data_mode = 'topdown'
|
100 |
+
data_root = '/data/'
|
101 |
+
|
102 |
+
backend_args = dict(backend='local')
|
103 |
+
# backend_args = dict(
|
104 |
+
# backend='petrel',
|
105 |
+
# path_mapping=dict({
|
106 |
+
# f'{data_root}': 's3://openmmlab/datasets/detection/coco/',
|
107 |
+
# f'{data_root}': 's3://openmmlab/datasets/detection/coco/'
|
108 |
+
# }))
|
109 |
+
|
110 |
+
# pipelines
|
111 |
+
train_pipeline = [
|
112 |
+
dict(type='LoadImage', backend_args=backend_args),
|
113 |
+
dict(type='GetBBoxCenterScale'),
|
114 |
+
dict(type='RandomFlip', direction='horizontal'),
|
115 |
+
dict(type='RandomHalfBody'),
|
116 |
+
dict(
|
117 |
+
type='RandomBBoxTransform', scale_factor=[0.6, 1.4], rotate_factor=80),
|
118 |
+
dict(type='TopdownAffine', input_size=codec['input_size']),
|
119 |
+
dict(type='mmdet.YOLOXHSVRandomAug'),
|
120 |
+
dict(
|
121 |
+
type='Albumentation',
|
122 |
+
transforms=[
|
123 |
+
dict(type='Blur', p=0.1),
|
124 |
+
dict(type='MedianBlur', p=0.1),
|
125 |
+
dict(
|
126 |
+
type='CoarseDropout',
|
127 |
+
max_holes=1,
|
128 |
+
max_height=0.4,
|
129 |
+
max_width=0.4,
|
130 |
+
min_holes=1,
|
131 |
+
min_height=0.2,
|
132 |
+
min_width=0.2,
|
133 |
+
p=1.0),
|
134 |
+
]),
|
135 |
+
dict(type='GenerateTarget', encoder=codec),
|
136 |
+
dict(type='PackPoseInputs')
|
137 |
+
]
|
138 |
+
val_pipeline = [
|
139 |
+
dict(type='LoadImage', backend_args=backend_args),
|
140 |
+
dict(type='GetBBoxCenterScale'),
|
141 |
+
dict(type='TopdownAffine', input_size=codec['input_size']),
|
142 |
+
dict(type='PackPoseInputs')
|
143 |
+
]
|
144 |
+
|
145 |
+
train_pipeline_stage2 = [
|
146 |
+
dict(type='LoadImage', backend_args=backend_args),
|
147 |
+
dict(type='GetBBoxCenterScale'),
|
148 |
+
dict(type='RandomFlip', direction='horizontal'),
|
149 |
+
dict(type='RandomHalfBody'),
|
150 |
+
dict(
|
151 |
+
type='RandomBBoxTransform',
|
152 |
+
shift_factor=0.,
|
153 |
+
scale_factor=[0.75, 1.25],
|
154 |
+
rotate_factor=60),
|
155 |
+
dict(type='TopdownAffine', input_size=codec['input_size']),
|
156 |
+
dict(type='mmdet.YOLOXHSVRandomAug'),
|
157 |
+
dict(
|
158 |
+
type='Albumentation',
|
159 |
+
transforms=[
|
160 |
+
dict(type='Blur', p=0.1),
|
161 |
+
dict(type='MedianBlur', p=0.1),
|
162 |
+
dict(
|
163 |
+
type='CoarseDropout',
|
164 |
+
max_holes=1,
|
165 |
+
max_height=0.4,
|
166 |
+
max_width=0.4,
|
167 |
+
min_holes=1,
|
168 |
+
min_height=0.2,
|
169 |
+
min_width=0.2,
|
170 |
+
p=0.5),
|
171 |
+
]),
|
172 |
+
dict(type='GenerateTarget', encoder=codec),
|
173 |
+
dict(type='PackPoseInputs')
|
174 |
+
]
|
175 |
+
|
176 |
+
datasets = []
|
177 |
+
dataset_coco=dict(
|
178 |
+
type=dataset_type,
|
179 |
+
data_root=data_root,
|
180 |
+
data_mode=data_mode,
|
181 |
+
ann_file='coco/annotations/coco_wholebody_train_v1.0.json',
|
182 |
+
data_prefix=dict(img='coco/train2017/'),
|
183 |
+
pipeline=[],
|
184 |
+
)
|
185 |
+
datasets.append(dataset_coco)
|
186 |
+
|
187 |
+
scene = ['Magic_show', 'Entertainment', 'ConductMusic', 'Online_class',
|
188 |
+
'TalkShow', 'Speech', 'Fitness', 'Interview', 'Olympic', 'TVShow',
|
189 |
+
'Singing', 'SignLanguage', 'Movie', 'LiveVlog', 'VideoConference']
|
190 |
+
|
191 |
+
for i in range(len(scene)):
|
192 |
+
datasets.append(
|
193 |
+
dict(
|
194 |
+
type=dataset_type,
|
195 |
+
data_root=data_root,
|
196 |
+
data_mode=data_mode,
|
197 |
+
ann_file='UBody/annotations/'+scene[i]+'/keypoint_annotation.json',
|
198 |
+
data_prefix=dict(img='UBody/images/'+scene[i]+'/'),
|
199 |
+
pipeline=[],
|
200 |
+
)
|
201 |
+
)
|
202 |
+
|
203 |
+
# data loaders
|
204 |
+
train_dataloader = dict(
|
205 |
+
batch_size=32,
|
206 |
+
num_workers=10,
|
207 |
+
persistent_workers=True,
|
208 |
+
sampler=dict(type='DefaultSampler', shuffle=True),
|
209 |
+
dataset=dict(
|
210 |
+
type='CombinedDataset',
|
211 |
+
metainfo=dict(from_file='configs/_base_/datasets/coco_wholebody.py'),
|
212 |
+
datasets=datasets,
|
213 |
+
pipeline=train_pipeline,
|
214 |
+
test_mode=False,
|
215 |
+
))
|
216 |
+
val_dataloader = dict(
|
217 |
+
batch_size=32,
|
218 |
+
num_workers=10,
|
219 |
+
persistent_workers=True,
|
220 |
+
drop_last=False,
|
221 |
+
sampler=dict(type='DefaultSampler', shuffle=False, round_up=False),
|
222 |
+
dataset=dict(
|
223 |
+
type=dataset_type,
|
224 |
+
data_root=data_root,
|
225 |
+
data_mode=data_mode,
|
226 |
+
ann_file='coco/annotations/coco_wholebody_val_v1.0.json',
|
227 |
+
bbox_file=f'{data_root}coco/person_detection_results/'
|
228 |
+
'COCO_val2017_detections_AP_H_56_person.json',
|
229 |
+
data_prefix=dict(img='coco/val2017/'),
|
230 |
+
test_mode=True,
|
231 |
+
pipeline=val_pipeline,
|
232 |
+
))
|
233 |
+
test_dataloader = val_dataloader
|
234 |
+
|
235 |
+
# hooks
|
236 |
+
default_hooks = dict(
|
237 |
+
checkpoint=dict(
|
238 |
+
save_best='coco-wholebody/AP', rule='greater', max_keep_ckpts=1))
|
239 |
+
|
240 |
+
custom_hooks = [
|
241 |
+
dict(
|
242 |
+
type='EMAHook',
|
243 |
+
ema_type='ExpMomentumEMA',
|
244 |
+
momentum=0.0002,
|
245 |
+
update_buffers=True,
|
246 |
+
priority=49),
|
247 |
+
dict(
|
248 |
+
type='mmdet.PipelineSwitchHook',
|
249 |
+
switch_epoch=max_epochs - stage2_num_epochs,
|
250 |
+
switch_pipeline=train_pipeline_stage2)
|
251 |
+
]
|
252 |
+
|
253 |
+
# evaluators
|
254 |
+
val_evaluator = dict(
|
255 |
+
type='CocoWholeBodyMetric',
|
256 |
+
ann_file=data_root + 'coco/annotations/coco_wholebody_val_v1.0.json')
|
257 |
+
test_evaluator = val_evaluator
|
pose/config/yolox_l_8xb8-300e_coco.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
img_scale = (640, 640) # width, height
|
2 |
+
|
3 |
+
# model settings
|
4 |
+
model = dict(
|
5 |
+
type='YOLOX',
|
6 |
+
data_preprocessor=dict(
|
7 |
+
type='DetDataPreprocessor',
|
8 |
+
pad_size_divisor=32,
|
9 |
+
batch_augments=[
|
10 |
+
dict(
|
11 |
+
type='BatchSyncRandomResize',
|
12 |
+
random_size_range=(480, 800),
|
13 |
+
size_divisor=32,
|
14 |
+
interval=10)
|
15 |
+
]),
|
16 |
+
backbone=dict(
|
17 |
+
type='CSPDarknet',
|
18 |
+
deepen_factor=1.0,
|
19 |
+
widen_factor=1.0,
|
20 |
+
out_indices=(2, 3, 4),
|
21 |
+
use_depthwise=False,
|
22 |
+
spp_kernal_sizes=(5, 9, 13),
|
23 |
+
norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
|
24 |
+
act_cfg=dict(type='Swish'),
|
25 |
+
),
|
26 |
+
neck=dict(
|
27 |
+
type='YOLOXPAFPN',
|
28 |
+
in_channels=[256, 512, 1024],
|
29 |
+
out_channels=256,
|
30 |
+
num_csp_blocks=3,
|
31 |
+
use_depthwise=False,
|
32 |
+
upsample_cfg=dict(scale_factor=2, mode='nearest'),
|
33 |
+
norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
|
34 |
+
act_cfg=dict(type='Swish')),
|
35 |
+
bbox_head=dict(
|
36 |
+
type='YOLOXHead',
|
37 |
+
num_classes=80,
|
38 |
+
in_channels=256,
|
39 |
+
feat_channels=256,
|
40 |
+
stacked_convs=2,
|
41 |
+
strides=(8, 16, 32),
|
42 |
+
use_depthwise=False,
|
43 |
+
norm_cfg=dict(type='BN', momentum=0.03, eps=0.001),
|
44 |
+
act_cfg=dict(type='Swish'),
|
45 |
+
loss_cls=dict(
|
46 |
+
type='CrossEntropyLoss',
|
47 |
+
use_sigmoid=True,
|
48 |
+
reduction='sum',
|
49 |
+
loss_weight=1.0),
|
50 |
+
loss_bbox=dict(
|
51 |
+
type='IoULoss',
|
52 |
+
mode='square',
|
53 |
+
eps=1e-16,
|
54 |
+
reduction='sum',
|
55 |
+
loss_weight=5.0),
|
56 |
+
loss_obj=dict(
|
57 |
+
type='CrossEntropyLoss',
|
58 |
+
use_sigmoid=True,
|
59 |
+
reduction='sum',
|
60 |
+
loss_weight=1.0),
|
61 |
+
loss_l1=dict(type='L1Loss', reduction='sum', loss_weight=1.0)),
|
62 |
+
train_cfg=dict(assigner=dict(type='SimOTAAssigner', center_radius=2.5)),
|
63 |
+
# In order to align the source code, the threshold of the val phase is
|
64 |
+
# 0.01, and the threshold of the test phase is 0.001.
|
65 |
+
test_cfg=dict(score_thr=0.01, nms=dict(type='nms', iou_threshold=0.65)))
|
66 |
+
|
67 |
+
# dataset settings
|
68 |
+
data_root = 'data/coco/'
|
69 |
+
dataset_type = 'CocoDataset'
|
70 |
+
|
71 |
+
# Example to use different file client
|
72 |
+
# Method 1: simply set the data root and let the file I/O module
|
73 |
+
# automatically infer from prefix (not support LMDB and Memcache yet)
|
74 |
+
|
75 |
+
# data_root = 's3://openmmlab/datasets/detection/coco/'
|
76 |
+
|
77 |
+
# Method 2: Use `backend_args`, `file_client_args` in versions before 3.0.0rc6
|
78 |
+
# backend_args = dict(
|
79 |
+
# backend='petrel',
|
80 |
+
# path_mapping=dict({
|
81 |
+
# './data/': 's3://openmmlab/datasets/detection/',
|
82 |
+
# 'data/': 's3://openmmlab/datasets/detection/'
|
83 |
+
# }))
|
84 |
+
backend_args = None
|
85 |
+
|
86 |
+
train_pipeline = [
|
87 |
+
dict(type='Mosaic', img_scale=img_scale, pad_val=114.0),
|
88 |
+
dict(
|
89 |
+
type='RandomAffine',
|
90 |
+
scaling_ratio_range=(0.1, 2),
|
91 |
+
# img_scale is (width, height)
|
92 |
+
border=(-img_scale[0] // 2, -img_scale[1] // 2)),
|
93 |
+
dict(
|
94 |
+
type='MixUp',
|
95 |
+
img_scale=img_scale,
|
96 |
+
ratio_range=(0.8, 1.6),
|
97 |
+
pad_val=114.0),
|
98 |
+
dict(type='YOLOXHSVRandomAug'),
|
99 |
+
dict(type='RandomFlip', prob=0.5),
|
100 |
+
# According to the official implementation, multi-scale
|
101 |
+
# training is not considered here but in the
|
102 |
+
# 'mmdet/models/detectors/yolox.py'.
|
103 |
+
# Resize and Pad are for the last 15 epochs when Mosaic,
|
104 |
+
# RandomAffine, and MixUp are closed by YOLOXModeSwitchHook.
|
105 |
+
dict(type='Resize', scale=img_scale, keep_ratio=True),
|
106 |
+
dict(
|
107 |
+
type='Pad',
|
108 |
+
pad_to_square=True,
|
109 |
+
# If the image is three-channel, the pad value needs
|
110 |
+
# to be set separately for each channel.
|
111 |
+
pad_val=dict(img=(114.0, 114.0, 114.0))),
|
112 |
+
dict(type='FilterAnnotations', min_gt_bbox_wh=(1, 1), keep_empty=False),
|
113 |
+
dict(type='PackDetInputs')
|
114 |
+
]
|
115 |
+
|
116 |
+
train_dataset = dict(
|
117 |
+
# use MultiImageMixDataset wrapper to support mosaic and mixup
|
118 |
+
type='MultiImageMixDataset',
|
119 |
+
dataset=dict(
|
120 |
+
type=dataset_type,
|
121 |
+
data_root=data_root,
|
122 |
+
ann_file='annotations/instances_train2017.json',
|
123 |
+
data_prefix=dict(img='train2017/'),
|
124 |
+
pipeline=[
|
125 |
+
dict(type='LoadImageFromFile', backend_args=backend_args),
|
126 |
+
dict(type='LoadAnnotations', with_bbox=True)
|
127 |
+
],
|
128 |
+
filter_cfg=dict(filter_empty_gt=False, min_size=32),
|
129 |
+
backend_args=backend_args),
|
130 |
+
pipeline=train_pipeline)
|
131 |
+
|
132 |
+
test_pipeline = [
|
133 |
+
dict(type='LoadImageFromFile', backend_args=backend_args),
|
134 |
+
dict(type='Resize', scale=img_scale, keep_ratio=True),
|
135 |
+
dict(
|
136 |
+
type='Pad',
|
137 |
+
pad_to_square=True,
|
138 |
+
pad_val=dict(img=(114.0, 114.0, 114.0))),
|
139 |
+
dict(type='LoadAnnotations', with_bbox=True),
|
140 |
+
dict(
|
141 |
+
type='PackDetInputs',
|
142 |
+
meta_keys=('img_id', 'img_path', 'ori_shape', 'img_shape',
|
143 |
+
'scale_factor'))
|
144 |
+
]
|
145 |
+
|
146 |
+
train_dataloader = dict(
|
147 |
+
batch_size=8,
|
148 |
+
num_workers=4,
|
149 |
+
persistent_workers=True,
|
150 |
+
sampler=dict(type='DefaultSampler', shuffle=True),
|
151 |
+
dataset=train_dataset)
|
152 |
+
val_dataloader = dict(
|
153 |
+
batch_size=8,
|
154 |
+
num_workers=4,
|
155 |
+
persistent_workers=True,
|
156 |
+
drop_last=False,
|
157 |
+
sampler=dict(type='DefaultSampler', shuffle=False),
|
158 |
+
dataset=dict(
|
159 |
+
type=dataset_type,
|
160 |
+
data_root=data_root,
|
161 |
+
ann_file='annotations/instances_val2017.json',
|
162 |
+
data_prefix=dict(img='val2017/'),
|
163 |
+
test_mode=True,
|
164 |
+
pipeline=test_pipeline,
|
165 |
+
backend_args=backend_args))
|
166 |
+
test_dataloader = val_dataloader
|
167 |
+
|
168 |
+
val_evaluator = dict(
|
169 |
+
type='CocoMetric',
|
170 |
+
ann_file=data_root + 'annotations/instances_val2017.json',
|
171 |
+
metric='bbox',
|
172 |
+
backend_args=backend_args)
|
173 |
+
test_evaluator = val_evaluator
|
174 |
+
|
175 |
+
# training settings
|
176 |
+
max_epochs = 300
|
177 |
+
num_last_epochs = 15
|
178 |
+
interval = 10
|
179 |
+
|
180 |
+
train_cfg = dict(max_epochs=max_epochs, val_interval=interval)
|
181 |
+
|
182 |
+
# optimizer
|
183 |
+
# default 8 gpu
|
184 |
+
base_lr = 0.01
|
185 |
+
optim_wrapper = dict(
|
186 |
+
type='OptimWrapper',
|
187 |
+
optimizer=dict(
|
188 |
+
type='SGD', lr=base_lr, momentum=0.9, weight_decay=5e-4,
|
189 |
+
nesterov=True),
|
190 |
+
paramwise_cfg=dict(norm_decay_mult=0., bias_decay_mult=0.))
|
191 |
+
|
192 |
+
# learning rate
|
193 |
+
param_scheduler = [
|
194 |
+
dict(
|
195 |
+
# use quadratic formula to warm up 5 epochs
|
196 |
+
# and lr is updated by iteration
|
197 |
+
# TODO: fix default scope in get function
|
198 |
+
type='mmdet.QuadraticWarmupLR',
|
199 |
+
by_epoch=True,
|
200 |
+
begin=0,
|
201 |
+
end=5,
|
202 |
+
convert_to_iter_based=True),
|
203 |
+
dict(
|
204 |
+
# use cosine lr from 5 to 285 epoch
|
205 |
+
type='CosineAnnealingLR',
|
206 |
+
eta_min=base_lr * 0.05,
|
207 |
+
begin=5,
|
208 |
+
T_max=max_epochs - num_last_epochs,
|
209 |
+
end=max_epochs - num_last_epochs,
|
210 |
+
by_epoch=True,
|
211 |
+
convert_to_iter_based=True),
|
212 |
+
dict(
|
213 |
+
# use fixed lr during last 15 epochs
|
214 |
+
type='ConstantLR',
|
215 |
+
by_epoch=True,
|
216 |
+
factor=1,
|
217 |
+
begin=max_epochs - num_last_epochs,
|
218 |
+
end=max_epochs,
|
219 |
+
)
|
220 |
+
]
|
221 |
+
|
222 |
+
default_hooks = dict(
|
223 |
+
checkpoint=dict(
|
224 |
+
interval=interval,
|
225 |
+
max_keep_ckpts=3 # only keep latest 3 checkpoints
|
226 |
+
))
|
227 |
+
|
228 |
+
custom_hooks = [
|
229 |
+
dict(
|
230 |
+
type='YOLOXModeSwitchHook',
|
231 |
+
num_last_epochs=num_last_epochs,
|
232 |
+
priority=48),
|
233 |
+
dict(type='SyncNormHook', priority=48),
|
234 |
+
dict(
|
235 |
+
type='EMAHook',
|
236 |
+
ema_type='ExpMomentumEMA',
|
237 |
+
momentum=0.0001,
|
238 |
+
update_buffers=True,
|
239 |
+
priority=49)
|
240 |
+
]
|
241 |
+
|
242 |
+
# NOTE: `auto_scale_lr` is for automatically scaling LR,
|
243 |
+
# USER SHOULD NOT CHANGE ITS VALUES.
|
244 |
+
# base_batch_size = (8 GPUs) x (8 samples per GPU)
|
245 |
+
auto_scale_lr = dict(base_batch_size=64)
|
pose/script/dwpose.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Openpose
|
2 |
+
# Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose
|
3 |
+
# 2nd Edited by https://github.com/Hzzone/pytorch-openpose
|
4 |
+
# 3rd Edited by ControlNet
|
5 |
+
# 4th Edited by ControlNet (added face and correct hands)
|
6 |
+
|
7 |
+
import os
|
8 |
+
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
|
9 |
+
|
10 |
+
import cv2
|
11 |
+
import torch
|
12 |
+
import numpy as np
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
|
16 |
+
import pose.script.util as util
|
17 |
+
|
18 |
+
def resize_image(input_image, resolution):
|
19 |
+
H, W, C = input_image.shape
|
20 |
+
H = float(H)
|
21 |
+
W = float(W)
|
22 |
+
k = float(resolution) / min(H, W)
|
23 |
+
H *= k
|
24 |
+
W *= k
|
25 |
+
H = int(np.round(H / 64.0)) * 64
|
26 |
+
W = int(np.round(W / 64.0)) * 64
|
27 |
+
img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
|
28 |
+
return img
|
29 |
+
|
30 |
+
def HWC3(x):
|
31 |
+
assert x.dtype == np.uint8
|
32 |
+
if x.ndim == 2:
|
33 |
+
x = x[:, :, None]
|
34 |
+
assert x.ndim == 3
|
35 |
+
H, W, C = x.shape
|
36 |
+
assert C == 1 or C == 3 or C == 4
|
37 |
+
if C == 3:
|
38 |
+
return x
|
39 |
+
if C == 1:
|
40 |
+
return np.concatenate([x, x, x], axis=2)
|
41 |
+
if C == 4:
|
42 |
+
color = x[:, :, 0:3].astype(np.float32)
|
43 |
+
alpha = x[:, :, 3:4].astype(np.float32) / 255.0
|
44 |
+
y = color * alpha + 255.0 * (1.0 - alpha)
|
45 |
+
y = y.clip(0, 255).astype(np.uint8)
|
46 |
+
return y
|
47 |
+
|
48 |
+
def draw_pose(pose, H, W, draw_face):
|
49 |
+
bodies = pose['bodies']
|
50 |
+
faces = pose['faces']
|
51 |
+
hands = pose['hands']
|
52 |
+
candidate = bodies['candidate']
|
53 |
+
subset = bodies['subset']
|
54 |
+
|
55 |
+
# only the most significant person
|
56 |
+
faces = pose['faces'][:1]
|
57 |
+
hands = pose['hands'][:2]
|
58 |
+
candidate = bodies['candidate'][:18]
|
59 |
+
subset = bodies['subset'][:1]
|
60 |
+
|
61 |
+
# draw
|
62 |
+
canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)
|
63 |
+
canvas = util.draw_bodypose(canvas, candidate, subset)
|
64 |
+
canvas = util.draw_handpose(canvas, hands)
|
65 |
+
if draw_face == True:
|
66 |
+
canvas = util.draw_facepose(canvas, faces)
|
67 |
+
|
68 |
+
return canvas
|
69 |
+
|
70 |
+
class DWposeDetector:
|
71 |
+
def __init__(self, det_config=None, det_ckpt=None, pose_config=None, pose_ckpt=None, device="cpu", keypoints_only=False):
|
72 |
+
from pose.script.wholebody import Wholebody
|
73 |
+
|
74 |
+
self.pose_estimation = Wholebody(det_config, det_ckpt, pose_config, pose_ckpt, device)
|
75 |
+
self.keypoints_only = keypoints_only
|
76 |
+
def to(self, device):
|
77 |
+
self.pose_estimation.to(device)
|
78 |
+
return self
|
79 |
+
'''
|
80 |
+
detect_resolution: 短边resize到多少 这是 draw pose 时的原始渲染分辨率。建议1024
|
81 |
+
image_resolution: 短边resize到多少 这是 save pose 时的文件分辨率。建议768
|
82 |
+
|
83 |
+
实际检测分辨率:
|
84 |
+
yolox: (640, 640)
|
85 |
+
dwpose:(288, 384)
|
86 |
+
'''
|
87 |
+
|
88 |
+
def __call__(self, input_image, detect_resolution=1024, image_resolution=768, output_type="pil", **kwargs):
|
89 |
+
|
90 |
+
input_image = cv2.cvtColor(np.array(input_image, dtype=np.uint8), cv2.COLOR_RGB2BGR)
|
91 |
+
# cv2.imshow('', input_image)
|
92 |
+
# cv2.waitKey(0)
|
93 |
+
|
94 |
+
input_image = HWC3(input_image)
|
95 |
+
input_image = resize_image(input_image, detect_resolution)
|
96 |
+
H, W, C = input_image.shape
|
97 |
+
|
98 |
+
with torch.no_grad():
|
99 |
+
candidate, subset = self.pose_estimation(input_image)
|
100 |
+
nums, keys, locs = candidate.shape
|
101 |
+
candidate[..., 0] /= float(W)
|
102 |
+
candidate[..., 1] /= float(H)
|
103 |
+
body = candidate[:,:18].copy()
|
104 |
+
body = body.reshape(nums*18, locs)
|
105 |
+
score = subset[:,:18]
|
106 |
+
|
107 |
+
for i in range(len(score)):
|
108 |
+
for j in range(len(score[i])):
|
109 |
+
if score[i][j] > 0.3:
|
110 |
+
score[i][j] = int(18*i+j)
|
111 |
+
else:
|
112 |
+
score[i][j] = -1
|
113 |
+
|
114 |
+
un_visible = subset<0.3
|
115 |
+
candidate[un_visible] = -1
|
116 |
+
|
117 |
+
foot = candidate[:,18:24]
|
118 |
+
|
119 |
+
faces = candidate[:,24:92]
|
120 |
+
|
121 |
+
hands = candidate[:,92:113]
|
122 |
+
hands = np.vstack([hands, candidate[:,113:]])
|
123 |
+
|
124 |
+
bodies = dict(candidate=body, subset=score)
|
125 |
+
pose = dict(bodies=bodies, hands=hands, faces=faces)
|
126 |
+
|
127 |
+
if self.keypoints_only==True:
|
128 |
+
return pose
|
129 |
+
else:
|
130 |
+
detected_map = draw_pose(pose, H, W, draw_face=False)
|
131 |
+
detected_map = HWC3(detected_map)
|
132 |
+
img = resize_image(input_image, image_resolution)
|
133 |
+
H, W, C = img.shape
|
134 |
+
detected_map = cv2.resize(detected_map, (W, H), interpolation=cv2.INTER_LINEAR)
|
135 |
+
# cv2.imshow('detected_map',detected_map)
|
136 |
+
# cv2.waitKey(0)
|
137 |
+
|
138 |
+
if output_type == "pil":
|
139 |
+
detected_map = cv2.cvtColor(detected_map, cv2.COLOR_BGR2RGB)
|
140 |
+
detected_map = Image.fromarray(detected_map)
|
141 |
+
|
142 |
+
return detected_map, pose
|
143 |
+
|
pose/script/tool.py
ADDED
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib
|
2 |
+
import os
|
3 |
+
import os.path as osp
|
4 |
+
import shutil
|
5 |
+
import sys
|
6 |
+
from pathlib import Path
|
7 |
+
|
8 |
+
import av
|
9 |
+
import numpy as np
|
10 |
+
import torch
|
11 |
+
import torchvision
|
12 |
+
from einops import rearrange
|
13 |
+
from PIL import Image
|
14 |
+
|
15 |
+
|
16 |
+
def seed_everything(seed):
|
17 |
+
import random
|
18 |
+
|
19 |
+
import numpy as np
|
20 |
+
|
21 |
+
torch.manual_seed(seed)
|
22 |
+
torch.cuda.manual_seed_all(seed)
|
23 |
+
np.random.seed(seed % (2**32))
|
24 |
+
random.seed(seed)
|
25 |
+
|
26 |
+
|
27 |
+
def import_filename(filename):
|
28 |
+
spec = importlib.util.spec_from_file_location("mymodule", filename)
|
29 |
+
module = importlib.util.module_from_spec(spec)
|
30 |
+
sys.modules[spec.name] = module
|
31 |
+
spec.loader.exec_module(module)
|
32 |
+
return module
|
33 |
+
|
34 |
+
|
35 |
+
def delete_additional_ckpt(base_path, num_keep):
|
36 |
+
dirs = []
|
37 |
+
for d in os.listdir(base_path):
|
38 |
+
if d.startswith("checkpoint-"):
|
39 |
+
dirs.append(d)
|
40 |
+
num_tot = len(dirs)
|
41 |
+
if num_tot <= num_keep:
|
42 |
+
return
|
43 |
+
# ensure ckpt is sorted and delete the ealier!
|
44 |
+
del_dirs = sorted(dirs, key=lambda x: int(x.split("-")[-1]))[: num_tot - num_keep]
|
45 |
+
for d in del_dirs:
|
46 |
+
path_to_dir = osp.join(base_path, d)
|
47 |
+
if osp.exists(path_to_dir):
|
48 |
+
shutil.rmtree(path_to_dir)
|
49 |
+
|
50 |
+
|
51 |
+
def save_videos_from_pil(pil_images, path, fps):
|
52 |
+
|
53 |
+
save_fmt = Path(path).suffix
|
54 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
55 |
+
width, height = pil_images[0].size
|
56 |
+
|
57 |
+
if save_fmt == ".mp4":
|
58 |
+
codec = "libx264"
|
59 |
+
container = av.open(path, "w")
|
60 |
+
stream = container.add_stream(codec, rate=fps)
|
61 |
+
|
62 |
+
stream.width = width
|
63 |
+
stream.height = height
|
64 |
+
stream.pix_fmt = 'yuv420p'
|
65 |
+
stream.bit_rate = 10000000
|
66 |
+
stream.options["crf"] = "18"
|
67 |
+
|
68 |
+
for pil_image in pil_images:
|
69 |
+
# pil_image = Image.fromarray(image_arr).convert("RGB")
|
70 |
+
av_frame = av.VideoFrame.from_image(pil_image)
|
71 |
+
container.mux(stream.encode(av_frame))
|
72 |
+
container.mux(stream.encode())
|
73 |
+
container.close()
|
74 |
+
|
75 |
+
elif save_fmt == ".gif":
|
76 |
+
pil_images[0].save(
|
77 |
+
fp=path,
|
78 |
+
format="GIF",
|
79 |
+
append_images=pil_images[1:],
|
80 |
+
save_all=True,
|
81 |
+
duration=(1 / fps * 1000),
|
82 |
+
loop=0,
|
83 |
+
)
|
84 |
+
else:
|
85 |
+
raise ValueError("Unsupported file type. Use .mp4 or .gif.")
|
86 |
+
|
87 |
+
|
88 |
+
def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8):
|
89 |
+
videos = rearrange(videos, "b c t h w -> t b c h w")
|
90 |
+
height, width = videos.shape[-2:]
|
91 |
+
outputs = []
|
92 |
+
|
93 |
+
for x in videos:
|
94 |
+
x = torchvision.utils.make_grid(x, nrow=n_rows) # (c h w)
|
95 |
+
x = x.transpose(0, 1).transpose(1, 2).squeeze(-1) # (h w c)
|
96 |
+
if rescale:
|
97 |
+
x = (x + 1.0) / 2.0 # -1,1 -> 0,1
|
98 |
+
x = (x * 255).numpy().astype(np.uint8)
|
99 |
+
x = Image.fromarray(x)
|
100 |
+
|
101 |
+
outputs.append(x)
|
102 |
+
|
103 |
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
104 |
+
|
105 |
+
save_videos_from_pil(outputs, path, fps)
|
106 |
+
|
107 |
+
|
108 |
+
def read_frames(video_path):
|
109 |
+
container = av.open(video_path)
|
110 |
+
|
111 |
+
video_stream = next(s for s in container.streams if s.type == "video")
|
112 |
+
frames = []
|
113 |
+
for packet in container.demux(video_stream):
|
114 |
+
for frame in packet.decode():
|
115 |
+
image = Image.frombytes(
|
116 |
+
"RGB",
|
117 |
+
(frame.width, frame.height),
|
118 |
+
frame.to_rgb().to_ndarray(),
|
119 |
+
)
|
120 |
+
frames.append(image)
|
121 |
+
|
122 |
+
return frames
|
123 |
+
|
124 |
+
|
125 |
+
def get_fps(video_path):
|
126 |
+
container = av.open(video_path)
|
127 |
+
video_stream = next(s for s in container.streams if s.type == "video")
|
128 |
+
fps = video_stream.average_rate
|
129 |
+
container.close()
|
130 |
+
return fps
|
pose/script/util.py
ADDED
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import numpy as np
|
3 |
+
import cv2
|
4 |
+
|
5 |
+
|
6 |
+
eps = 0.01
|
7 |
+
|
8 |
+
def smart_width(d):
|
9 |
+
if d<5:
|
10 |
+
return 1
|
11 |
+
elif d<10:
|
12 |
+
return 2
|
13 |
+
elif d<20:
|
14 |
+
return 3
|
15 |
+
elif d<40:
|
16 |
+
return 4
|
17 |
+
elif d<80:
|
18 |
+
return 5
|
19 |
+
elif d<160:
|
20 |
+
return 6
|
21 |
+
elif d<320:
|
22 |
+
return 7
|
23 |
+
else:
|
24 |
+
return 8
|
25 |
+
|
26 |
+
|
27 |
+
|
28 |
+
def draw_bodypose(canvas, candidate, subset):
|
29 |
+
H, W, C = canvas.shape
|
30 |
+
candidate = np.array(candidate)
|
31 |
+
subset = np.array(subset)
|
32 |
+
|
33 |
+
limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
|
34 |
+
[10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
|
35 |
+
[1, 16], [16, 18], [3, 17], [6, 18]]
|
36 |
+
|
37 |
+
colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
|
38 |
+
[0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
|
39 |
+
[170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
|
40 |
+
|
41 |
+
for i in range(17):
|
42 |
+
for n in range(len(subset)):
|
43 |
+
index = subset[n][np.array(limbSeq[i]) - 1]
|
44 |
+
if -1 in index:
|
45 |
+
continue
|
46 |
+
Y = candidate[index.astype(int), 0] * float(W)
|
47 |
+
X = candidate[index.astype(int), 1] * float(H)
|
48 |
+
mX = np.mean(X)
|
49 |
+
mY = np.mean(Y)
|
50 |
+
length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
|
51 |
+
angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
|
52 |
+
|
53 |
+
width = smart_width(length)
|
54 |
+
polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), width), int(angle), 0, 360, 1)
|
55 |
+
cv2.fillConvexPoly(canvas, polygon, colors[i])
|
56 |
+
|
57 |
+
canvas = (canvas * 0.6).astype(np.uint8)
|
58 |
+
|
59 |
+
for i in range(18):
|
60 |
+
for n in range(len(subset)):
|
61 |
+
index = int(subset[n][i])
|
62 |
+
if index == -1:
|
63 |
+
continue
|
64 |
+
x, y = candidate[index][0:2]
|
65 |
+
x = int(x * W)
|
66 |
+
y = int(y * H)
|
67 |
+
radius = 4
|
68 |
+
cv2.circle(canvas, (int(x), int(y)), radius, colors[i], thickness=-1)
|
69 |
+
|
70 |
+
return canvas
|
71 |
+
|
72 |
+
|
73 |
+
def draw_handpose(canvas, all_hand_peaks):
|
74 |
+
import matplotlib
|
75 |
+
|
76 |
+
H, W, C = canvas.shape
|
77 |
+
|
78 |
+
edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
|
79 |
+
[10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
|
80 |
+
|
81 |
+
# (person_number*2, 21, 2)
|
82 |
+
for i in range(len(all_hand_peaks)):
|
83 |
+
peaks = all_hand_peaks[i]
|
84 |
+
peaks = np.array(peaks)
|
85 |
+
|
86 |
+
for ie, e in enumerate(edges):
|
87 |
+
|
88 |
+
x1, y1 = peaks[e[0]]
|
89 |
+
x2, y2 = peaks[e[1]]
|
90 |
+
|
91 |
+
x1 = int(x1 * W)
|
92 |
+
y1 = int(y1 * H)
|
93 |
+
x2 = int(x2 * W)
|
94 |
+
y2 = int(y2 * H)
|
95 |
+
if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
|
96 |
+
length = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
|
97 |
+
width = smart_width(length)
|
98 |
+
cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255, thickness=width)
|
99 |
+
|
100 |
+
for _, keyponit in enumerate(peaks):
|
101 |
+
x, y = keyponit
|
102 |
+
|
103 |
+
x = int(x * W)
|
104 |
+
y = int(y * H)
|
105 |
+
if x > eps and y > eps:
|
106 |
+
radius = 3
|
107 |
+
cv2.circle(canvas, (x, y), radius, (0, 0, 255), thickness=-1)
|
108 |
+
return canvas
|
109 |
+
|
110 |
+
|
111 |
+
def draw_facepose(canvas, all_lmks):
|
112 |
+
H, W, C = canvas.shape
|
113 |
+
for lmks in all_lmks:
|
114 |
+
lmks = np.array(lmks)
|
115 |
+
for lmk in lmks:
|
116 |
+
x, y = lmk
|
117 |
+
x = int(x * W)
|
118 |
+
y = int(y * H)
|
119 |
+
if x > eps and y > eps:
|
120 |
+
radius = 3
|
121 |
+
cv2.circle(canvas, (x, y), radius, (255, 255, 255), thickness=-1)
|
122 |
+
return canvas
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
# Calculate the resolution
|
128 |
+
def size_calculate(h, w, resolution):
|
129 |
+
|
130 |
+
H = float(h)
|
131 |
+
W = float(w)
|
132 |
+
|
133 |
+
# resize the short edge to the resolution
|
134 |
+
k = float(resolution) / min(H, W) # short edge
|
135 |
+
H *= k
|
136 |
+
W *= k
|
137 |
+
|
138 |
+
# resize to the nearest integer multiple of 64
|
139 |
+
H = int(np.round(H / 64.0)) * 64
|
140 |
+
W = int(np.round(W / 64.0)) * 64
|
141 |
+
return H, W
|
142 |
+
|
143 |
+
|
144 |
+
|
145 |
+
def warpAffine_kps(kps, M):
|
146 |
+
a = M[:,:2]
|
147 |
+
t = M[:,2]
|
148 |
+
kps = np.dot(kps, a.T) + t
|
149 |
+
return kps
|
150 |
+
|
151 |
+
|
152 |
+
|
153 |
+
|
pose/script/wholebody.py
ADDED
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright (c) OpenMMLab. All rights reserved.
|
2 |
+
import os
|
3 |
+
import numpy as np
|
4 |
+
import warnings
|
5 |
+
|
6 |
+
try:
|
7 |
+
import mmcv
|
8 |
+
except ImportError:
|
9 |
+
warnings.warn(
|
10 |
+
"The module 'mmcv' is not installed. The package will have limited functionality. Please install it using the command: mim install 'mmcv>=2.0.1'"
|
11 |
+
)
|
12 |
+
|
13 |
+
try:
|
14 |
+
from mmpose.apis import inference_topdown
|
15 |
+
from mmpose.apis import init_model as init_pose_estimator
|
16 |
+
from mmpose.evaluation.functional import nms
|
17 |
+
from mmpose.utils import adapt_mmdet_pipeline
|
18 |
+
from mmpose.structures import merge_data_samples
|
19 |
+
except ImportError:
|
20 |
+
warnings.warn(
|
21 |
+
"The module 'mmpose' is not installed. The package will have limited functionality. Please install it using the command: mim install 'mmpose>=1.1.0'"
|
22 |
+
)
|
23 |
+
|
24 |
+
try:
|
25 |
+
from mmdet.apis import inference_detector, init_detector
|
26 |
+
except ImportError:
|
27 |
+
warnings.warn(
|
28 |
+
"The module 'mmdet' is not installed. The package will have limited functionality. Please install it using the command: mim install 'mmdet>=3.1.0'"
|
29 |
+
)
|
30 |
+
|
31 |
+
|
32 |
+
class Wholebody:
|
33 |
+
def __init__(self,
|
34 |
+
det_config=None, det_ckpt=None,
|
35 |
+
pose_config=None, pose_ckpt=None,
|
36 |
+
device="cpu"):
|
37 |
+
|
38 |
+
if det_config is None:
|
39 |
+
det_config = os.path.join(os.path.dirname(__file__), "yolox_config/yolox_l_8xb8-300e_coco.py")
|
40 |
+
|
41 |
+
if pose_config is None:
|
42 |
+
pose_config = os.path.join(os.path.dirname(__file__), "dwpose_config/dwpose-l_384x288.py")
|
43 |
+
|
44 |
+
if det_ckpt is None:
|
45 |
+
det_ckpt = 'https://download.openmmlab.com/mmdetection/v2.0/yolox/yolox_l_8x8_300e_coco/yolox_l_8x8_300e_coco_20211126_140236-d3bd2b23.pth'
|
46 |
+
|
47 |
+
if pose_ckpt is None:
|
48 |
+
pose_ckpt = "https://huggingface.co/wanghaofan/dw-ll_ucoco_384/resolve/main/dw-ll_ucoco_384.pth"
|
49 |
+
|
50 |
+
# build detector
|
51 |
+
self.detector = init_detector(det_config, det_ckpt, device=device)
|
52 |
+
self.detector.cfg = adapt_mmdet_pipeline(self.detector.cfg)
|
53 |
+
|
54 |
+
# build pose estimator
|
55 |
+
self.pose_estimator = init_pose_estimator(
|
56 |
+
pose_config,
|
57 |
+
pose_ckpt,
|
58 |
+
device=device)
|
59 |
+
|
60 |
+
def to(self, device):
|
61 |
+
self.detector.to(device)
|
62 |
+
self.pose_estimator.to(device)
|
63 |
+
return self
|
64 |
+
|
65 |
+
def __call__(self, oriImg):
|
66 |
+
# predict bbox
|
67 |
+
det_result = inference_detector(self.detector, oriImg)
|
68 |
+
pred_instance = det_result.pred_instances.cpu().numpy()
|
69 |
+
bboxes = np.concatenate(
|
70 |
+
(pred_instance.bboxes, pred_instance.scores[:, None]), axis=1)
|
71 |
+
bboxes = bboxes[np.logical_and(pred_instance.labels == 0,
|
72 |
+
pred_instance.scores > 0.5)]
|
73 |
+
|
74 |
+
# set NMS threshold
|
75 |
+
bboxes = bboxes[nms(bboxes, 0.7), :4]
|
76 |
+
|
77 |
+
# predict keypoints
|
78 |
+
if len(bboxes) == 0:
|
79 |
+
pose_results = inference_topdown(self.pose_estimator, oriImg)
|
80 |
+
else:
|
81 |
+
pose_results = inference_topdown(self.pose_estimator, oriImg, bboxes)
|
82 |
+
preds = merge_data_samples(pose_results)
|
83 |
+
preds = preds.pred_instances
|
84 |
+
|
85 |
+
# preds = pose_results[0].pred_instances
|
86 |
+
keypoints = preds.get('transformed_keypoints',
|
87 |
+
preds.keypoints)
|
88 |
+
if 'keypoint_scores' in preds:
|
89 |
+
scores = preds.keypoint_scores
|
90 |
+
else:
|
91 |
+
scores = np.ones(keypoints.shape[:-1])
|
92 |
+
|
93 |
+
if 'keypoints_visible' in preds:
|
94 |
+
visible = preds.keypoints_visible
|
95 |
+
else:
|
96 |
+
visible = np.ones(keypoints.shape[:-1])
|
97 |
+
keypoints_info = np.concatenate(
|
98 |
+
(keypoints, scores[..., None], visible[..., None]),
|
99 |
+
axis=-1)
|
100 |
+
# compute neck joint
|
101 |
+
neck = np.mean(keypoints_info[:, [5, 6]], axis=1)
|
102 |
+
# neck score when visualizing pred
|
103 |
+
neck[:, 2:4] = np.logical_and(
|
104 |
+
keypoints_info[:, 5, 2:4] > 0.3,
|
105 |
+
keypoints_info[:, 6, 2:4] > 0.3).astype(int)
|
106 |
+
new_keypoints_info = np.insert(
|
107 |
+
keypoints_info, 17, neck, axis=1)
|
108 |
+
mmpose_idx = [
|
109 |
+
17, 6, 8, 10, 7, 9, 12, 14, 16, 13, 15, 2, 1, 4, 3
|
110 |
+
]
|
111 |
+
openpose_idx = [
|
112 |
+
1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17
|
113 |
+
]
|
114 |
+
new_keypoints_info[:, openpose_idx] = \
|
115 |
+
new_keypoints_info[:, mmpose_idx]
|
116 |
+
keypoints_info = new_keypoints_info
|
117 |
+
|
118 |
+
keypoints, scores, visible = keypoints_info[
|
119 |
+
..., :2], keypoints_info[..., 2], keypoints_info[..., 3]
|
120 |
+
|
121 |
+
return keypoints, scores
|
pose_align.py
ADDED
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import argparse
|
3 |
+
import torch
|
4 |
+
import copy
|
5 |
+
import cv2
|
6 |
+
import os
|
7 |
+
import moviepy.video.io.ImageSequenceClip
|
8 |
+
from datetime import datetime
|
9 |
+
import gc
|
10 |
+
from huggingface_hub import hf_hub_download
|
11 |
+
|
12 |
+
from pose.script.dwpose import DWposeDetector, draw_pose
|
13 |
+
from pose.script.util import size_calculate, warpAffine_kps
|
14 |
+
|
15 |
+
|
16 |
+
'''
|
17 |
+
Detect dwpose from img, then align it by scale parameters
|
18 |
+
img: frame from the pose video
|
19 |
+
detector: DWpose
|
20 |
+
scales: scale parameters
|
21 |
+
'''
|
22 |
+
class PoseAlignmentInference:
|
23 |
+
def __init__(self):
|
24 |
+
self.detector = None
|
25 |
+
self.model_paths = {
|
26 |
+
"det_ckpt": os.path.join("pretrained_weights", "dwpose", "yolox_l_8x8_300e_coco.pth"),
|
27 |
+
"pose_ckpt": os.path.join("pretrained_weights", "dwpose", "dw-ll_ucoco_384.pth")
|
28 |
+
}
|
29 |
+
self.config_paths = {
|
30 |
+
"pose_config": os.path.join("pose", "config", "dwpose-l_384x288.py"),
|
31 |
+
"det_config": os.path.join("pose", "config", "yolox_l_8xb8-300e_coco.py"),
|
32 |
+
}
|
33 |
+
self.output_dir = os.path.join("assets", "video")
|
34 |
+
#self.download_models()
|
35 |
+
|
36 |
+
def align_pose(
|
37 |
+
self,
|
38 |
+
vidfn: str,
|
39 |
+
imgfn_refer: str,
|
40 |
+
detect_resolution: int,
|
41 |
+
image_resolution: int,
|
42 |
+
align_frame: int,
|
43 |
+
max_frame: int,
|
44 |
+
):
|
45 |
+
dt_file_name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
|
46 |
+
outfn=os.path.abspath(os.path.join(self.output_dir, f'{dt_file_name}_demo.mp4'))
|
47 |
+
outfn_align_pose_video=os.path.abspath(os.path.join(self.output_dir, f'{dt_file_name}.mp4'))
|
48 |
+
|
49 |
+
video = cv2.VideoCapture(vidfn)
|
50 |
+
width= video.get(cv2.CAP_PROP_FRAME_WIDTH)
|
51 |
+
height= video.get(cv2.CAP_PROP_FRAME_HEIGHT)
|
52 |
+
|
53 |
+
total_frame= video.get(cv2.CAP_PROP_FRAME_COUNT)
|
54 |
+
fps= video.get(cv2.CAP_PROP_FPS)
|
55 |
+
|
56 |
+
print("height:", height)
|
57 |
+
print("width:", width)
|
58 |
+
print("fps:", fps)
|
59 |
+
|
60 |
+
H_in, W_in = height, width
|
61 |
+
H_out, W_out = size_calculate(H_in,W_in, detect_resolution)
|
62 |
+
H_out, W_out = size_calculate(H_out,W_out, image_resolution)
|
63 |
+
|
64 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
65 |
+
self.detector = DWposeDetector(
|
66 |
+
det_config = self.config_paths["det_config"],
|
67 |
+
det_ckpt = self.model_paths["det_ckpt"],
|
68 |
+
pose_config = self.config_paths["pose_config"],
|
69 |
+
pose_ckpt = self.model_paths["pose_ckpt"],
|
70 |
+
keypoints_only=False
|
71 |
+
)
|
72 |
+
detector = self.detector.to(device)
|
73 |
+
|
74 |
+
refer_img = cv2.imread(imgfn_refer)
|
75 |
+
output_refer, pose_refer = detector(refer_img,detect_resolution=detect_resolution, image_resolution=image_resolution, output_type='cv2',return_pose_dict=True)
|
76 |
+
body_ref_img = pose_refer['bodies']['candidate']
|
77 |
+
hands_ref_img = pose_refer['hands']
|
78 |
+
faces_ref_img = pose_refer['faces']
|
79 |
+
output_refer = cv2.cvtColor(output_refer, cv2.COLOR_RGB2BGR)
|
80 |
+
|
81 |
+
|
82 |
+
skip_frames = align_frame
|
83 |
+
max_frame = max_frame
|
84 |
+
pose_list, video_frame_buffer, video_pose_buffer = [], [], []
|
85 |
+
|
86 |
+
|
87 |
+
cap = cv2.VideoCapture('2.mp4') # 读取视频
|
88 |
+
while cap.isOpened(): # 当视频被打开时:
|
89 |
+
ret, frame = cap.read() # 读取视频,读取到的某一帧存储到frame,若是读取成功,ret为True,反之为False
|
90 |
+
if ret: # 若是读取成功
|
91 |
+
cv2.imshow('frame', frame) # 显示读取到的这一帧画面
|
92 |
+
key = cv2.waitKey(25) # 等待一段时间,并且检测键盘输入
|
93 |
+
if key == ord('q'): # 若是键盘输入'q',则退出,释放视频
|
94 |
+
cap.release() # 释放视频
|
95 |
+
break
|
96 |
+
else:
|
97 |
+
cap.release()
|
98 |
+
cv2.destroyAllWindows() # 关闭所有窗口
|
99 |
+
|
100 |
+
|
101 |
+
for i in range(max_frame):
|
102 |
+
ret, img = video.read()
|
103 |
+
if img is None:
|
104 |
+
break
|
105 |
+
else:
|
106 |
+
if i < skip_frames:
|
107 |
+
continue
|
108 |
+
video_frame_buffer.append(img)
|
109 |
+
|
110 |
+
# estimate scale parameters by the 1st frame in the video
|
111 |
+
if i==skip_frames:
|
112 |
+
output_1st_img, pose_1st_img = detector(img, detect_resolution, image_resolution, output_type='cv2', return_pose_dict=True)
|
113 |
+
body_1st_img = pose_1st_img['bodies']['candidate']
|
114 |
+
hands_1st_img = pose_1st_img['hands']
|
115 |
+
faces_1st_img = pose_1st_img['faces']
|
116 |
+
|
117 |
+
'''
|
118 |
+
计算逻辑:
|
119 |
+
1. 先把 ref 和 pose 的高 resize 到一样,且都保持原来的长宽比。
|
120 |
+
2. 用点在图中的实际坐标来计算。
|
121 |
+
3. 实际计算中,把h的坐标归一化到 [0, 1], w为[0, W/H]
|
122 |
+
4. 由于 dwpose 的输出本来就是归一化的坐标,所以h不需要变,w要乘W/H
|
123 |
+
注意:dwpose 输���是 (w, h)
|
124 |
+
'''
|
125 |
+
|
126 |
+
# h不变,w缩放到原比例
|
127 |
+
ref_H, ref_W = refer_img.shape[0], refer_img.shape[1]
|
128 |
+
ref_ratio = ref_W / ref_H
|
129 |
+
body_ref_img[:, 0] = body_ref_img[:, 0] * ref_ratio
|
130 |
+
hands_ref_img[:, :, 0] = hands_ref_img[:, :, 0] * ref_ratio
|
131 |
+
faces_ref_img[:, :, 0] = faces_ref_img[:, :, 0] * ref_ratio
|
132 |
+
|
133 |
+
video_ratio = width / height
|
134 |
+
body_1st_img[:, 0] = body_1st_img[:, 0] * video_ratio
|
135 |
+
hands_1st_img[:, :, 0] = hands_1st_img[:, :, 0] * video_ratio
|
136 |
+
faces_1st_img[:, :, 0] = faces_1st_img[:, :, 0] * video_ratio
|
137 |
+
|
138 |
+
# scale
|
139 |
+
align_args = dict()
|
140 |
+
|
141 |
+
dist_1st_img = np.linalg.norm(body_1st_img[0]-body_1st_img[1]) # 0.078
|
142 |
+
dist_ref_img = np.linalg.norm(body_ref_img[0]-body_ref_img[1]) # 0.106
|
143 |
+
align_args["scale_neck"] = dist_ref_img / dist_1st_img # align / pose = ref / 1st
|
144 |
+
|
145 |
+
dist_1st_img = np.linalg.norm(body_1st_img[16]-body_1st_img[17])
|
146 |
+
dist_ref_img = np.linalg.norm(body_ref_img[16]-body_ref_img[17])
|
147 |
+
align_args["scale_face"] = dist_ref_img / dist_1st_img
|
148 |
+
|
149 |
+
dist_1st_img = np.linalg.norm(body_1st_img[2]-body_1st_img[5]) # 0.112
|
150 |
+
dist_ref_img = np.linalg.norm(body_ref_img[2]-body_ref_img[5]) # 0.174
|
151 |
+
align_args["scale_shoulder"] = dist_ref_img / dist_1st_img
|
152 |
+
|
153 |
+
dist_1st_img = np.linalg.norm(body_1st_img[2]-body_1st_img[3]) # 0.895
|
154 |
+
dist_ref_img = np.linalg.norm(body_ref_img[2]-body_ref_img[3]) # 0.134
|
155 |
+
s1 = dist_ref_img / dist_1st_img
|
156 |
+
dist_1st_img = np.linalg.norm(body_1st_img[5]-body_1st_img[6])
|
157 |
+
dist_ref_img = np.linalg.norm(body_ref_img[5]-body_ref_img[6])
|
158 |
+
s2 = dist_ref_img / dist_1st_img
|
159 |
+
align_args["scale_arm_upper"] = (s1+s2)/2 # 1.548
|
160 |
+
|
161 |
+
dist_1st_img = np.linalg.norm(body_1st_img[3]-body_1st_img[4])
|
162 |
+
dist_ref_img = np.linalg.norm(body_ref_img[3]-body_ref_img[4])
|
163 |
+
s1 = dist_ref_img / dist_1st_img
|
164 |
+
dist_1st_img = np.linalg.norm(body_1st_img[6]-body_1st_img[7])
|
165 |
+
dist_ref_img = np.linalg.norm(body_ref_img[6]-body_ref_img[7])
|
166 |
+
s2 = dist_ref_img / dist_1st_img
|
167 |
+
align_args["scale_arm_lower"] = (s1+s2)/2
|
168 |
+
|
169 |
+
# hand
|
170 |
+
dist_1st_img = np.zeros(10)
|
171 |
+
dist_ref_img = np.zeros(10)
|
172 |
+
|
173 |
+
dist_1st_img[0] = np.linalg.norm(hands_1st_img[0,0]-hands_1st_img[0,1])
|
174 |
+
dist_1st_img[1] = np.linalg.norm(hands_1st_img[0,0]-hands_1st_img[0,5])
|
175 |
+
dist_1st_img[2] = np.linalg.norm(hands_1st_img[0,0]-hands_1st_img[0,9])
|
176 |
+
dist_1st_img[3] = np.linalg.norm(hands_1st_img[0,0]-hands_1st_img[0,13])
|
177 |
+
dist_1st_img[4] = np.linalg.norm(hands_1st_img[0,0]-hands_1st_img[0,17])
|
178 |
+
dist_1st_img[5] = np.linalg.norm(hands_1st_img[1,0]-hands_1st_img[1,1])
|
179 |
+
dist_1st_img[6] = np.linalg.norm(hands_1st_img[1,0]-hands_1st_img[1,5])
|
180 |
+
dist_1st_img[7] = np.linalg.norm(hands_1st_img[1,0]-hands_1st_img[1,9])
|
181 |
+
dist_1st_img[8] = np.linalg.norm(hands_1st_img[1,0]-hands_1st_img[1,13])
|
182 |
+
dist_1st_img[9] = np.linalg.norm(hands_1st_img[1,0]-hands_1st_img[1,17])
|
183 |
+
|
184 |
+
dist_ref_img[0] = np.linalg.norm(hands_ref_img[0,0]-hands_ref_img[0,1])
|
185 |
+
dist_ref_img[1] = np.linalg.norm(hands_ref_img[0,0]-hands_ref_img[0,5])
|
186 |
+
dist_ref_img[2] = np.linalg.norm(hands_ref_img[0,0]-hands_ref_img[0,9])
|
187 |
+
dist_ref_img[3] = np.linalg.norm(hands_ref_img[0,0]-hands_ref_img[0,13])
|
188 |
+
dist_ref_img[4] = np.linalg.norm(hands_ref_img[0,0]-hands_ref_img[0,17])
|
189 |
+
dist_ref_img[5] = np.linalg.norm(hands_ref_img[1,0]-hands_ref_img[1,1])
|
190 |
+
dist_ref_img[6] = np.linalg.norm(hands_ref_img[1,0]-hands_ref_img[1,5])
|
191 |
+
dist_ref_img[7] = np.linalg.norm(hands_ref_img[1,0]-hands_ref_img[1,9])
|
192 |
+
dist_ref_img[8] = np.linalg.norm(hands_ref_img[1,0]-hands_ref_img[1,13])
|
193 |
+
dist_ref_img[9] = np.linalg.norm(hands_ref_img[1,0]-hands_ref_img[1,17])
|
194 |
+
|
195 |
+
ratio = 0
|
196 |
+
count = 0
|
197 |
+
for i in range (10):
|
198 |
+
if dist_1st_img[i] != 0:
|
199 |
+
ratio = ratio + dist_ref_img[i]/dist_1st_img[i]
|
200 |
+
count = count + 1
|
201 |
+
if count!=0:
|
202 |
+
align_args["scale_hand"] = (ratio/count+align_args["scale_arm_upper"]+align_args["scale_arm_lower"])/3
|
203 |
+
else:
|
204 |
+
align_args["scale_hand"] = (align_args["scale_arm_upper"]+align_args["scale_arm_lower"])/2
|
205 |
+
|
206 |
+
# body
|
207 |
+
dist_1st_img = np.linalg.norm(body_1st_img[1] - (body_1st_img[8] + body_1st_img[11])/2 )
|
208 |
+
dist_ref_img = np.linalg.norm(body_ref_img[1] - (body_ref_img[8] + body_ref_img[11])/2 )
|
209 |
+
align_args["scale_body_len"]=dist_ref_img / dist_1st_img
|
210 |
+
|
211 |
+
dist_1st_img = np.linalg.norm(body_1st_img[8]-body_1st_img[9])
|
212 |
+
dist_ref_img = np.linalg.norm(body_ref_img[8]-body_ref_img[9])
|
213 |
+
s1 = dist_ref_img / dist_1st_img
|
214 |
+
dist_1st_img = np.linalg.norm(body_1st_img[11]-body_1st_img[12])
|
215 |
+
dist_ref_img = np.linalg.norm(body_ref_img[11]-body_ref_img[12])
|
216 |
+
s2 = dist_ref_img / dist_1st_img
|
217 |
+
align_args["scale_leg_upper"] = (s1+s2)/2
|
218 |
+
|
219 |
+
dist_1st_img = np.linalg.norm(body_1st_img[9]-body_1st_img[10])
|
220 |
+
dist_ref_img = np.linalg.norm(body_ref_img[9]-body_ref_img[10])
|
221 |
+
s1 = dist_ref_img / dist_1st_img
|
222 |
+
dist_1st_img = np.linalg.norm(body_1st_img[12]-body_1st_img[13])
|
223 |
+
dist_ref_img = np.linalg.norm(body_ref_img[12]-body_ref_img[13])
|
224 |
+
s2 = dist_ref_img / dist_1st_img
|
225 |
+
align_args["scale_leg_lower"] = (s1+s2)/2
|
226 |
+
|
227 |
+
####################
|
228 |
+
####################
|
229 |
+
# need adjust nan
|
230 |
+
for k,v in align_args.items():
|
231 |
+
if np.isnan(v):
|
232 |
+
align_args[k]=1
|
233 |
+
|
234 |
+
# centre offset (the offset of key point 1)
|
235 |
+
offset = body_ref_img[1] - body_1st_img[1]
|
236 |
+
|
237 |
+
|
238 |
+
# pose align
|
239 |
+
pose_img, pose_ori = detector(img, detect_resolution, image_resolution, output_type='cv2', return_pose_dict=True)
|
240 |
+
video_pose_buffer.append(pose_img)
|
241 |
+
pose_align = self.align_img(img, pose_ori, align_args, detect_resolution, image_resolution)
|
242 |
+
|
243 |
+
|
244 |
+
# add centre offset
|
245 |
+
pose = pose_align
|
246 |
+
pose['bodies']['candidate'] = pose['bodies']['candidate'] + offset
|
247 |
+
pose['hands'] = pose['hands'] + offset
|
248 |
+
pose['faces'] = pose['faces'] + offset
|
249 |
+
|
250 |
+
|
251 |
+
# h不变,w从绝对坐标缩放回0-1 注意这里要回到ref的坐标系
|
252 |
+
pose['bodies']['candidate'][:, 0] = pose['bodies']['candidate'][:, 0] / ref_ratio
|
253 |
+
pose['hands'][:, :, 0] = pose['hands'][:, :, 0] / ref_ratio
|
254 |
+
pose['faces'][:, :, 0] = pose['faces'][:, :, 0] / ref_ratio
|
255 |
+
pose_list.append(pose)
|
256 |
+
|
257 |
+
# stack
|
258 |
+
body_list = [pose['bodies']['candidate'][:18] for pose in pose_list]
|
259 |
+
body_list_subset = [pose['bodies']['subset'][:1] for pose in pose_list]
|
260 |
+
hands_list = [pose['hands'][:2] for pose in pose_list]
|
261 |
+
faces_list = [pose['faces'][:1] for pose in pose_list]
|
262 |
+
|
263 |
+
body_seq = np.stack(body_list , axis=0)
|
264 |
+
body_seq_subset = np.stack(body_list_subset, axis=0)
|
265 |
+
hands_seq = np.stack(hands_list , axis=0)
|
266 |
+
faces_seq = np.stack(faces_list , axis=0)
|
267 |
+
|
268 |
+
|
269 |
+
# concatenate and paint results
|
270 |
+
H = 768 # paint height
|
271 |
+
W1 = int((H/ref_H * ref_W)//2 *2)
|
272 |
+
W2 = int((H/height * width)//2 *2)
|
273 |
+
result_demo = [] # = Writer(args, None, H, 3*W1+2*W2, outfn, fps)
|
274 |
+
result_pose_only = [] # Writer(args, None, H, W1, args.outfn_align_pose_video, fps)
|
275 |
+
for i in range(len(body_seq)):
|
276 |
+
pose_t={}
|
277 |
+
pose_t["bodies"]={}
|
278 |
+
pose_t["bodies"]["candidate"]=body_seq[i]
|
279 |
+
pose_t["bodies"]["subset"]=body_seq_subset[i]
|
280 |
+
pose_t["hands"]=hands_seq[i]
|
281 |
+
pose_t["faces"]=faces_seq[i]
|
282 |
+
|
283 |
+
ref_img = cv2.cvtColor(refer_img, cv2.COLOR_RGB2BGR)
|
284 |
+
ref_img = cv2.resize(ref_img, (W1, H))
|
285 |
+
ref_pose= cv2.resize(output_refer, (W1, H))
|
286 |
+
|
287 |
+
output_transformed = draw_pose(
|
288 |
+
pose_t,
|
289 |
+
int(H_in*1024/W_in),
|
290 |
+
1024,
|
291 |
+
draw_face=False,
|
292 |
+
)
|
293 |
+
output_transformed = cv2.cvtColor(output_transformed, cv2.COLOR_BGR2RGB)
|
294 |
+
output_transformed = cv2.resize(output_transformed, (W1, H))
|
295 |
+
|
296 |
+
video_frame = cv2.resize(video_frame_buffer[i], (W2, H))
|
297 |
+
video_pose = cv2.resize(video_pose_buffer[i], (W2, H))
|
298 |
+
|
299 |
+
res = np.concatenate([ref_img, ref_pose, output_transformed, video_frame, video_pose], axis=1)
|
300 |
+
result_demo.append(res)
|
301 |
+
result_pose_only.append(output_transformed)
|
302 |
+
|
303 |
+
print(f"pose_list len: {len(pose_list)}")
|
304 |
+
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(result_demo, fps=fps)
|
305 |
+
clip.write_videofile(outfn, fps=fps)
|
306 |
+
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(result_pose_only, fps=fps)
|
307 |
+
clip.write_videofile(outfn_align_pose_video, fps=fps)
|
308 |
+
print('pose align done')
|
309 |
+
self.release_vram()
|
310 |
+
return outfn_align_pose_video, outfn
|
311 |
+
|
312 |
+
def download_models(self):
|
313 |
+
repo_id = 'jhj0517/MusePose'
|
314 |
+
for name, file_path in self.model_paths.items():
|
315 |
+
local_dir, filename = os.path.dirname(file_path), os.path.basename(file_path)
|
316 |
+
if not os.path.exists(local_dir):
|
317 |
+
os.makedirs(local_dir)
|
318 |
+
|
319 |
+
remote_filepath = os.path.join("dwpose", filename)
|
320 |
+
if not os.path.exists(file_path):
|
321 |
+
hf_hub_download(repo_id=repo_id, filename=remote_filepath,
|
322 |
+
local_dir=local_dir,
|
323 |
+
local_dir_use_symlinks=False)
|
324 |
+
|
325 |
+
def release_vram(self):
|
326 |
+
if self.detector is not None:
|
327 |
+
del self.detector
|
328 |
+
self.detector = None
|
329 |
+
if torch.cuda.is_available():
|
330 |
+
torch.cuda.empty_cache()
|
331 |
+
gc.collect()
|
332 |
+
|
333 |
+
@staticmethod
|
334 |
+
def align_img(img, pose_ori, scales, detect_resolution, image_resolution):
|
335 |
+
|
336 |
+
body_pose = copy.deepcopy(pose_ori['bodies']['candidate'])
|
337 |
+
hands = copy.deepcopy(pose_ori['hands'])
|
338 |
+
faces = copy.deepcopy(pose_ori['faces'])
|
339 |
+
|
340 |
+
'''
|
341 |
+
计算逻辑:
|
342 |
+
0. 该函数内进行绝对变换,始终保持人体中心点 body_pose[1] 不变
|
343 |
+
1. 先把 ref 和 pose 的高 resize 到一样,且都保持原来的长宽比。
|
344 |
+
2. 用点在图中的实际坐标来计算。
|
345 |
+
3. 实际计算中,把h的坐标归一化到 [0, 1], w为[0, W/H]
|
346 |
+
4. 由于 dwpose 的输出本来就是归一化的坐标,所以h不需要变,w要乘W/H
|
347 |
+
注意:dwpose 输出是 (w, h)
|
348 |
+
'''
|
349 |
+
|
350 |
+
# h不变,w缩放到原比例
|
351 |
+
H_in, W_in, C_in = img.shape
|
352 |
+
video_ratio = W_in / H_in
|
353 |
+
body_pose[:, 0] = body_pose[:, 0] * video_ratio
|
354 |
+
hands[:, :, 0] = hands[:, :, 0] * video_ratio
|
355 |
+
faces[:, :, 0] = faces[:, :, 0] * video_ratio
|
356 |
+
|
357 |
+
# scales of 10 body parts
|
358 |
+
scale_neck = scales["scale_neck"]
|
359 |
+
scale_face = scales["scale_face"]
|
360 |
+
scale_shoulder = scales["scale_shoulder"]
|
361 |
+
scale_arm_upper = scales["scale_arm_upper"]
|
362 |
+
scale_arm_lower = scales["scale_arm_lower"]
|
363 |
+
scale_hand = scales["scale_hand"]
|
364 |
+
scale_body_len = scales["scale_body_len"]
|
365 |
+
scale_leg_upper = scales["scale_leg_upper"]
|
366 |
+
scale_leg_lower = scales["scale_leg_lower"]
|
367 |
+
|
368 |
+
scale_sum = 0
|
369 |
+
count = 0
|
370 |
+
scale_list = [scale_neck, scale_face, scale_shoulder, scale_arm_upper, scale_arm_lower, scale_hand,
|
371 |
+
scale_body_len, scale_leg_upper, scale_leg_lower]
|
372 |
+
for i in range(len(scale_list)):
|
373 |
+
if not np.isinf(scale_list[i]):
|
374 |
+
scale_sum = scale_sum + scale_list[i]
|
375 |
+
count = count + 1
|
376 |
+
for i in range(len(scale_list)):
|
377 |
+
if np.isinf(scale_list[i]):
|
378 |
+
scale_list[i] = scale_sum / count
|
379 |
+
|
380 |
+
# offsets of each part
|
381 |
+
offset = dict()
|
382 |
+
offset["14_15_16_17_to_0"] = body_pose[[14, 15, 16, 17], :] - body_pose[[0], :]
|
383 |
+
offset["3_to_2"] = body_pose[[3], :] - body_pose[[2], :]
|
384 |
+
offset["4_to_3"] = body_pose[[4], :] - body_pose[[3], :]
|
385 |
+
offset["6_to_5"] = body_pose[[6], :] - body_pose[[5], :]
|
386 |
+
offset["7_to_6"] = body_pose[[7], :] - body_pose[[6], :]
|
387 |
+
offset["9_to_8"] = body_pose[[9], :] - body_pose[[8], :]
|
388 |
+
offset["10_to_9"] = body_pose[[10], :] - body_pose[[9], :]
|
389 |
+
offset["12_to_11"] = body_pose[[12], :] - body_pose[[11], :]
|
390 |
+
offset["13_to_12"] = body_pose[[13], :] - body_pose[[12], :]
|
391 |
+
offset["hand_left_to_4"] = hands[1, :, :] - body_pose[[4], :]
|
392 |
+
offset["hand_right_to_7"] = hands[0, :, :] - body_pose[[7], :]
|
393 |
+
|
394 |
+
# neck
|
395 |
+
c_ = body_pose[1]
|
396 |
+
cx = c_[0]
|
397 |
+
cy = c_[1]
|
398 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_neck)
|
399 |
+
|
400 |
+
neck = body_pose[[0], :]
|
401 |
+
neck = warpAffine_kps(neck, M)
|
402 |
+
body_pose[[0], :] = neck
|
403 |
+
|
404 |
+
# body_pose_up_shoulder
|
405 |
+
c_ = body_pose[0]
|
406 |
+
cx = c_[0]
|
407 |
+
cy = c_[1]
|
408 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_face)
|
409 |
+
|
410 |
+
body_pose_up_shoulder = offset["14_15_16_17_to_0"] + body_pose[[0], :]
|
411 |
+
body_pose_up_shoulder = warpAffine_kps(body_pose_up_shoulder, M)
|
412 |
+
body_pose[[14, 15, 16, 17], :] = body_pose_up_shoulder
|
413 |
+
|
414 |
+
# shoulder
|
415 |
+
c_ = body_pose[1]
|
416 |
+
cx = c_[0]
|
417 |
+
cy = c_[1]
|
418 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_shoulder)
|
419 |
+
|
420 |
+
body_pose_shoulder = body_pose[[2, 5], :]
|
421 |
+
body_pose_shoulder = warpAffine_kps(body_pose_shoulder, M)
|
422 |
+
body_pose[[2, 5], :] = body_pose_shoulder
|
423 |
+
|
424 |
+
# arm upper left
|
425 |
+
c_ = body_pose[2]
|
426 |
+
cx = c_[0]
|
427 |
+
cy = c_[1]
|
428 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_arm_upper)
|
429 |
+
|
430 |
+
elbow = offset["3_to_2"] + body_pose[[2], :]
|
431 |
+
elbow = warpAffine_kps(elbow, M)
|
432 |
+
body_pose[[3], :] = elbow
|
433 |
+
|
434 |
+
# arm lower left
|
435 |
+
c_ = body_pose[3]
|
436 |
+
cx = c_[0]
|
437 |
+
cy = c_[1]
|
438 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_arm_lower)
|
439 |
+
|
440 |
+
wrist = offset["4_to_3"] + body_pose[[3], :]
|
441 |
+
wrist = warpAffine_kps(wrist, M)
|
442 |
+
body_pose[[4], :] = wrist
|
443 |
+
|
444 |
+
# hand left
|
445 |
+
c_ = body_pose[4]
|
446 |
+
cx = c_[0]
|
447 |
+
cy = c_[1]
|
448 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_hand)
|
449 |
+
|
450 |
+
hand = offset["hand_left_to_4"] + body_pose[[4], :]
|
451 |
+
hand = warpAffine_kps(hand, M)
|
452 |
+
hands[1, :, :] = hand
|
453 |
+
|
454 |
+
# arm upper right
|
455 |
+
c_ = body_pose[5]
|
456 |
+
cx = c_[0]
|
457 |
+
cy = c_[1]
|
458 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_arm_upper)
|
459 |
+
|
460 |
+
elbow = offset["6_to_5"] + body_pose[[5], :]
|
461 |
+
elbow = warpAffine_kps(elbow, M)
|
462 |
+
body_pose[[6], :] = elbow
|
463 |
+
|
464 |
+
# arm lower right
|
465 |
+
c_ = body_pose[6]
|
466 |
+
cx = c_[0]
|
467 |
+
cy = c_[1]
|
468 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_arm_lower)
|
469 |
+
|
470 |
+
wrist = offset["7_to_6"] + body_pose[[6], :]
|
471 |
+
wrist = warpAffine_kps(wrist, M)
|
472 |
+
body_pose[[7], :] = wrist
|
473 |
+
|
474 |
+
# hand right
|
475 |
+
c_ = body_pose[7]
|
476 |
+
cx = c_[0]
|
477 |
+
cy = c_[1]
|
478 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_hand)
|
479 |
+
|
480 |
+
hand = offset["hand_right_to_7"] + body_pose[[7], :]
|
481 |
+
hand = warpAffine_kps(hand, M)
|
482 |
+
hands[0, :, :] = hand
|
483 |
+
|
484 |
+
# body len
|
485 |
+
c_ = body_pose[1]
|
486 |
+
cx = c_[0]
|
487 |
+
cy = c_[1]
|
488 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_body_len)
|
489 |
+
|
490 |
+
body_len = body_pose[[8, 11], :]
|
491 |
+
body_len = warpAffine_kps(body_len, M)
|
492 |
+
body_pose[[8, 11], :] = body_len
|
493 |
+
|
494 |
+
# leg upper left
|
495 |
+
c_ = body_pose[8]
|
496 |
+
cx = c_[0]
|
497 |
+
cy = c_[1]
|
498 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_leg_upper)
|
499 |
+
|
500 |
+
knee = offset["9_to_8"] + body_pose[[8], :]
|
501 |
+
knee = warpAffine_kps(knee, M)
|
502 |
+
body_pose[[9], :] = knee
|
503 |
+
|
504 |
+
# leg lower left
|
505 |
+
c_ = body_pose[9]
|
506 |
+
cx = c_[0]
|
507 |
+
cy = c_[1]
|
508 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_leg_lower)
|
509 |
+
|
510 |
+
ankle = offset["10_to_9"] + body_pose[[9], :]
|
511 |
+
ankle = warpAffine_kps(ankle, M)
|
512 |
+
body_pose[[10], :] = ankle
|
513 |
+
|
514 |
+
# leg upper right
|
515 |
+
c_ = body_pose[11]
|
516 |
+
cx = c_[0]
|
517 |
+
cy = c_[1]
|
518 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_leg_upper)
|
519 |
+
|
520 |
+
knee = offset["12_to_11"] + body_pose[[11], :]
|
521 |
+
knee = warpAffine_kps(knee, M)
|
522 |
+
body_pose[[12], :] = knee
|
523 |
+
|
524 |
+
# leg lower right
|
525 |
+
c_ = body_pose[12]
|
526 |
+
cx = c_[0]
|
527 |
+
cy = c_[1]
|
528 |
+
M = cv2.getRotationMatrix2D((cx, cy), 0, scale_leg_lower)
|
529 |
+
|
530 |
+
ankle = offset["13_to_12"] + body_pose[[12], :]
|
531 |
+
ankle = warpAffine_kps(ankle, M)
|
532 |
+
body_pose[[13], :] = ankle
|
533 |
+
|
534 |
+
# none part
|
535 |
+
body_pose_none = pose_ori['bodies']['candidate'] == -1.
|
536 |
+
hands_none = pose_ori['hands'] == -1.
|
537 |
+
faces_none = pose_ori['faces'] == -1.
|
538 |
+
|
539 |
+
body_pose[body_pose_none] = -1.
|
540 |
+
hands[hands_none] = -1.
|
541 |
+
nan = float('nan')
|
542 |
+
if len(hands[np.isnan(hands)]) > 0:
|
543 |
+
print('nan')
|
544 |
+
faces[faces_none] = -1.
|
545 |
+
|
546 |
+
# last check nan -> -1.
|
547 |
+
body_pose = np.nan_to_num(body_pose, nan=-1.)
|
548 |
+
hands = np.nan_to_num(hands, nan=-1.)
|
549 |
+
faces = np.nan_to_num(faces, nan=-1.)
|
550 |
+
|
551 |
+
# return
|
552 |
+
pose_align = copy.deepcopy(pose_ori)
|
553 |
+
pose_align['bodies']['candidate'] = body_pose
|
554 |
+
pose_align['hands'] = hands
|
555 |
+
pose_align['faces'] = faces
|
556 |
+
|
557 |
+
return pose_align
|
requirements.txt
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
--index-url https://download.pytorch.org/whl/cu121
|
2 |
+
torch==2.1.2
|
3 |
+
torchvision==0.16.2
|
4 |
+
torchdiffeq==0.2.3
|
5 |
+
torchmetrics==1.2.1
|
6 |
+
torchsde==0.2.5
|
7 |
+
accelerate==0.29.3
|
8 |
+
av==11.0.0
|
9 |
+
clip @ https://github.com/openai/CLIP/archive/d50d76daa670286dd6cacf3bcd80b5e4823fc8e1.zip#sha256=b5842c25da441d6c581b53a5c60e0c2127ebafe0f746f8e15561a006c6c3be6a
|
10 |
+
decord==0.6.0
|
11 |
+
diffusers>=0.24.0,<=0.27.2
|
12 |
+
einops==0.4.1
|
13 |
+
imageio==2.33.0
|
14 |
+
imageio-ffmpeg==0.4.9
|
15 |
+
ffmpeg-python==0.2.0
|
16 |
+
omegaconf==2.2.3
|
17 |
+
open-clip-torch==2.20.0
|
18 |
+
opencv-contrib-python==4.8.1.78
|
19 |
+
opencv-python==4.8.1.78
|
20 |
+
scikit-image==0.21.0
|
21 |
+
scikit-learn==1.3.2
|
22 |
+
transformers==4.33.1
|
23 |
+
xformers==0.0.22
|
24 |
+
moviepy==1.0.3
|
25 |
+
wget==3.2
|
test_stage.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
from omegaconf import OmegaConf
|
3 |
+
import torch
|
4 |
+
from pprint import pprint
|
5 |
+
|
6 |
+
from musepose_inference import MusePoseInference
|
7 |
+
|
8 |
+
|
9 |
+
def parse_args():
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument("--config", type=str, default="./configs/test_stage.yaml")
|
12 |
+
parser.add_argument("-W", type=int, default=768, help="Width")
|
13 |
+
parser.add_argument("-H", type=int, default=768, help="Height")
|
14 |
+
parser.add_argument("-L", type=int, default=300, help="video frame length")
|
15 |
+
parser.add_argument("-S", type=int, default=48, help="video slice frame number")
|
16 |
+
parser.add_argument("-O", type=int, default=4, help="video slice overlap frame number")
|
17 |
+
|
18 |
+
parser.add_argument("--cfg", type=float, default=3.5, help="Classifier free guidance")
|
19 |
+
parser.add_argument("--seed", type=int, default=99)
|
20 |
+
parser.add_argument("--steps", type=int, default=20, help="DDIM sampling steps")
|
21 |
+
parser.add_argument("--fps", type=int)
|
22 |
+
parser.add_argument("--weight_dtype", type=str, default="fp16")
|
23 |
+
parser.add_argument("--output_dir", type=str, default="./output")
|
24 |
+
|
25 |
+
parser.add_argument("--skip", type=int, default=1, help="frame sample rate = (skip+1)")
|
26 |
+
args = parser.parse_args()
|
27 |
+
|
28 |
+
return args
|
29 |
+
|
30 |
+
|
31 |
+
def main():
|
32 |
+
args = parse_args()
|
33 |
+
config = OmegaConf.load(args.config)
|
34 |
+
|
35 |
+
musepose_infer = MusePoseInference(config=config, output_dir=args.output_dir)
|
36 |
+
|
37 |
+
ref_image_path = list(config["test_cases"].keys())[0]
|
38 |
+
pose_video_path = config["test_cases"][ref_image_path][0]
|
39 |
+
|
40 |
+
output_file_path = musepose_infer.infer_musepose(
|
41 |
+
ref_image_path=ref_image_path,
|
42 |
+
pose_video_path=pose_video_path,
|
43 |
+
weight_dtype=args.weight_dtype,
|
44 |
+
W=args.W,
|
45 |
+
H=args.H,
|
46 |
+
L=args.L,
|
47 |
+
S=args.S,
|
48 |
+
O=args.O,
|
49 |
+
cfg=args.cfg,
|
50 |
+
seed=args.seed,
|
51 |
+
steps=args.steps,
|
52 |
+
fps=args.fps,
|
53 |
+
skip=args.skip
|
54 |
+
)
|
55 |
+
|
56 |
+
print(f"{output_file_path} is saved")
|
57 |
+
|
58 |
+
|
59 |
+
if __name__ == "__main__":
|
60 |
+
main()
|