【问题标题】:Python OpenCV - VideoCapture.release() won't work in LinuxPython OpenCV - VideoCapture.release() 在 Linux 中不起作用
【发布时间】:2016-11-24 15:24:26
【问题描述】:

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

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

【问题讨论】:

  • 删除最后两行,因为那是导致应用程序挂起的原因(无论您按什么键,它都会停留在那里)
  • @BillalBEGUERADJ 我知道!!而不是这些行,而是一些与我的项目相关的代码......我的观点是应用程序始终在应用程序中,但必须在不退出的情况下释放相机
  • 我无法重现您的问题。我的意思是您的代码在我的机器上运行良好(Ubuntu 16.04 LTS,x64 位)

标签: python linux opencv video-capture


【解决方案1】:

我遇到了同样的问题。默认情况下,我的 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),但对于我的后端无关应用程序来说,避免这个问题比解决这个问题更容易。

【讨论】:

  • 非常感谢 Anna...我已经被这个问题困扰了一段时间!
【解决方案2】:

释放相机(不退出)的方法确实是release()。我已经在运行 OpenCV 2.4.13 和带有 Python 2.7.12 的 OpenCV 3.1 的 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/

如果有帮助,请告诉我!

【讨论】:

  • 嗨。谢谢。在我写到这个网站之前,我已经做了类似的事情。尝试在您的代码中在 release() 之后再次调用 cv2.open(0)。虽然它应该可以工作并重新打开相机,但它会告诉你“资源很忙”
  • cv2.open(0) 会给出 --> AttributeError: 'module' object has no attribute 'open'
  • 你必须使用 cap.open(0)。使用后它起作用了。我会更新答案
  • 我会尝试重新构建opencv
  • 即使问题没有解决,我也会接受你的回答,因为它可能与 opencv 构建有关
猜你喜欢
  • 2018-05-10
  • 1970-01-01
  • 2015-02-23
  • 2020-12-23
  • 1970-01-01
  • 2021-04-15
  • 2013-12-13
  • 2020-09-30
  • 2011-11-17
相关资源
最近更新 更多