简体   繁体   English

退出功能在使用Python的OpenCV中不起作用

[英]Exit function doesn't work in OpenCV with python

I just want to capture one frame, save it to test.png and then exit the code. 我只想捕获一帧,将其保存到test.png ,然后退出代码。 In this program exit() doesn't work, I have to use CTRL+C from the terminal every time. 在此程序中, exit()不起作用,我每次必须在终端上使用CTRL + C。

import cv2

#cv2.namedWindow("window")
cap = cv2.VideoCapture(0)

if cap.isOpened(): # if we are able to capture the first frame.
    val, frame = cap.read()
else:
    val = False
while val:
    #cv2.imshow("window", frame)
    cv2.imwrite('test.png',frame)
    val, frame = cap.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break

cap.release
cv2.destroyAllWindows()
exit()

Thanks in advance. 提前致谢。

Try adding & 0xFF to the wait key: 尝试将&0xFF添加到等待键:

key = cv2.waitKey(20) & 0xFF

You also need an active window: 您还需要一个活动窗口:

Note The function only works if there is at least one HighGUI window created and the window is active. 注意只有在至少创建了一个HighGUI窗口并且该窗口处于活动状态时,该函数才起作用。 If there are several HighGUI windows, any of them can be active. 如果有多个HighGUI窗口,则它们中的任何一个都可以处于活动状态。

The method waitkey(t) waits t in milliseconds, so your code is waiting 20 ms for a key press for each loop. 方法waitkey(t)以毫秒为单位等待t,因此您的代码为每个循环等待20 ms的按键操作。 Considering that your 考虑到你

cv2.imwrite('test.png',frame)

might take some time to write to file, are you perhaps pressing your exiting key at the wrong moment? 可能需要一些时间来写入文件,您是否可能在错误的时间按了退出键?

cv::waitKey only works if any openCV window is present and maybe active. cv::waitKey仅在存在任何openCV窗口且可能处于活动状态时才起作用。

Since you commented #cv2.namedWindow("window") and #cv2.imshow("window", frame) out there is no waitKey time and no chance to fetch the key. 由于您注释了#cv2.namedWindow("window")#cv2.imshow("window", frame) ,因此没有waitKey时间,也没有机会获取密钥。

Does it work if you activate namedWindow and imshow? 如果激活namedWindow和imshow是否可以正常工作?

To be sure additionally try 确保另外尝试

if key > 0: # exit on ESC
    break

to cancel on ANY keypress (but you still need an active openCV window) 取消任何按键(但您仍需要一个活动的openCV窗口)

To capture a single frame try this: 要捕获单个帧,请尝试以下操作:

import cv2

cap = cv2.VideoCapture(0)

val = False
maxTry = 100 # maximum number of tries to capture a frame from an opened device
cTry = 0

if cap.isOpened(): # if we are able to capture the first        frame.
    while (!val) and (cTry < maxTry)
        val, frame = cap.read()
        cTry = cTry + 1
else:
    val = False
if val:
    cv2.imwrite('test.png',frame)
else:
    print "No image captured"

cap.release
exit()

I am not a python programmer so please forgive me any syntax errors (and give me a hint to correct them) 我不是python程序员,所以请原谅我任何语法错误(并给我提示以纠正它们)

for python3 对于python3

cv2.imshow('imafast', frame)
if cv2.waitKey(25) & 0xFF == ord('q'):
    break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM