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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
| import argparse import time
import cv2 import numpy as np
""" 该文件主要用于识别人体姿态并输出最边缘坐标 主要函数为 detect_pose 不需要预览结果请注释 cv2.imshow 等相关代码即可 依赖库 opencv-python~=4.7.0.72 numpy~=1.24.2 """
protoFile = "data//pose/coco/pose_deploy_linevec.prototxt"
weightsFile = "data/pose/coco/pose_iter_440000.caffemodel"
nPoints = 18
keypointsMapping = ['Nose', 'Neck', 'R-Shoulder', 'R-Elbow', 'R-Wrist', 'L-Shoulder', 'L-Elbow', 'L-Wrist', 'R-Hip', 'R-Knee', 'R-Ankle', 'L-Hip', 'L-Knee', 'L-Ankle', 'R-Eye', 'L-Eye', 'R-Ear', 'L-Ear']
POSE_PAIRS = [[1, 2], [1, 5], [2, 3], [3, 4], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], [1, 11], [11, 12], [12, 13], [1, 0], [0, 14], [14, 16], [0, 15], [15, 17], [2, 17], [5, 16]]
mapIdx = [[31, 32], [39, 40], [33, 34], [35, 36], [41, 42], [43, 44], [19, 20], [21, 22], [23, 24], [25, 26], [27, 28], [29, 30], [47, 48], [49, 50], [53, 54], [51, 52], [55, 56], [37, 38], [45, 46]]
colors = [[0, 100, 255], [0, 100, 255], [0, 255, 255], [0, 100, 255], [0, 255, 255], [0, 100, 255], [0, 255, 0], [255, 200, 100], [255, 0, 255], [0, 255, 0], [255, 200, 100], [255, 0, 255], [0, 0, 255], [255, 0, 0], [200, 200, 0], [255, 0, 0], [200, 200, 0], [0, 0, 0]]
points = []
def detect_pose(image_path): """ 检测姿势 :param image_path: 图片路径 :return: 返回 pose, points 其中 pose 为 points 为 按照顺时针方向排列(即上右下左)的四个最顶点的坐标数组 调用函数例子如下: path = "img/test.png" pose, points = detect_pose(path) print(points) """
parser = argparse.ArgumentParser(description='运行关键点检测')
parser.add_argument("--device", default="cpu", help="推理设备") parser.add_argument("--image_file", default=image_path, help="输入图像")
args = parser.parse_args() image1 = cv2.imread(args.image_file)
def getKeypoints(probMap, threshold=0.1): """ 从输入的概率图(即 probMap)中提取关键点信息 :param probMap: 概率图 :param threshold: 二值化概率图时所采用的阈值,默认为 0.1 值较小时,可以提取出更多的关键点,但可能会包含一些噪声或冗余信息 值较大时,可以减少关键点的数量,但可能会漏掉一些有用信息 :return: 关键点列表 """ mapSmooth = cv2.GaussianBlur(probMap, (3, 3), 0, 0)
mapMask = np.uint8(mapSmooth > threshold)
contours, _ = cv2.findContours(mapMask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
keypoints = [] for cnt in contours: blobMask = np.zeros(mapMask.shape) blobMask = cv2.fillConvexPoly(blobMask, cnt, 1) maskedProbMap = mapSmooth * blobMask _, maxVal, _, maxLoc = cv2.minMaxLoc(maskedProbMap) keypoints.append(maxLoc + (probMap[maxLoc[1], maxLoc[0]],)) points.append(maxLoc) return keypoints
def getValidPairs(output): """ 在所有检测到的人中,寻找有效连接关系 :param output: 检测到的人体内容 :return: 有效连接关系列表,无效连接关系列表 """ valid_pairs = [] invalid_pairs = [] n_interp_samples = 10 paf_score_th = 0.1 conf_th = 0.7
for k in range(len(mapIdx)): pafA = output[0, mapIdx[k][0], :, :] pafB = output[0, mapIdx[k][1], :, :] pafA = cv2.resize(pafA, (frameWidth, frameHeight)) pafB = cv2.resize(pafB, (frameWidth, frameHeight))
candA = detected_keypoints[POSE_PAIRS[k][0]] candB = detected_keypoints[POSE_PAIRS[k][1]] nA = len(candA) nB = len(candB)
if (nA != 0 and nB != 0): valid_pair = np.zeros((0, 3)) for i in range(nA): max_j = -1 maxScore = -1 found = 0 for j in range(nB): d_ij = np.subtract(candB[j][:2], candA[i][:2]) norm = np.linalg.norm(d_ij) if norm: d_ij = d_ij / norm else: continue interp_coord = list(zip(np.linspace(candA[i][0], candB[j][0], num=n_interp_samples), np.linspace(candA[i][1], candB[j][1], num=n_interp_samples))) paf_interp = [] for k in range(len(interp_coord)): paf_interp.append([pafA[int(round(interp_coord[k][1])), int(round(interp_coord[k][0]))], pafB[int(round(interp_coord[k][1])), int(round(interp_coord[k][0]))]]) paf_scores = np.dot(paf_interp, d_ij) avg_paf_score = sum(paf_scores) / len(paf_scores)
if (len(np.where(paf_scores > paf_score_th)[0]) / n_interp_samples) > conf_th: if avg_paf_score > maxScore: max_j = j maxScore = avg_paf_score found = 1
if found: valid_pair = np.append(valid_pair, [[candA[i][3], candB[max_j][3], maxScore]], axis=0)
valid_pairs.append(valid_pair) else: print("没有连接 : k = {}".format(k)) invalid_pairs.append(k) valid_pairs.append([]) return valid_pairs, invalid_pairs
def getPersonwiseKeypoints(valid_pairs, invalid_pairs): """ 遍历所有有效连接关系,将其对应的关键点分配给不同的人,并计算出每个人在当前姿态下的得分。 这样可以更为合适地去描绘人体姿态,减少出现 A 的左眼连结到 B 的右眼的情况 :param valid_pairs: 有效连接关系列表 :param invalid_pairs: 无效连接关系列表 :return: 个性化关键点数组 """ personwiseKeypoints = -1 * np.ones((0, 19))
for k in range(len(mapIdx)): if k not in invalid_pairs: partAs = valid_pairs[k][:, 0] partBs = valid_pairs[k][:, 1] indexA, indexB = np.array(POSE_PAIRS[k]) for i in range(len(valid_pairs[k])): found = 0 person_idx = -1 for j in range(len(personwiseKeypoints)): if personwiseKeypoints[j][indexA] == partAs[i]: person_idx = j found = 1 break
if found: personwiseKeypoints[person_idx][indexB] = partBs[i] personwiseKeypoints[person_idx][-1] += keypoints_list[partBs[i].astype(int), 2] + \ valid_pairs[k][i][ 2] elif not found and k < 17: row = -1 * np.ones(19) row[indexA] = partAs[i] row[indexB] = partBs[i] row[-1] = sum(keypoints_list[valid_pairs[k][i, :2].astype(int), 2]) + valid_pairs[k][i][2] personwiseKeypoints = np.vstack([personwiseKeypoints, row]) return personwiseKeypoints
frameWidth = image1.shape[1] frameHeight = image1.shape[0]
t = time.time() net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile) if args.device == "cpu": net.setPreferableBackend(cv2.dnn.DNN_TARGET_CPU) print("使用 CPU") elif args.device == "gpu": net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA) print("使用 GPU")
inHeight = 368 inWidth = int((inHeight / frameHeight) * frameWidth)
inpBlob = cv2.dnn.blobFromImage(image1, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False) net.setInput(inpBlob) output = net.forward() print("前馈传递所需时间 = {}".format(time.time() - t))
detected_keypoints = [] keypoints_list = np.zeros((0, 3)) keypoint_id = 0 threshold = 0.1
for part in range(nPoints): probMap = output[0, part, :, :] probMap = cv2.resize(probMap, (image1.shape[1], image1.shape[0]))
keypoints = getKeypoints(probMap, threshold) print("Keypoints - {} : {}".format(keypointsMapping[part], keypoints)) keypoints_with_id = [] for i in range(len(keypoints)): keypoints_with_id.append(keypoints[i] + (keypoint_id,)) keypoints_list = np.vstack([keypoints_list, keypoints[i]]) keypoint_id += 1
detected_keypoints.append(keypoints_with_id)
frameClone = image1.copy() for i in range(nPoints): for j in range(len(detected_keypoints[i])): print(detected_keypoints[i][j][0:2]) cv2.putText(frameClone, "{}".format(keypointsMapping[i]), detected_keypoints[i][j][0:2], cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) cv2.putText(frameClone, "({})".format(detected_keypoints[i][j]), detected_keypoints[i][j][0:2], cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1) cv2.circle(frameClone, detected_keypoints[i][j][0:2], 5, colors[i], -1, cv2.LINE_AA)
valid_pairs, invalid_pairs = getValidPairs(output) personwiseKeypoints = getPersonwiseKeypoints(valid_pairs, invalid_pairs)
for i in range(17): for n in range(len(personwiseKeypoints)): index = personwiseKeypoints[n][np.array(POSE_PAIRS[i])] if -1 in index: continue B = np.int32(keypoints_list[index.astype(int), 0]) A = np.int32(keypoints_list[index.astype(int), 1]) cv2.line(frameClone, (B[0], A[0]), (B[1], A[1]), colors[i], 3, cv2.LINE_AA)
cv2.imshow("关键点", frameClone) cv2.imshow("姿态检测", frameClone) cv2.waitKey(0)
return personwiseKeypoints[0] if len(personwiseKeypoints) > 0 else None, get_vertex_coordinates(points)
def get_vertex_coordinates(arr): """ 获取坐标数组中的四个顶点坐标 :param arr: 包含坐标点的二维数组,行表示点的数量,列表示每个点的坐标轴数量 :return: arr 一个按照顺时针方向排列的四个顶点的坐标数组 """
arr = np.array(arr)
top_idx = np.argmin(arr[:, 1]) bottom_idx = np.argmax(arr[:, 1]) left_idx = np.argmin(arr[:, 0]) right_idx = np.argmax(arr[:, 0])
print("最上坐标为:({}, {})".format(arr[top_idx][0], arr[top_idx][1])) print("最下坐标为:({}, {})".format(arr[bottom_idx][0], arr[bottom_idx][1])) print("最左坐标为:({}, {})".format(arr[left_idx][0], arr[left_idx][1])) print("最右坐标为:({}, {})".format(arr[right_idx][0], arr[right_idx][1]))
coordinates = np.array([ [arr[top_idx][0], arr[top_idx][1]], [arr[right_idx][0], arr[right_idx][1]], [arr[bottom_idx][0], arr[bottom_idx][1]], [arr[left_idx][0], arr[left_idx][1]] ])
return coordinates
if __name__ == '__main__': path = "../data/result.png" pose, points = detect_pose(path) print('------------') print(points)
|