我构建了一个调用 IP 摄像机的 python 模块,但是当我尝试关闭由 cv2 生成的窗口时,该窗口会在无限循环中一次又一次地生成。你能帮我解决这个问题吗?
这是脚本
import cv2
source = "rtsp://admin:admin2016@192.168.1.2//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()
最佳答案
我无法完全重现你的错误(我最终用你的代码导致 Python 崩溃),但我确实想出了一个修复方法。
while ok_flag:
(ok_flag, img) = cap.read()
cv2.imshow("CallingCamera View", img)
if cv2.waitKey(0) == 27:
ok_flag = False
cv2.destroyAllWindows()
我不确定您是否有理由将 waitKey 时间设置为 1 毫秒,出于测试目的,将其设置为 0(永远)同样有效。我想将它设置为 1 毫秒会给你最新的图像?我的测试是使用桌面上的静态图像运行的。否则删除两个中断和 if not ok_flag 语句似乎解决了所有问题。您实际上并不需要这些,因为一旦 ok_flag 变为 False,循环就会终止。
关于python - 如何关闭 cv2 窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37214036/