Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 1482f46

Browse files
authoredOct 2, 2024··
Volume Control with hands
1 parent 00e9d86 commit 1482f46

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
 

‎computer_vision/WaveTune.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import cv2
2+
import mediapipe as mp
3+
import pyautogui
4+
import math
5+
import time
6+
CAMERA_ID = 0
7+
FLIP_IMAGE = True
8+
VOLUME_CHANGE_COOLDOWN = 0.5
9+
VOLUME_CHANGE_THRESHOLD = 50
10+
def main():
11+
cap = cv2.VideoCapture(CAMERA_ID)
12+
if not cap.isOpened():
13+
print(f"Error: Could not open camera with ID {CAMERA_ID}")
14+
return
15+
hands = mp.solutions.hands.Hands(static_image_mode=False, max_num_hands=1, min_detection_confidence=0.5, min_tracking_confidence=0.5)
16+
mpDraw = mp.solutions.drawing_utils
17+
last_volume_change_time = 0
18+
distance = 0
19+
while True:
20+
success, image = cap.read()
21+
if not success:
22+
print("Failed to capture frame")
23+
break
24+
if FLIP_IMAGE:
25+
image = cv2.flip(image, 1)
26+
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
27+
results = hands.process(image_rgb)
28+
if results.multi_hand_landmarks:
29+
for hand_landmarks in results.multi_hand_landmarks:
30+
mpDraw.draw_landmarks(image, hand_landmarks, mp.solutions.hands.HAND_CONNECTIONS)
31+
thumb_tip = hand_landmarks.landmark[4]
32+
index_tip = hand_landmarks.landmark[8]
33+
x1, y1 = int(thumb_tip.x * image.shape[1]), int(thumb_tip.y * image.shape[0])
34+
x2, y2 = int(index_tip.x * image.shape[1]), int(index_tip.y * image.shape[0])
35+
cv2.circle(image, (x1, y1), 8, (0, 0, 255), -1)
36+
cv2.circle(image, (x2, y2), 8, (0, 255, 255), -1)
37+
cv2.line(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
38+
distance = math.hypot(x2 - x1, y2 - y1)
39+
current_time = time.time()
40+
if current_time - last_volume_change_time > VOLUME_CHANGE_COOLDOWN:
41+
if distance > VOLUME_CHANGE_THRESHOLD:
42+
pyautogui.press("volumeup")
43+
print("Volume Up")
44+
else:
45+
pyautogui.press("volumedown")
46+
print("Volume Down")
47+
last_volume_change_time = current_time
48+
cv2.putText(image, f"Distance: {int(distance)}", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
49+
cv2.imshow("Hand Volume Control", image)
50+
key = cv2.waitKey(1) & 0xFF
51+
if key == 27:
52+
print("Esc key pressed. Exiting...")
53+
break
54+
elif key == ord('q'):
55+
print("Q key pressed. Exiting...")
56+
break
57+
cap.release()
58+
cv2.destroyAllWindows()
59+
print("Program ended")
60+
if __name__ == "__main__":
61+
main()

0 commit comments

Comments
 (0)
Please sign in to comment.