Stacy123 commited on
Commit
f53df8b
·
1 Parent(s): 3d463f3

Upload body.py

Browse files
Files changed (1) hide show
  1. pytorch-openpose/body.py +218 -0
pytorch-openpose/body.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import math
4
+ import time
5
+ from scipy.ndimage.filters import gaussian_filter
6
+ import matplotlib.pyplot as plt
7
+ import matplotlib
8
+ import torch
9
+ from torchvision import transforms
10
+
11
+ from src import util
12
+ from src.model import bodypose_model
13
+
14
+ class Body(object):
15
+ def __init__(self, model_path):
16
+ self.model = bodypose_model()
17
+ if torch.cuda.is_available():
18
+ self.model = self.model.cuda()
19
+ model_dict = util.transfer(self.model, torch.load(model_path))
20
+ self.model.load_state_dict(model_dict)
21
+ self.model.eval()
22
+
23
+ def __call__(self, oriImg):
24
+ # scale_search = [0.5, 1.0, 1.5, 2.0]
25
+ scale_search = [0.5]
26
+ boxsize = 368
27
+ stride = 8
28
+ padValue = 128
29
+ thre1 = 0.1
30
+ thre2 = 0.05
31
+ multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search]
32
+ heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 19))
33
+ paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))
34
+
35
+ for m in range(len(multiplier)):
36
+ scale = multiplier[m]
37
+ imageToTest = cv2.resize(oriImg, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
38
+ imageToTest_padded, pad = util.padRightDownCorner(imageToTest, stride, padValue)
39
+ im = np.transpose(np.float32(imageToTest_padded[:, :, :, np.newaxis]), (3, 2, 0, 1)) / 256 - 0.5
40
+ im = np.ascontiguousarray(im)
41
+
42
+ data = torch.from_numpy(im).float()
43
+ if torch.cuda.is_available():
44
+ data = data.cuda()
45
+ # data = data.permute([2, 0, 1]).unsqueeze(0).float()
46
+ with torch.no_grad():
47
+ Mconv7_stage6_L1, Mconv7_stage6_L2 = self.model(data)
48
+ Mconv7_stage6_L1 = Mconv7_stage6_L1.cpu().numpy()
49
+ Mconv7_stage6_L2 = Mconv7_stage6_L2.cpu().numpy()
50
+
51
+ # extract outputs, resize, and remove padding
52
+ # heatmap = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[1]].data), (1, 2, 0)) # output 1 is heatmaps
53
+ heatmap = np.transpose(np.squeeze(Mconv7_stage6_L2), (1, 2, 0)) # output 1 is heatmaps
54
+ heatmap = cv2.resize(heatmap, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
55
+ heatmap = heatmap[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
56
+ heatmap = cv2.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv2.INTER_CUBIC)
57
+
58
+ # paf = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[0]].data), (1, 2, 0)) # output 0 is PAFs
59
+ paf = np.transpose(np.squeeze(Mconv7_stage6_L1), (1, 2, 0)) # output 0 is PAFs
60
+ paf = cv2.resize(paf, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
61
+ paf = paf[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
62
+ paf = cv2.resize(paf, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv2.INTER_CUBIC)
63
+
64
+ heatmap_avg += heatmap_avg + heatmap / len(multiplier)
65
+ paf_avg += + paf / len(multiplier)
66
+
67
+ all_peaks = []
68
+ peak_counter = 0
69
+
70
+ for part in range(18):
71
+ map_ori = heatmap_avg[:, :, part]
72
+ one_heatmap = gaussian_filter(map_ori, sigma=3)
73
+
74
+ map_left = np.zeros(one_heatmap.shape)
75
+ map_left[1:, :] = one_heatmap[:-1, :]
76
+ map_right = np.zeros(one_heatmap.shape)
77
+ map_right[:-1, :] = one_heatmap[1:, :]
78
+ map_up = np.zeros(one_heatmap.shape)
79
+ map_up[:, 1:] = one_heatmap[:, :-1]
80
+ map_down = np.zeros(one_heatmap.shape)
81
+ map_down[:, :-1] = one_heatmap[:, 1:]
82
+
83
+ peaks_binary = np.logical_and.reduce(
84
+ (one_heatmap >= map_left, one_heatmap >= map_right, one_heatmap >= map_up, one_heatmap >= map_down, one_heatmap > thre1))
85
+ peaks = list(zip(np.nonzero(peaks_binary)[1], np.nonzero(peaks_binary)[0])) # note reverse
86
+ peaks_with_score = [x + (map_ori[x[1], x[0]],) for x in peaks]
87
+ peak_id = range(peak_counter, peak_counter + len(peaks))
88
+ peaks_with_score_and_id = [peaks_with_score[i] + (peak_id[i],) for i in range(len(peak_id))]
89
+
90
+ all_peaks.append(peaks_with_score_and_id)
91
+ peak_counter += len(peaks)
92
+
93
+ # find connection in the specified sequence, center 29 is in the position 15
94
+ limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
95
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
96
+ [1, 16], [16, 18], [3, 17], [6, 18]]
97
+ # the middle joints heatmap correpondence
98
+ mapIdx = [[31, 32], [39, 40], [33, 34], [35, 36], [41, 42], [43, 44], [19, 20], [21, 22], \
99
+ [23, 24], [25, 26], [27, 28], [29, 30], [47, 48], [49, 50], [53, 54], [51, 52], \
100
+ [55, 56], [37, 38], [45, 46]]
101
+
102
+ connection_all = []
103
+ special_k = []
104
+ mid_num = 10
105
+
106
+ for k in range(len(mapIdx)):
107
+ score_mid = paf_avg[:, :, [x - 19 for x in mapIdx[k]]]
108
+ candA = all_peaks[limbSeq[k][0] - 1]
109
+ candB = all_peaks[limbSeq[k][1] - 1]
110
+ nA = len(candA)
111
+ nB = len(candB)
112
+ indexA, indexB = limbSeq[k]
113
+ if (nA != 0 and nB != 0):
114
+ connection_candidate = []
115
+ for i in range(nA):
116
+ for j in range(nB):
117
+ vec = np.subtract(candB[j][:2], candA[i][:2])
118
+ norm = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
119
+ norm = max(0.001, norm)
120
+ vec = np.divide(vec, norm)
121
+
122
+ startend = list(zip(np.linspace(candA[i][0], candB[j][0], num=mid_num), \
123
+ np.linspace(candA[i][1], candB[j][1], num=mid_num)))
124
+
125
+ vec_x = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 0] \
126
+ for I in range(len(startend))])
127
+ vec_y = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 1] \
128
+ for I in range(len(startend))])
129
+
130
+ score_midpts = np.multiply(vec_x, vec[0]) + np.multiply(vec_y, vec[1])
131
+ score_with_dist_prior = sum(score_midpts) / len(score_midpts) + min(
132
+ 0.5 * oriImg.shape[0] / norm - 1, 0)
133
+ criterion1 = len(np.nonzero(score_midpts > thre2)[0]) > 0.8 * len(score_midpts)
134
+ criterion2 = score_with_dist_prior > 0
135
+ if criterion1 and criterion2:
136
+ connection_candidate.append(
137
+ [i, j, score_with_dist_prior, score_with_dist_prior + candA[i][2] + candB[j][2]])
138
+
139
+ connection_candidate = sorted(connection_candidate, key=lambda x: x[2], reverse=True)
140
+ connection = np.zeros((0, 5))
141
+ for c in range(len(connection_candidate)):
142
+ i, j, s = connection_candidate[c][0:3]
143
+ if (i not in connection[:, 3] and j not in connection[:, 4]):
144
+ connection = np.vstack([connection, [candA[i][3], candB[j][3], s, i, j]])
145
+ if (len(connection) >= min(nA, nB)):
146
+ break
147
+
148
+ connection_all.append(connection)
149
+ else:
150
+ special_k.append(k)
151
+ connection_all.append([])
152
+
153
+ # last number in each row is the total parts number of that person
154
+ # the second last number in each row is the score of the overall configuration
155
+ subset = -1 * np.ones((0, 20))
156
+ candidate = np.array([item for sublist in all_peaks for item in sublist])
157
+
158
+ for k in range(len(mapIdx)):
159
+ if k not in special_k:
160
+ partAs = connection_all[k][:, 0]
161
+ partBs = connection_all[k][:, 1]
162
+ indexA, indexB = np.array(limbSeq[k]) - 1
163
+
164
+ for i in range(len(connection_all[k])): # = 1:size(temp,1)
165
+ found = 0
166
+ subset_idx = [-1, -1]
167
+ for j in range(len(subset)): # 1:size(subset,1):
168
+ if subset[j][indexA] == partAs[i] or subset[j][indexB] == partBs[i]:
169
+ subset_idx[found] = j
170
+ found += 1
171
+
172
+ if found == 1:
173
+ j = subset_idx[0]
174
+ if subset[j][indexB] != partBs[i]:
175
+ subset[j][indexB] = partBs[i]
176
+ subset[j][-1] += 1
177
+ subset[j][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
178
+ elif found == 2: # if found 2 and disjoint, merge them
179
+ j1, j2 = subset_idx
180
+ membership = ((subset[j1] >= 0).astype(int) + (subset[j2] >= 0).astype(int))[:-2]
181
+ if len(np.nonzero(membership == 2)[0]) == 0: # merge
182
+ subset[j1][:-2] += (subset[j2][:-2] + 1)
183
+ subset[j1][-2:] += subset[j2][-2:]
184
+ subset[j1][-2] += connection_all[k][i][2]
185
+ subset = np.delete(subset, j2, 0)
186
+ else: # as like found == 1
187
+ subset[j1][indexB] = partBs[i]
188
+ subset[j1][-1] += 1
189
+ subset[j1][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
190
+
191
+ # if find no partA in the subset, create a new subset
192
+ elif not found and k < 17:
193
+ row = -1 * np.ones(20)
194
+ row[indexA] = partAs[i]
195
+ row[indexB] = partBs[i]
196
+ row[-1] = 2
197
+ row[-2] = sum(candidate[connection_all[k][i, :2].astype(int), 2]) + connection_all[k][i][2]
198
+ subset = np.vstack([subset, row])
199
+ # delete some rows of subset which has few parts occur
200
+ deleteIdx = []
201
+ for i in range(len(subset)):
202
+ if subset[i][-1] < 4 or subset[i][-2] / subset[i][-1] < 0.4:
203
+ deleteIdx.append(i)
204
+ subset = np.delete(subset, deleteIdx, axis=0)
205
+
206
+ # subset: n*20 array, 0-17 is the index in candidate, 18 is the total score, 19 is the total parts
207
+ # candidate: x, y, score, id
208
+ return candidate, subset
209
+
210
+ if __name__ == "__main__":
211
+ body_estimation = Body('../model/body_pose_model.pth')
212
+
213
+ test_image = '../images/ski.jpg'
214
+ oriImg = cv2.imread(test_image) # B,G,R order
215
+ candidate, subset = body_estimation(oriImg)
216
+ canvas = util.draw_bodypose(oriImg, candidate, subset)
217
+ plt.imshow(canvas[:, :, [2, 1, 0]])
218
+ plt.show()