“I am using six USB cameras for a multi-camera OpenCV project. Each time I reconnect or reboot the system, the camera indices change, and even the USB serial mappings are inconsistent. How can I reliably maintain a fixed and correct camera order for proper alignment in OpenCV?”
The index is only the order in which the OS lists the devices, so it will change after a reboot or replug. The fix is to not use the index as the identity.
Linux: open the camera by path instead. /dev/v4l/by-path/… is tied to the physical USB port, and /dev/v4l/by-id/… is tied to the camera’s serial. Cheap cameras of the same model often share the same ID, so by-path is usually safer. You can also write udev rules that create fixed names such as /dev/cam_left. Then use cv2.VideoCapture(path, cv2.CAP_V4L2).
Windows: the index follows the DirectShow/MSMF order. Either plug each camera into the same USB port every time and list the device names with a DirectShow helper library (for example pygrabber), or run a one-time “identify” step and save the mapping to a file.
A trick that works on both: put a printed ArUco marker (a different ID per camera) or a labelled card in front of each camera, and at startup open every index and check which marker each one sees. That builds the mapping automatically and still works when two identical cameras swap places.
Also, six USB cameras on one controller often run out of bandwidth. Use separate controllers or hubs, MJPG mode, and a lower resolution if frames drop.
On Linux, run ls -l /dev/v4l/by-path/ to map each physical USB port to its camera position. Keep the cameras on those ports and use cv2.VideoCapture(path, cv2.CAP_V4L2) to open the corresponding capture node instead of using an index. Some cameras expose multiple video nodes, so check which one produces frames. If you want clearer names, a udev rule can create a symlink for each port. Verify the mapping after reconnecting before using it for alignment.
One addition: treat the startup mapping as a checked invariant, not a one-time lookup. After resolving the by-path/udev names (or ArUco IDs), open every camera, read a frame, and verify frame arrival; if any expected name is missing, abort rather than falling back to numeric indices, because a silent fallback is what breaks alignment. Save the known mapping to a config file, but revalidate it on boot. Also note that if identical cameras swap physical ports, by-path follows the port, not the camera, so the marker check is the identity check that survives that.