#!/usr/bin/python3

import cv2
import threading

# Function to continuously read frames from a camera and display them
def display_frames(cap, window_name):
    while True:
        ret, frame = cap.read()
        if not ret:
            print(f"Error reading frame from {window_name} camera.")
            break

        cv2.imshow(window_name, frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

# Open two video capture objects for each camera
cap_left = cv2.VideoCapture(1)  # Adjust the index if needed
cap_right = cv2.VideoCapture(2)  # Adjust the index if needed

# Check if the cameras opened successfully
if not cap_left.isOpened() or not cap_right.isOpened():
    print("Error: Couldn't open one or both cameras.")
    exit()

# Set the width and height of the video capture (adjust as needed)
cap_left.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap_left.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
cap_right.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
cap_right.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

# Create threads for each camera
thread_left = threading.Thread(target=display_frames, args=(cap_left, 'Left Camera'))
thread_right = threading.Thread(target=display_frames, args=(cap_right, 'Right Camera'))

# Start the threads
thread_left.start()
thread_right.start()

# Wait for the threads to finish (when 'q' is pressed)
thread_left.join()
thread_right.join()

# Release the video capture objects and close the OpenCV windows
cap_left.release()
cap_right.release()
cv2.destroyAllWindows()
