DanielY DanielY - 4 months ago 58
Linux Question

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

Answer

The way to free the camera (without exiting) is indeed release(). I've tested your code in Linux Mint 18 (64bit) running OpenCV 3.1 and 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)

Let me know if this helps!