- 1 year ago
Videocapture() with multiple cameras
To capture video from multiple cameras using OpenCV's VideoCapture
in Python, you can follow these steps:
- Import the necessary libraries:
pythonimport cv2
- Determine the number of cameras available:
pythonnum_cameras = 2 # Adjust the number based on the available cameras
- Create instances of
VideoCapture
for each camera:
pythoncapture_list = []
for i in range(num_cameras):
capture = cv2.VideoCapture(i)
if not capture.isOpened():
print(f"Camera {i} not available.")
capture_list.append(capture)
In the above code, we create a list called capture_list
to store instances of VideoCapture
for each camera. We iterate over the range of the number of cameras and create a VideoCapture
object for each camera using its index (i
).
- Start capturing frames from each camera:
pythonwhile True:
frames = []
for capture in capture_list:
ret, frame = capture.read()
if ret:
frames.append(frame)
# Process or display the frames as needed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
In the above code, we enter a loop to continuously capture frames from each camera. We use a nested loop to iterate over capture_list
and read frames from each camera using capture.read()
. The frames are stored in a list called frames
.
You can then process or display the frames as required within the loop. Pressing 'q' will break the loop and exit the program.
- Release the
VideoCapture
objects and clean up:
pythonfor capture in capture_list:
capture.release()
cv2.destroyAllWindows()
After you finish capturing frames, make sure to release the VideoCapture
objects and close any open windows using release()
and destroyAllWindows()
respectively.
By following these steps, you can capture video from multiple cameras simultaneously using OpenCV's VideoCapture
in Python. Adjust the num_cameras
variable to match the number of available cameras on your system, and modify the processing or display logic as needed for your specific use case.