人体姿态识别代码python
时间: 2023-06-20 12:04:24 浏览: 83
以下是一个基于OpenCV和深度学习的人体姿态识别代码示例:
```
import cv2
import numpy as np
import time
protoFile = "pose_deploy_linevec.prototxt"
weightsFile = "pose_iter_440000.caffemodel"
nPoints = 18
POSE_PAIRS = [[1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7], [1, 8], [8, 9], [9, 10], [10, 11], [8, 12], [12, 13], [13, 14], [1, 15], [15, 17], [1, 16], [16, 18], [2, 17], [5, 18]]
net = cv2.dnn.readNetFromCaffe(protoFile, weightsFile)
cap = cv2.VideoCapture(0)
time.sleep(2)
while True:
ret, frame = cap.read()
frameCopy = np.copy(frame)
frameWidth = frame.shape[1]
frameHeight = frame.shape[0]
aspect_ratio = frameWidth / frameHeight
threshold = 0.1
t = time.time()
net.setInput(cv2.dnn.blobFromImage(frame, 1.0, (368, 368), (0, 0, 0), swapRB=False, crop=False))
out = net.forward()
print("time taken by network : {:.3f}".format(time.time() - t))
out = out[:, :nPoints, :, :]
assert (len(POSE_PAIRS) == out.shape[1])
points = []
for i in range(nPoints):
# confidence map of corresponding body's part.
probMap = out[0, i, :, :]
probMap = cv2.resize(probMap, (frameWidth, frameHeight))
# Find global maxima of the probMap.
minVal, prob, minLoc, point = cv2.minMaxLoc(probMap)
if prob > threshold:
cv2.circle(frameCopy, (int(point[0]), int(point[1])), 8, (0, 255, 255), thickness=-1, lineType=cv2.FILLED)
cv2.putText(frameCopy, "{}".format(i), (int(point[0]), int(point[1])), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, lineType=cv2.LINE_AA)
# Add the point to the list if the probability is greater than the threshold
points.append((int(point[0]), int(point[1])))
else:
points.append(None)
# Draw Skeleton
for pair in POSE_PAIRS:
partA = pair[0]
partB = pair[1]
if points[partA] and points[partB]:
cv2.line(frame, points[partA], points[partB], (0, 255, 255), 2)
cv2.circle(frame, points[partA], 8, (0, 0, 255), thickness=-1, lineType=cv2.FILLED)
cv2.imshow('Output-Keypoints', frameCopy)
cv2.imshow('Output-Skeleton', frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
该代码使用了一个基于Caffe的预训练神经网络,首先从摄像头中读取帧,然后对每个帧进行预测,以检测人体的关键点,并绘制骨架。你可以根据自己的需求进行修改。