Python OpenCV - VideoCapture.release() 在 Linux 中不起作用 [英] Python OpenCV - VideoCapture.release() won't work in Linux
问题描述
我使用的是 OpenCV 2.4.9 和 Python 2.7.11.
I'm using OpenCV 2.4.9 and Python 2.7.11.
我编写了一个显示相机输出的小程序,当按下q"时,关闭相机但不退出应用程序(为了进一步工作......).
I've written a small program that shows the camera output, and when pressing 'q', closes the camera but doesn't exit the application (for further work...).
问题是网络摄像头没有真正释放,LED 一直亮着,当我再次尝试打开它时,它说资源正忙,直到我完全退出程序.不过在 Windows 中它确实可以正常工作...
The issue is that the webcam is not really released, the LED keeps on and when I try again to open it, it says that the resource is busy, until I completely exit the program. It DOES work ok in Windows, though...
代码如下:
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)
我错过了什么?有没有办法在不退出程序的情况下释放相机?提前致谢
What am I missing? Is there a way to free the camera without exiting the program? Thanks in advance
推荐答案
释放相机(不退出)的方法确实是 release().我已经在运行 OpenCV 2.4.13 和 OpenCV 3.1 和 Python 2.7.12 的 Linux Mint 18(64 位)环境中测试了您的代码.没有问题.
The way to free the camera (without exiting) is indeed release(). I've tested your code in a Linux Mint 18 (64bit) environment running both OpenCV 2.4.13 and also OpenCV 3.1 with Python 2.7.12. There were no issues.
您可以通过以下方式查看代码中发生的事情:
Here is a way for you to see what is going on in your code:
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/
You may want to think about reinstalling OpenCV on your system. I recommend checking out the awesome guides on PyImageSearch --> http://www.pyimagesearch.com/opencv-tutorials-resources-guides/
让我知道这是否有帮助!
这篇关于Python OpenCV - VideoCapture.release() 在 Linux 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!