我正在使用 OpenCV 2.4.9 和 Python 2.7.11。
我编写了一个显示相机输出的小程序,当按下“q”时,关闭相机但不退出应用程序(用于进一步工作......)。
问题是网络摄像头没有真正释放,LED 一直亮着,当我再次尝试打开它时,它说资源繁忙,直到我完全退出程序。 它在 Windows 中工作正常,但是......
代码如下:
import cv2
import sys
cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if frame is None:
print "BYE"
break
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
while True:
cv2.waitKey(1)
我错过了什么?有没有办法在不退出程序的情况下释放相机? 提前致谢
最佳答案
释放相机(不退出)的方法确实是release()。我已经在运行 OpenCV 2.4.13 和 OpenCV 3.1 以及 Python 2.7.12 的 Linux Mint 18(64 位)环境中测试了您的代码。没有问题。
这是一种让您查看代码中正在发生的事情的方法:
import cv2
import sys
#print "Before cv2.VideoCapture(0)"
#print cap.grab()
cap = cv2.VideoCapture(0)
print "After cv2.VideoCapture(0): cap.grab() --> " + str(cap.grab()) + "\n"
while True:
ret, frame = cap.read()
if frame is None:
print "BYE"
break
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
print "After breaking, but before cap.release(): cap.grab() --> " + str(cap.grab()) + "\n"
cap.release()
print "After breaking, and after cap.release(): cap.grab() --> " + str(cap.grab()) + "\n"
cap.open(0)
print "After reopening cap with cap.open(0): cap.grab() --> " + str(cap.grab()) + "\n"
cv2.destroyAllWindows()
while True:
cv2.waitKey(1)
您可能需要考虑在您的系统上重新安装 OpenCV。我建议查看 PyImageSearch 上的精彩指南 --> http://www.pyimagesearch.com/opencv-tutorials-resources-guides/
如果这有帮助,请告诉我!
关于Python OpenCV - VideoCapture.release() 在 Linux 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38497384/