How to count cameras in OpenCV 2.3?
Solution 1:
OpenCV still has no API to enumerate the cameras or get the number of available devices. See this ticket on OpenCV bug tracker for details.
Behavior of VideoCapture is undefined for device numbers greater then number of devices connected and depends from API used to communicate with your camera. See OpenCV 2.3 (C++,QtGui), Problem Initializing some specific USB Devices and Setups for the list of APIs used in OpenCV.
Solution 2:
Even if it's an old post here a solution for OpenCV 2/C++
/**
* Get the number of camera available
*/
int countCameras()
{
cv::VideoCapture temp_camera;
int maxTested = 10;
for (int i = 0; i < maxTested; i++){
cv::VideoCapture temp_camera(i);
bool res = (!temp_camera.isOpened());
temp_camera.release();
if (res)
{
return i;
}
}
return maxTested;
}
Tested under Windows 7 x64 with :
- OpenCV 3 [Custom Build]
- OpenCV 2.4.9
- OpenCV 2.4.8
With 0 to 3 Usb Cameras
Solution 3:
This is a very old post but I found that under Python 2.7 on Ubuntu 14.04 and OpenCv 3 none of the solutions here worked for me. Instead I came up with something like this in Python:
import cv2
def clearCapture(capture):
capture.release()
cv2.destroyAllWindows()
def countCameras():
n = 0
for i in range(10):
try:
cap = cv2.VideoCapture(i)
ret, frame = cap.read()
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
clearCapture(cap)
n += 1
except:
clearCapture(cap)
break
return n
print countCameras()
Maybe someone will find this useful.
Solution 4:
I do this in Python:
def count_cameras():
for i in range(10):
temp_camera = cv.CreateCameraCapture(i-1)
temp_frame = cv.QueryFrame(temp_camera)
del(temp_camera)
if temp_frame==None:
del(temp_frame)
return i-1 #MacbookPro counts embedded webcam twice
Sadly Opencv opens the Camera object anyway, even if there is nothing there, but if you try to extract its content, there will be nothing to attribute to. You can use that to check your number of cameras. It works in every platform I tested so it is good.
The reason for returning i-1
is that MacBookPro Counts its own embedded camera twice.