利用Google开源手部追踪
以下为代码及其讲解
import cv2
import mediapipe as mp
import time
cap = cv2.VideoCapture(0)
mpHands = mp.solutions.hands
hands = mpHands.Hands()
mpDraw = mp.solutions.drawing_utils
handLmsStyle = mpDraw.DrawingSpec(color=(0, 0, 255), thickness=5)
handConStyle = mpDraw.DrawingSpec(color=(0, 255, 0), thickness=5)
pTime = 0
cTime = 0
'''
设置mpHands.Hands的参数:
def __init__(self,
static_image_mode=False, #指检测静态图片还是动态图片
max_num_hands=2, #最多能侦测几只手
model_complexity=1, #模型的复杂度
min_detection_confidence=0.5, #侦测手掌的严谨度(0~1)
min_tracking_confidence=0.5): #追踪的严谨度(0~1)
'''
while True:
ret, img = cap.read()
if ret:
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
result = hands.process(imgRGB)
imgHeight = img.shape[0]
imgWidth = img.shape[1]
if result.multi_hand_landmarks:
for handLms in result.multi_hand_landmarks:
mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS, handLmsStyle, handConStyle)
for i, lm in enumerate(handLms.landmark):
xPos = int(lm.x * imgWidth)
yPos = int(lm.y * imgHeight)
cv2.putText(img, str(i), (xPos-25, yPos+5), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (0, 0, 255), 2)
'''
放大某个点
if i ==4:
cv2.circle(img, (xPos, yPos), 10, (0, 0, 255), cv2.FILLED)
'''
print(i, xPos, yPos)
cTime = time.time()
fps = 1/(cTime-pTime)
pTime = cTime
cv2.putText(img, f"FPS :{int(fps)}", (30, 50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0))
cv2.imshow('img', img)
if cv2.waitKey(1) == ord('q'):
break
|