-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdemo_cpm_hand2.py
325 lines (260 loc) · 12.6 KB
/
demo_cpm_hand2.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#Imported Functions
import tensorflow as tf
import numpy as np
import cv2
import time
import math
import os
import serial
from models.nets import cpm_hand_slim
from utils import cpm_utils
#Define port for transmitting data serially to Arduino.
port = '/dev/ttyACM0'
s = serial.Serial(port,115200)
#ignoring tf warnings
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
#Defining Input File Arguments
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_integer('input_size',
default=368,
help='Input image size')
tf.app.flags.DEFINE_integer('hmap_size',
default=46,
help='Output heatmap size')
tf.app.flags.DEFINE_integer('stages',
default=6,
help='How many CPM stages')
# Set color for each finger
joint_color_code = [[139, 53, 255],
[0, 56, 255],
[43, 140, 237],
[37, 168, 36],
[147, 147, 0],
[70, 17, 145]]
# Each Element of the list defines a joint to joint connection.
limbs = [[0, 1],
[1, 2],
[2, 3],
[3, 4],
[0, 5],
[5, 6],
[6, 7],
[7, 8],
[0, 9],
[9, 10],
[10, 11],
[11, 12],
[0, 13],
[13, 14],
[14, 15],
[15, 16],
[0, 17],
[17, 18],
[18, 19],
[19, 20]
]
#Define a nx6 2-d array to store n data timesteps: angles of (index, middle, ring, little, palm, thumb).
m_avg=np.zeros((15,6))
#Refernce values to be set each time in the beginning of the execution.
ratios=np.zeros((6))
avg_i=0
def main(argv):
global ratios, avg_i, m_avg, s
tf_device = '/gpu:0'
with tf.device(tf_device):
#Build graph
input_data = tf.placeholder(dtype=tf.float32, shape=[None, FLAGS.input_size, FLAGS.input_size, 3],name='input_image')
center_map = tf.placeholder(dtype=tf.float32, shape=[None, FLAGS.input_size, FLAGS.input_size, 1],name='center_map')
model = cpm_hand_slim.CPM_Model(FLAGS.stages, 21 + 1)
model.build_model(input_data, center_map, 1)
saver = tf.train.Saver()
#Create session and restore weights
sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=False))
sess.run(tf.global_variables_initializer())
model.load_weights_from_file(models/weights/cpm_hand.pkl, sess, False)
#get gaussian image
test_center_map = cpm_utils.gaussian_img(FLAGS.input_size, FLAGS.input_size, FLAGS.input_size / 2,
FLAGS.input_size / 2,
21)
test_center_map = np.reshape(test_center_map, [1, FLAGS.input_size, FLAGS.input_size, 1])
#Starting Video Input
cam = cv2.VideoCapture(0)
# Create kalman filters
kalman_filter_array = [cv2.KalmanFilter(4, 2) for _ in range(21)]
for _, joint_kalman_filter in enumerate(kalman_filter_array):
joint_kalman_filter.transitionMatrix = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1]],
np.float32)
joint_kalman_filter.measurementMatrix = np.array([[1, 0, 0, 0], [0, 1, 0, 0]], np.float32)
joint_kalman_filter.processNoiseCov = np.array([[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]],
np.float32) * 3e-2
with tf.device(tf_device):
t0=time.time()
while True:
print(time.time()-t0)
#Read image and resize it according to architecture input size.
test_img = cpm_utils.read_image([], cam, FLAGS.input_size, 'WEBCAM')
test_img_resize = cv2.resize(test_img, (FLAGS.input_size, FLAGS.input_size))
test_img_input = test_img_resize / 256.0 - 0.5
test_img_input = np.expand_dims(test_img_input, axis=0)
# Starting time of each iteration.
t1 = time.time()
#Run the image through the model and get corresponding heatmap.
stage_heatmap_np = sess.run([model.stage_heatmap[2]],
feed_dict={'input_image:0': test_img_input,
'center_map:0': test_center_map})
#Get the coordinates of each joint and print the image with joints makrked on the figure.
demo_img,coords = visualize_result(test_img, FLAGS, stage_heatmap_np, kalman_filter_array)
cv2.imshow('current heatmap', (demo_img).astype(np.uint8))
#At the beginning of each execution, user gets 30 sec
#for setting reference angles when hand was kept straight.
if ((time.time()-t0)<30):
store_deb(coords, t0)
print('ratios: '+str(ratios))
else:
debug(coords)
print('degrees: '+str(np.mean(m_avg,axis=0)))
#Calculate moving average for past n timesteps.
mavg_deg=np.mean(m_avg,axis=0)
mavg_deg[4]= min(mavg_deg[4],20)
avg_i=(avg_i+1)%15
#Setting the string to be transmitted to Arduino.
transp_str=''
for i in mavg_deg:
transp_str=transp_str+str(i)+','
#Flushing the input and output buffer before writing to Serial.
s.flushInput()
s.flushOutput()
s.write(transp_str.encode())
if cv2.waitKey(1) == ord('q'): break
def visualize_result(test_img, FLAGS, stage_heatmap_np, kalman_filter_array):
demo_stage_heatmaps = []
last_heatmap = stage_heatmap_np[len(stage_heatmap_np) - 1][0, :, :, 0:21].reshape(
(FLAGS.hmap_size, FLAGS.hmap_size, 21))
last_heatmap = cv2.resize(last_heatmap, (test_img.shape[1], test_img.shape[0]))
joint_coord_set = np.zeros((21, 2))
# Plot joint colors
for joint_num in range(21):
joint_coord = np.unravel_index(np.argmax(last_heatmap[:, :, joint_num]),
(test_img.shape[0], test_img.shape[1]))
joint_coord = np.array(joint_coord).reshape((2, 1)).astype(np.float32)
kalman_filter_array[joint_num].correct(joint_coord)
kalman_pred = kalman_filter_array[joint_num].predict()
joint_coord_set[joint_num, :] = np.array([kalman_pred[0], kalman_pred[1]]).reshape((2))
color_code_num = (joint_num // 4)
if joint_num in [0, 4, 8, 12, 16]:
joint_color = list(map(lambda x: x + 35 * (joint_num % 4), joint_color_code[color_code_num]))
cv2.circle(test_img, center=(joint_coord[1], joint_coord[0]), radius=3, color=joint_color, thickness=-1)
else:
joint_color = list(map(lambda x: x + 35 * (joint_num % 4), joint_color_code[color_code_num]))
cv2.circle(test_img, center=(joint_coord[1], joint_coord[0]), radius=3, color=joint_color, thickness=-1)
# Plot limb colors
for limb_num in range(len(limbs)):
x1 = joint_coord_set[limbs[limb_num][0], 0]
y1 = joint_coord_set[limbs[limb_num][0], 1]
x2 = joint_coord_set[limbs[limb_num][1], 0]
y2 = joint_coord_set[limbs[limb_num][1], 1]
length = ((x1 - x2) ** 2 + (y1 - y2) ** 2) ** 0.5
if length < 150 and length > 5:
deg = math.degrees(math.atan2(x1 - x2, y1 - y2))
polygon = cv2.ellipse2Poly((int((y1 + y2) / 2), int((x1 + x2) / 2)),
(int(length / 2), 3),
int(deg),
0, 360, 1)
color_code_num = limb_num // 4
limb_color = list(map(lambda x: x + 35 * (limb_num % 4), joint_color_code[color_code_num]))
cv2.fillConvexPoly(test_img, polygon, color=limb_color)
return test_img,joint_coord_set
def debug(coords):
#This Func. calculates the required angles.
global m_avg
global ratios
degs=[]
#Get the coordinates of the required joints.
coords1 = []
for i in [1,5,8,9,12,13,16,17,20,0]:
coords1.append(coords[i])
#Get median of all joints
Xc1=(coords1[0][0]+coords1[1][0]+coords1[3][0]+coords1[5][0]+coords1[7][0])/5
Yc1=(coords1[0][1]+coords1[1][1]+coords1[3][1]+coords1[5][1]+coords1[7][1])/5
'''Get the ratios of 4 fingers to calculate finger angles.
ratio of length of finger to distance between finger-palm joint and median is calculated.
'''
for i in range(4):
length1=((coords1[2*i+1][0]-Xc1)**2+(coords1[2*i+1][1]-Yc1)**2)**0.5
length2=((coords1[2*i+2][0]-coords1[2*i+1][0])**2+(coords1[2*i+2][1]-coords1[2*i+1][1])**2)**0.5
r=length2/length1
r=r/float(ratios[i])
if(r>1):
r=1
if(r<-1):
r=-1
#using current and refernce ratios, finger angles are calculated.
degs.append(math.degrees(math.acos((r))))
###Solved Formula for calculating Palm and thumb angle.
#Approx distance between palm-thumb joint and center of palm is calculated.
ax=((coords1[0][0]-coords1[9][0])**2+(coords1[0][1]-coords1[9][1])**2)**0.5
bx=((coords1[1][0]-coords1[9][0])**2+(coords1[1][1]-coords1[9][1])**2)**0.5
cx=((coords1[0][0]-coords1[1][0])**2+(coords1[0][1]-coords1[1][1])**2)**0.5
h=(4*(ax**2)*(bx**2)-(ax**2+bx**2-cx**2)**2)/(4*(bx**2))
h=max(h,0)**0.5
h=h/float(ratios[4])
if(h>1):
h=1
if(h<-1):
h=-1
#using current and refernce ratios, palm angles are calculated.
degs.append(math.degrees(math.acos((h))))
#Approx distance between palm-little finger joint and tip of thumb is calculated.
ax=((coords[0][0]-coords[4][0])**2+(coords[0][1]-coords[4][1])**2)**0.5
bx=((coords[0][0]-coords[17][0])**2+(coords[0][1]-coords[17][1])**2)**0.5
cx=((coords[4][0]-coords[17][0])**2+(coords[4][1]-coords[17][1])**2)**0.5
h=(ax**2+bx**2-cx**2)/(2*ax*bx)
h=math.degrees(math.acos((max(h,0)**0.5)))
h=h/float(ratios[5])
if(h>1):
h=1
if(h<-1):
h=-1
#using current and refernce ratios, thumb angles are calculated.
degs.append(math.degrees(math.acos((h))))
#angles for current timestep is updated in m_avg and previous nth timestep entry is deleted.
for i in range(6):
m_avg[avg_i][i]=degs[i]
def store_deb(coords, t0):
#This func. calculates the refernce values
global ratios
#Exponential averaging is used to get correct ratios for 15 secs..
#ratio = Beta*ratio+New_Value*(1-Beta)
#First Fifteen seconds are alloted for adjusting hand in camera and next fifteen seconds to set the refernce ratios.
if((time.time()-t0)>15):
#Get the coordinates of the required joints.
coords1=[]
for i in [1,5,8,9,12,13,16,17,20,0]:
coords1.append(coords[i])
#Get median of all joints
Xc1=(coords1[0][0]+coords1[1][0]+coords1[3][0]+coords1[5][0]+coords1[7][0])/5
Yc1=(coords1[0][1]+coords1[1][1]+coords1[3][1]+coords1[5][1]+coords1[7][1])/5
'''Get the ratios of 4 fingers to calculate finger angles.
ratio of length of finger to distance between finger-palm joint and median is calculated.
'''
for i in range(4):
length1=((coords1[2*i+1][0]-Xc1)**2+(coords1[2*i+1][1]-Yc1)**2)**0.5
length2=((coords1[2*i+2][0]-coords1[2*i+1][0])**2+(coords1[2*i+2][1]-coords1[2*i+1][1])**2)**0.5
r=length2/length1
ratios[i] = 0.8*ratios[i]+r*0.2
#Approx distance between palm-thumb joint and center of palm is calculated.
ax=((coords1[0][0]-coords1[9][0])**2+(coords1[0][1]-coords1[9][1])**2)**0.5
bx=((coords1[1][0]-coords1[9][0])**2+(coords1[1][1]-coords1[9][1])**2)**0.5
cx=((coords1[0][0]-coords1[1][0])**2+(coords1[0][1]-coords1[1][1])**2)**0.5
h=(4*(ax**2)*(bx**2)-(ax**2+bx**2-cx**2)**2)/(4*(bx**2))
h=max(h,0)**0.5
ratios[4]=ratios[4]*0.8+h*0.2
#Approx distance between palm-little finger joint and tip of thumb is calculated.
ax=((coords[0][0]-coords[4][0])**2+(coords[0][1]-coords[4][1])**2)**0.5
bx=((coords[0][0]-coords[17][0])**2+(coords[0][1]-coords[17][1])**2)**0.5
cx=((coords[4][0]-coords[17][0])**2+(coords[4][1]-coords[17][1])**2)**0.5
h=(ax**2+bx**2-cx**2)/(2*ax*bx)
h=math.degrees(math.acos((max(h,0)**0.5)))
ratios[5]=ratios[5]*0.8+h*0.2
if __name__ == '__main__':
tf.app.run()