Untitled
unknown
plain_text
a year ago
2.2 kB
9
Indexable
import cv2
import time
class MultiCameraCapture:
def __init__(self, camera_indices):
# Initialize a list of VideoCapture objects based on the provided indices
self.cameras = [cv2.VideoCapture(index) for index in camera_indices]
# Check if all cameras are opened successfully
if not all(cam.isOpened() for cam in self.cameras):
raise RuntimeError("Error: One or more cameras could not be opened.")
def read(self):
frames = []
timestamps = []
# Record the timestamp before capturing frames
start_time = time.time()
for cam in self.cameras:
ret, frame = cam.read()
if not ret:
raise RuntimeError("Error: Failed to capture frame from one or more cameras.")
frames.append(frame)
# Record the timestamp after capturing frames
end_time = time.time()
timestamps.append(start_time)
timestamps.append(end_time)
return frames, timestamps
def release(self):
# Release all camera resources
for cam in self.cameras:
cam.release()
def __del__(self):
# Ensure cameras are released when the object is deleted
self.release()
# Example usage
if __name__ == "__main__":
# Indices for the cameras (adjust as necessary)
camera_indices = [0, 1, 2, 3]
# Create an instance of the MultiCameraCapture class
multi_camera = MultiCameraCapture(camera_indices)
try:
while True:
frames, timestamps = multi_camera.read()
# Display the frames (for demonstration purposes)
for i, frame in enumerate(frames):
cv2.imshow(f'Camera {i+1}', frame)
# Print timestamps to check synchronization
print(f"Timestamps: {timestamps}")
# Exit loop on 'q' key press
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
# Release resources and close all windows
multi_camera.release()
cv2.destroyAllWindows()Editor is loading...
Leave a Comment