简体   繁体   中英

Python OpenCV - VideoCapture.release() won't work in Linux

I'm using OpenCV 2.4.9 and Python 2.7.11.

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...).

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...

Here's the code:

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

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)

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/

Let me know if this helps!

I had the same problem. By default, my OpenCV build was using Gstreamer as a backend for VideoCapture(). If I forced it to use V4L2 instead, eg

cap = VideoCapture(0,cv2.CAP_V4L2)

cap.release() worked.

The Gstreamer backend SHOULD be able to close any pipelines it opens (see source code here: https://github.com/opencv/opencv/blob/master/modules/videoio/src/cap_gstreamer.cpp ), but for my backend-agnostic application it was easier to avoid than fix that issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM