Python 如何关闭 cv2 窗口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37214036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I close a cv2 window?
提问by Patricio Palacios
I build a python module that calls an IP Camera, but when I try to close the window generated by cv2 the window is generated again and again in an infinite loop. Can you help me with this?
我构建了一个调用 IP 摄像机的 python 模块,但是当我尝试关闭由 cv2 生成的窗口时,该窗口会在无限循环中一次又一次地生成。你能帮我解决这个问题吗?
This is the script
这是脚本
import cv2
source = "rtsp://admin:[email protected]//Streaming/Channels/2"
cap = cv2.VideoCapture(source)
ok_flag = True
while ok_flag:
(ok_flag, img) = cap.read()
if not ok_flag:
break
cv2.imshow("CallingCamera View", img)
if cv2.waitKey(1) == 27:
ok_flag = False
break
cv2.destroyAllWindows()
回答by Grr
I couldn't quite replicate your error (I ended up crashing python with your code), but I did come up with a fix.
我无法完全复制您的错误(我最终用您的代码使 python 崩溃),但我确实想出了一个修复程序。
while ok_flag:
(ok_flag, img) = cap.read()
cv2.imshow("CallingCamera View", img)
if cv2.waitkey(0) ==27:
ok_flag = False
cv2.destroyAllWindows()
I wasn't sure if you had a reason for setting the waitKey time to 1ms or not, for testing purposes setting it to 0 (forever) worked just the same. I guess setting it to 1ms for you would get you the most recent image? My test was run with a static image residing on my desktop. Otherwise removing the two breaks and the if not ok_flag statement seemed to iron everything out. You don't really need those since as soon as ok_flag goes to False the loop terminates.
我不确定您是否有理由将 waitKey 时间设置为 1 毫秒,出于测试目的,将其设置为 0(永远)的效果是一样的。我想将它设置为 1ms 会让你得到最新的图像?我的测试是使用驻留在我桌面上的静态图像运行的。否则删除两个中断和 if not ok_flag 语句似乎可以解决所有问题。你真的不需要那些,因为一旦 ok_flag 变为 False,循环就会终止。
回答by user1109729
cv2.destroyWindow("shown_img")
The parameter is the same as used for cv2.imshow("shown_img", img)
参数与用于的相同cv2.imshow("shown_img", img)