如果我"clicked"这个按钮,如何更改 cv2.矩形上的颜色?



我想改变我的矩形的颜色,如果我点击这个自制按钮。不幸的是,当我的食指指向这个按钮时,我已经设法改变了颜色。当我把食指从按钮上移开时,它又恢复了原来的颜色。

我如何实现它,当我移动我的食指到这个按钮,并保持它一秒钟(为exl。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语句中添加另一个条件,而不是仅仅取决于食指的位置,这取决于变量(例如,iftTrue还是False)。这可能令人困惑,但让我用示例来解释它:

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():时间文档

现在,我知道对于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)

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

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

相关内容

  • 没有找到相关文章

最新更新