如果我在此按钮上 "clicked",如何更改 cv2.rectangle 上的颜色?

How to change the colour on a cv2.rectangle if I "clicked" on this button?

如果我单击这个自制按钮,我想更改矩形的颜色。不幸的是,当我的食指指向这个按钮时,我设法改变了颜色。当我从按钮上移开食指时,它 returns 变成原来的颜色。

我该如何实现,当我将食指移到此按钮上并按住它一秒钟(例如 4 秒)时,按钮的紫色应该永久变为绿色。如果我再次按住它,我的绿色按钮应该永久变为紫色。

cv2.rectangle(image, (100, 300), (200, 200), (255, 0, 255), cv2.FILLED)
thumb = res.right_hand_landmarks[8]
if ((thumb.x < 0.40 and thumb.x >= 0.30) and 
     (thumb.y < 0.69 and thumb.y >= 0.64)):
     cv2.rectangle(image, (100, 300), (200, 200), (0, 255, 0), cv2.FILLED)

在这里,你可以在if语句中添加另一个条件,而不是仅仅依赖于食指的位置,这取决于变量(例如,ift是否是TrueFalse。这可能令人困惑,但让我用示例来解释一下:

ift = False 
# Keep the var 'False' if the index finger was not in the self-made button for 4 seconds or more, else 'True'

现在,为了计算时间,您可以使用内置的 time 模块。这是一个例子:

from time import time, sleep

val = time()
sleep(1)
print(int(time() - val)) # Converting to integer, as the default is set to 'float'

# OUTPUT
# 1

这是 time 模块的文档,您可以在其中找到 time.time()time Documentation

现在,我知道 cv2,你实际上不能使用 sleep,因为它会停止整个迭代,所以这里有另一个解决方法,例如:

from time import time

var = False
x = time()
y = time()

while True:
    if not var:
        x = time()
        # If the 'var' is False, it will refresh the 'time()' value in every iteration, but not if the value was True.
    
    if int(time() - y) >= 4: 
        print(int(time() - x), int(time() - y)) 
        break

# OUTPUT
# 0 4

现在,我们知道了如何使用上述逻辑计算经过的时间,让我们在您的代码中实现它:

from time import time

# Variables below outside the loop, so that it doesn't reset at every iteration
ift = False # Let's assume 'False' is for 'purple' and 'True' is for 'green'
inside = False # It's to check whether the finger is in or not 
t = time() # If the below code (you provided) is in a function, then I prefer adding it in the function before the loop starts

# Everything under is assumed to be inside the loop (assuming you are using the loop)
thumb = res.right_hand_landmarks[8]
if ((thumb.x < 0.40 and thumb.x >= 0.30) and 
     (thumb.y < 0.69 and thumb.y >= 0.64)):
    cv2.rectangle(image, (100, 300), (200, 200), (255, 0, 255), cv2.FILLED)
    inside = True
else: 
    cv2.rectangle(image, (100, 300), (200, 200), (0, 255, 0), cv2.FILLED)
    inside = False
    t = time() # Refreshes the time, because the finger is no more inside

if inside and int(time() - t) >= 4:
    ift = not ift # Changes the value of 'ift' to its opposite, i.e., if the value was False, it will become True and vice versa

if ift:
    cv2.rectangle(image, (100, 300), (200, 200), (0, 255, 0), cv2.FILLED)
else:
    cv2.rectangle(image, (100, 300), (200, 200), (255, 0, 255), cv2.FILLED)

上面提到的代码可能会或可能不会工作,因为它没有经过测试。但是,这足以为您提供有关可以使用什么逻辑来解决问题的信息。

注意,上面的代码可以在扩展时减少,并且可能有可以减少的无用行,但为了便于解释,它已被扩展。