Hand Tracking Module
Hand Tracking Module
import mediapipe as mp
import time
import math
class handDetector():
def __init__(self, mode=False, maxHands=2, modelComp=1, detectionCon=0.5,
trackCon=0.5):
self.mode = mode
self.maxHands = maxHands
self.modelComp = modelComp
self.detectionCon = detectionCon
self.trackCon = trackCon
self.mpHands = mp.solutions.hands
self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.modelComp,
self.detectionCon, self.trackCon)
self.mpDraw = mp.solutions.drawing_utils
self.tipIds = [4, 8, 12, 16, 20]
if self.results.multi_hand_landmarks:
for handLms in self.results.multi_hand_landmarks:
if draw:
self.mpDraw.draw_landmarks(img, handLms,
self.mpHands.HAND_CONNECTIONS)
return img
if draw:
cv2.rectangle(img, (xmin - 20, ymin - 20), (xmax + 20, ymax + 20),
(0, 255, 0), 2)
# Fingers
for id in range(1, 5):
if len(self.lmList) >= max(self.tipIds[id], self.tipIds[id] - 2):
if self.lmList[self.tipIds[id]][2] <
self.lmList[self.tipIds[id] - 2][2]:
fingers.append(1)
else:
fingers.append(0)
else:
fingers.append(0)
else:
fingers = [0] * 5 # Return 0 for all fingers if no landmarks are
detected
return fingers
if draw:
cv2.line(img, (x1, y1), (x2, y2), (255, 0, 255), t)
cv2.circle(img, (x1, y1), r, (255, 0, 255), cv2.FILLED)
cv2.circle(img, (x2, y2), r, (255, 0, 255), cv2.FILLED)
cv2.circle(img, (cx, cy), r, (0, 0, 255), cv2.FILLED)
length = math.hypot(x2 - x1, y2 - y1)
def main():
pTime = 0
cTime = 0
cap = cv2.VideoCapture(0)
detector = handDetector()
while True:
success, img = cap.read()
img = detector.findHands(img)
lmList, bbox = detector.findPosition(img)
if len(lmList) != 0:
print(lmList[4])
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
if __name__ == "__main__":
main()