我想编写一段代码,在其中按住一个键,直到执行另一个操作。这是我的代码:
'''
virtual steering wheel
hold your hand as you hold steering wheel
turn right
turn left
'''
import cv2
import mediapipe as mp
import math
import keyboard
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
switch_hand = 1
decider = 0
# For webcam input:
cap = cv2.VideoCapture(0)
with mp_hands.Hands(
min_detection_confidence=0.5,
min_tracking_confidence=0.5) as hands:
while cap.isOpened():
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
# If loading a video, use 'break' instead of 'continue'.
continue
# Flip the image horizontally for a later selfie-view display, and convert
# the BGR image to RGB.
image = cv2.cvtColor(cv2.flip(image, 1), cv2.COLOR_BGR2RGB)
# To improve performance, optionally mark the image as not writeable to
# pass by reference.
image.flags.writeable = False
results = hands.process(image)
# Draw the hand annotations on the image.
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
right_temp = []
left_temp = []
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(image, hand_landmarks, mp_hands.HAND_CONNECTIONS)
# x and y cordinates of thumbtip
if switch_hand == 1:
right_temp.append([float(hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].x), float(hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].y)])
elif(switch_hand == -1):
left_temp.append([float(hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].x), float(hand_landmarks.landmark[mp_hands.HandLandmark.WRIST].y)])
switch_hand *= -1
if(len(right_temp) == 1 or len(left_temp) == 1):
try:
myradians = math.atan2(right_temp[0][1]- left_temp[0][1], right_temp[0][0] - left_temp[0][0])
mydegrees = int(math.degrees(myradians))
#print(int(mydegrees))
if(int(mydegrees > 14) or (-170 < mydegrees < -160)):
print("right")
keyboard.press('d')
elif(int(mydegrees <-15)):
print("left")
keyboard.press('a')
else:
print("nothing")
keyboard.release()
except:
pass
cv2.imshow('View pannel', image)
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
当代码输出“右”时,我想像在物理世界中那样按住“d”键,一旦代码输出“左”就松开键,反之亦然。
我的代码的问题是:
在循环的每一步中,它都会按下并释放一个键,类似于多次按下一个键。