Skip to content

Instantly share code, notes, and snippets.

@kianurivzzz
Created November 12, 2023 13:59
Show Gist options
  • Save kianurivzzz/772910ce096b36395047487e38b3d1d9 to your computer and use it in GitHub Desktop.
Save kianurivzzz/772910ce096b36395047487e38b3d1d9 to your computer and use it in GitHub Desktop.
import cv2
import mediapipe as mp
cap = cv2.VideoCapture(0)
mp_hands = mp.solutions.hands
hands = mp_hands.Hands(max_num_hands=2)
mp_draw = mp.solutions.drawing_utils
blue, green, red = 0, 0, 255
square_size = 50
square_pos = [300, 150]
while True:
success, image = cap.read()
image = cv2.resize(image, (image.shape[1] // 2, image.shape[0] // 2))
image = cv2.flip(image, 1)
x1, y1 = square_pos
x2, y2 = x1 + square_size, y1 + square_size
cv2.rectangle(image, (x1, y1), (x2, y2), (blue, green, red), 5)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = hands.process(image_rgb)
if results.multi_hand_landmarks:
for hand_idx, hand_lms in enumerate(results.multi_hand_landmarks):
for id, lm in enumerate(hand_lms.landmark):
if hand_idx == 0 or hand_idx == 1:
h, w, c = image.shape
cx, cy = int(lm.x * w), int(lm.y * h)
if id == 8:
# Если палец касается левой границы квадрата
if (x1 - 15 <= cx <= x1 + 15) and y1 <= cy <= y2:
square_pos[0] += 10
red = 0
green = 255
# Если палец касается верхней границы квадрата
elif (y1 - 15 <= cy <= y1 + 15) and x1 <= cx <= x2:
square_pos[1] += 10
red = 0
green = 255
# Если палец касается правой границы квадрата
elif (x2 + 15 >= cx >= x2) and y1 <= cy <= y2:
square_pos[0] -= 10
red = 0
green = 255
# Если палец касается нижней границы квадрата
elif (y2 + 15 >= cy >= y2) and x1 <= cx <= x2:
square_pos[1] -= 10
red = 0
green = 255
else:
red = 255
green = 0
mp_draw.draw_landmarks(image, hand_lms, mp_hands.HAND_CONNECTIONS)
cv2.imshow('Find hand and move rectangle', image)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment