Persistence of camera index across reboots in linux

I am trying to grab video from 3 cameras in linux using opencv. After grabbing, I want to do processing in specific to each of the cameras. The code I am using is


     for(int i=0;i<3;i++) {
        videoS[i].open(i, CAP_V4L2);
}

However, everytime I reboot the pc, the index assigned to these cameras changes. How to ensure that the number representing the specific camera remains same even after reboot

there is no persistence for indices and generally no means to enumerate cameras or ask for cameras by identity.

to my knowledge, there are also no plans to implement any of that. I keep hoping that someone will contradict me. oh well.

you could try messing around with udev rules such that the cameras get consistent names as /dev/videoSomething, where Something is a number you assign, or a device ID.

people usually solve the problem by sidestepping that part of opencv and using V4L2 directly. at least then you’ve got “only” the OS to deal with.

I do what Crackwitz said - manage the camera with V4L2 directly, which provides a lot more control / information.

If you still want to use OpenCV to manage the cameras / streaming etc., you might be able to do some OS / V4L2 stuff and figure out the mapping between camera and OpenCV videodev index?

For example:
To get the camera serial number to /dev/videoX mapping:
ls -lt /dev/video/by-id

To get the camera hardware path to /dev/videoX mapping:
ls -lt /dev/video/by-path

If you can determine that OpenCV videodev index is arranged in the same order as the /dev/videoX devices, you could figure out which physical camera (or hardware address) a given index maps to at runtime. Even if that mapping is arranged in a deterministic order, you would have to consider what happens if a camera is reset at runtime (the mapping might change, etc.)

If that doesn’t work (maybe the mapping isn’t deterministic) you might be able to do something like:

  1. Open a camera with OpenCV and set one of the settings to a specific value (e.g. brightness set to 1 or whatever)
  2. Open each /dev/videoX device one at a time, and query the same setting.
  3. When you find the V4L2 device that has the matching setting (/dev/video3, for example), then you can back out which physical camera is associated with your OpenCV handle.

Might be workable and if so it’s better than nothing, but if you can just manage it all yourself with V4L2 then you can definitely get what you want.