Python OpenCV - VideoCapture.release()在Linux中不起作用

问题描述 投票:1回答:2

我正在使用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)

我错过了什么?有没有办法在不退出程序的情况下释放相机?提前致谢

python linux opencv video-capture
2个回答
3
投票

释放相机(不退出)的方法确实是release()。我已经在运行OpenCV 2.4.13的Linux Mint 18(64位)环境中测试了您的代码,并使用Python 2.7.12运行了OpenCV 3.1。没有问题。

您可以通过以下方式查看代码中发生的情况:

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/

如果这有帮助,请告诉我!


0
投票

我有同样的问题。默认情况下,我的OpenCV构建使用Gstreamer作为VideoCapture()的后端。如果我强迫它使用V4L2,例如

cap = VideoCapture(0,cv2.CAP_V4L2)

cap.release()工作。

Gstreamer后端应该能够关闭它打开的任何管道(参见这里的源代码:https://github.com/opencv/opencv/blob/master/modules/videoio/src/cap_gstreamer.cpp),但对于我的后端不可知的应用程序,它比解决这个问题更容易避免。

© www.soinside.com 2019 - 2024. All rights reserved.