Search code examples
pythonopencvpyside2

VideoCapture() camera index and QCameraInfo.availableCameras() index do not match


I try to get a list of cameras to know which one I need to access given their names. However, the list I get with Qt's QCameraInfo.availableCameras() versus the index I supply to cv2.VideoCapture() seem to not always match, so if I have a camera named "CAM1" from QCameraInfo.availableCameras() at index 0, and if I do VideoCapture(0), I don't access "CAM1".

Why and how to fix this?

import cv2
from PySide2.QtMultimedia import QCameraInfo

camera_list = []
index = 0

for cam in QCameraInfo.availableCameras():
    camera_list.append([index, cam.description()])
    index += 1

print(camera_list)

camera = cv2.VideoCapture(0)

Solution

  • So the issue is Windows has more than one backend for cameras and OpenCV uses the MSMF back-end while Qt uses the COM interface (named DirectShow) and the backends have different indexes. A solution is provided by use of cv2.CAP_DSHOW. You can do cv2.VideoCapture(index + cv2.CAP_DSHOW) to fix the issue.