摄像头或者视频输出检测人体姿态
import cv2
import mediapipe as mp
import time
"""封装1肢体检测"""
class poseDetector():
def __init__(self,mode = False,complexity = 1,smooth_landmarks = True,enable_segmentation = False,smooth_segmentation = True,detection = 0.5,tracking = 0.5):
self.mode = mode
self.complexity = complexity
self.smooth_landmarks = smooth_landmarks
self.enable_segmentation = enable_segmentation
self.smooth_segmentation = smooth_segmentation
self.detection = detection
self.tracking =tracking
self.mpDraw = mp.solutions.drawing_utils
self.mpPose = mp.solutions.pose
self.pose = self.mpPose.Pose(self.mode,self.complexity,self.smooth_landmarks,self.enable_segmentation,self.smooth_segmentation,self.detection,self.tracking)
def findPose(self,frame,draw=True):
imgRGB = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
self.results = self.pose.process(imgRGB)
if self.results.pose_landmarks:
if draw:
self.mpDraw.draw_landmarks(frame, self.results.pose_landmarks, self.mpPose.POSE_CONNECTIONS)
return frame
def findPosition(self,frame,draw=True):
lmList =[]
if self.results.pose_landmarks:
for id, lm in enumerate(self.results.pose_landmarks.landmark):
h,w,c = frame.shape
print("id=",id)
print("lm=",lm)
cx,cy=int(lm.x*w),int(lm.y*h)
print("cx and cy = ",cx,cy)
lmList.append([id,cx,cy])
if draw:
cv2.circle(frame, (cx, cy), 2, (255, 0, 0), cv2.FILLED)
# if id==0:
# cv2.circle(frame, (cx, cy), 5, (0, 0, 255), cv2.FILLED)
# else:
# cv2.circle(frame,(cx,cy),2,(255,0,0),cv2.FILLED)
return lmList
def main():
#视频检测
# cap = cv2.VideoCapture('C:/zk/work/code/python/opencv4/opencv_tutorial_data-master/images/01.mp4')
#摄像头检测
cap = cv2.VideoCapture(0)
pTime = 0
detector = poseDetector()
while True:
ret, frame = cap.read()
frame = detector.findPose(frame)
lmList = detector.findPosition(frame,draw=False)
if len(lmList) != 0:
print(lmList[0])
cv2.circle(frame, (lmList[0][1], lmList[0][2]), 5, (255, 0, 0), cv2.FILLED)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(frame, str(int(fps)), (70, 50), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 0), 3)
cv2.imshow('Image', frame)
c = cv2.waitKey(1)
if c == 27:
break
if __name__ == "__main__":
main()