使用Python中的GPIOZero打开和关闭OpenCV窗口



从下周开始,我已经尝试了12种方法,但运气不佳。我正试图在按下按钮时打开OpenCV窗口,并在发布树莓派时关闭。我很犹豫是否发布代码,只是因为这个例子确实做了一些事情。但已经尝试过将打开的窗口部分放在按下按钮的功能中,将killallwindows部分放在按钮释放功能中。HAve还尝试传递一个变量,所以如果你按下按钮x=1,如果x=1,窗口就会打开,如果不按下,就会关闭。到目前为止,我在本应是个人项目中最容易的部分之一的事情上运气不佳。

这是一些不会崩溃的Janky代码。。。如果我按下按钮,窗户确实会弹出。我非常感谢你的建议!

我知道我在试图让按钮至少打开一个窗口时评论掉了释放按钮部分。。。任何使用它的尝试都没有成功。

import cv2
from gpiozero import Button 
from signal import pause
from time import sleep
cap = cv2.VideoCapture(0)
buttonFocus = Button(14)
def FocusPeakingStart(): 
while(True):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF ==('q'):
break
cap.release()
cv2.destroyAllWindows()

#def FocusPeakingStop(): 
#    print("FocusPeaking Stop") 
buttonFocus.when_pressed = FocusPeakingStart
#buttonFocus.when_released = FocusPeakingStop
pause()

这是对同一件事的另一次尝试。。。它也不起作用。

import cv2
from gpiozero import Button 
from signal import pause
from time import sleep
cap = cv2.VideoCapture(0)
buttonFocus = Button(14)
x=1
while(x == 0):
ret, frame = cap.read()
cv2.imshow('frame', frame)
if x == 1 & 0xFF ==('q'):
break
cap.release()
cv2.destroyAllWindows()
if buttonFocus.when_pressed:
x == 0
if buttonFocus.when_released:
x == 1
pause()

所以这是另一个尝试。。。

import cv2
from gpiozero import Button 
from time import sleep
from signal import pause
cap = cv2.VideoCapture(0)
x=0  #if button press set the X to 1(true) to start your while loop
buttonFocus = Button(27)
def FocusPeakingStart():
print("Focus Down")
global x
x=1
print(x)
def FocusPeakingStop():
print("Focus Up")
global x
x=0
print(x)
while(x):
ret, frame = cap.read()
cv2.imshow('image',frame)
k = cv2.waitKey(1) & 0xFF
if k == ord("r"):
continue #continue when "r" press on keyboard
elif k == 27:
break #break the loop if the button stop press
cv2.destroyAllWindows()
buttonFocus.when_pressed = FocusPeakingStart
buttonFocus.when_released = FocusPeakingStop
pause()

按钮在1和0之间更改X,但它们不会触发While循环打开窗口。

我没有树莓派,但我试着用键盘键模拟它

import cv2
from time import sleep
cap = cv2.VideoCapture(0)
x=1  #if button press set the X to 1(true) to start your while loop
while(x):
ret, frame = cap.read()
cv2.imshow('image',frame)
k = cv2.waitKey(1) & 0xFF
if k == ord("r"):
continue #continue when "r" press on keyboard
elif k == 27:
break #break the loop if the button stop press
cv2.destroyAllWindows()

cv2.waitkey用于等待或检测任何键盘键。当按下键盘上的任何按钮时,cv2.waitkey都会返回一个值,我们在这里所做的是将键盘键与我们想要的值相匹配。对于您的情况,您可以更换树莓按钮。

参见Ascii表Esc-27r-114

";单词";是将char("r"(转换为十进制。

你可以参考这个来了解更多关于opencv功能链接的信息

最新更新