forked from akanazawa/hmr
-
Notifications
You must be signed in to change notification settings - Fork 52
/
demo.py
215 lines (168 loc) · 7.15 KB
/
demo.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""
Demo of HMR.
Note that HMR requires the bounding box of the person in the image. The best performance is obtained when max length of the person in the image is roughly 150px.
When only the image path is supplied, it assumes that the image is centered on a person whose length is roughly 150px.
Alternatively, you can supply output of the openpose to figure out the bbox and the right scale factor.
Sample usage:
# On images on a tightly cropped image around the person
python -m demo --img_path data/im1963.jpg
python -m demo --img_path data/coco1.png
# On images, with openpose output
python -m demo --img_path data/random.jpg --json_path data/random_keypoints.json
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from absl import flags
import numpy as np
import skimage.io as io
import tensorflow as tf
from src.util import renderer as vis_util
from src.util import image as img_util
from src.util import openpose as op_util
import src.config
from src.RunModel import RunModel
import pandas as pd
import os
import glob
flags.DEFINE_string('img_path', 'data/im1963.jpg', 'Image to run')
flags.DEFINE_string(
'json_path', None,
'If specified, uses the openpose output to crop the image.')
def visualize(img_path, img, proc_param, joints, verts, cam):
"""
Renders the result in original image coordinate frame.
"""
cam_for_render, vert_shifted, joints_orig = vis_util.get_original(
proc_param, verts, cam, joints, img_size=img.shape[:2])
# Render results
skel_img = vis_util.draw_skeleton(img, joints_orig)
rend_img_overlay = renderer(
vert_shifted, cam=cam_for_render, img=img, do_alpha=True)
rend_img = renderer(
vert_shifted, cam=cam_for_render, img_size=img.shape[:2])
rend_img_vp1 = renderer.rotated(
vert_shifted, 60, cam=cam_for_render, img_size=img.shape[:2])
rend_img_vp2 = renderer.rotated(
vert_shifted, -60, cam=cam_for_render, img_size=img.shape[:2])
import matplotlib.pyplot as plt
# plt.ion()
plt.figure(1)
plt.clf()
plt.subplot(231)
plt.imshow(img)
plt.title('input')
plt.axis('off')
plt.subplot(232)
plt.imshow(skel_img)
plt.title('joint projection')
plt.axis('off')
plt.subplot(233)
plt.imshow(rend_img_overlay)
plt.title('3D Mesh overlay')
plt.axis('off')
plt.subplot(234)
plt.imshow(rend_img)
plt.title('3D mesh')
plt.axis('off')
plt.subplot(235)
plt.imshow(rend_img_vp1)
plt.title('diff vp')
plt.axis('off')
plt.subplot(236)
plt.imshow(rend_img_vp2)
plt.title('diff vp')
plt.axis('off')
plt.draw()
plt.savefig("hmr/output/images/"+os.path.splitext(os.path.basename(img_path))[0]+".png")
# import ipdb
# ipdb.set_trace()
def preprocess_image(img_path, json_path=None):
img = io.imread(img_path)
if img.shape[2] == 4:
img = img[:, :, :3]
if json_path is None:
if np.max(img.shape[:2]) != config.img_size:
print('Resizing so the max image size is %d..' % config.img_size)
scale = (float(config.img_size) / np.max(img.shape[:2]))
else:
scale = 1.
center = np.round(np.array(img.shape[:2]) / 2).astype(int)
# image center in (x,y)
center = center[::-1]
else:
scale, center = op_util.get_bbox(json_path)
crop, proc_param = img_util.scale_and_crop(img, scale, center,
config.img_size)
# Normalize image to [-1, 1]
crop = 2 * ((crop / 255.) - 0.5)
return crop, proc_param, img
def main(img_path, json_path=None):
sess = tf.Session()
model = RunModel(config, sess=sess)
input_img, proc_param, img = preprocess_image(img_path, json_path)
# Add batch dimension: 1 x D x D x 3
input_img = np.expand_dims(input_img, 0)
joints, verts, cams, joints3d, theta = model.predict(
input_img, get_theta=True)
# print('JOINTS 3D:')
# print(joints3d.shape)
# print(joints3d)
joints_names = ['Ankle.R_x', 'Ankle.R_y', 'Ankle.R_z',
'Knee.R_x', 'Knee.R_y', 'Knee.R_z',
'Hip.R_x', 'Hip.R_y', 'Hip.R_z',
'Hip.L_x', 'Hip.L_y', 'Hip.L_z',
'Knee.L_x', 'Knee.L_y', 'Knee.L_z',
'Ankle.L_x', 'Ankle.L_y', 'Ankle.L_z',
'Wrist.R_x', 'Wrist.R_y', 'Wrist.R_z',
'Elbow.R_x', 'Elbow.R_y', 'Elbow.R_z',
'Shoulder.R_x', 'Shoulder.R_y', 'Shoulder.R_z',
'Shoulder.L_x', 'Shoulder.L_y', 'Shoulder.L_z',
'Elbow.L_x', 'Elbow.L_y', 'Elbow.L_z',
'Wrist.L_x', 'Wrist.L_y', 'Wrist.L_z',
'Neck_x', 'Neck_y', 'Neck_z',
'Head_x', 'Head_y', 'Head_z',
'Nose_x', 'Nose_y', 'Nose_z',
'Eye.L_x', 'Eye.L_y', 'Eye.L_z',
'Eye.R_x', 'Eye.R_y', 'Eye.R_z',
'Ear.L_x', 'Ear.L_y', 'Ear.L_z',
'Ear.R_x', 'Ear.R_y', 'Ear.R_z']
joints_export = pd.DataFrame(joints3d.reshape(1,57), columns=joints_names)
joints_export.index.name = 'frame'
joints_export.iloc[:, 1::3] = joints_export.iloc[:, 1::3]*-1
joints_export.iloc[:, 2::3] = joints_export.iloc[:, 2::3]*-1
# col_list = list(joints_export)
# col_list[1::3], col_list[2::3] = col_list[2::3], col_list[1::3]
# joints_export = joints_export[col_list]
hipCenter = joints_export.loc[:][['Hip.R_x', 'Hip.R_y', 'Hip.R_z',
'Hip.L_x', 'Hip.L_y', 'Hip.L_z']]
joints_export['hip.Center_x'] = hipCenter.iloc[0][::3].sum()/2
joints_export['hip.Center_y'] = hipCenter.iloc[0][1::3].sum()/2
joints_export['hip.Center_z'] = hipCenter.iloc[0][2::3].sum()/2
joints_export.to_csv("hmr/output/csv/"+os.path.splitext(os.path.basename(img_path))[0]+".csv")
# pose = pd.DataFrame(theta[:, 3:75])
# pose.to_csv("hmr/output/theta_test.csv", header=None, index=None)
# print('THETA:', pose.shape, pose)
# import cv2
# rotations = [cv2.Rodrigues(aa)[0] for aa in pose.reshape(-1, 3)]
# print('ROTATIONS:', rotations)
visualize(img_path, img, proc_param, joints[0], verts[0], cams[0])
def join_csv():
path = 'hmr/output/csv/'
all_files = glob.glob(os.path.join(path, "*.csv"))
all_files.sort(key=lambda x: int(x.split('/')[-1].split('.')[0]))
df_from_each_file = (pd.read_csv(f) for f in all_files)
concatenated_df = pd.concat(df_from_each_file, ignore_index=True)
concatenated_df['frame'] = concatenated_df.index+1
concatenated_df.to_csv("hmr/output/csv_joined/csv_joined.csv", index=False)
if __name__ == '__main__':
config = flags.FLAGS
config(sys.argv)
# Using pre-trained model, change this to use your own.
config.load_path = src.config.PRETRAINED_MODEL
config.batch_size = 1
renderer = vis_util.SMPLRenderer(face_path=config.smpl_face_path)
main(config.img_path, config.json_path)
join_csv()
print('\nResult is in hmr/output (you can open images in Colaboratory by double-clicking them)')