#!/usr/bin/python3

import cv2
import numpy as np

# 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)

while True:
    # Read frames from both cameras
    ret_left, frame_left = cap_left.read()
    ret_right, frame_right = cap_right.read()
    
    # Break the loop if either of the cameras fails to read a frame
    if not ret_left or not ret_right:
       print("Error: Couldn't read frames from one or both cameras.")
       break

    # Display the frames side by side for stereo effect
    stereo_frame = cv2.hconcat([frame_left, frame_right])

    # Display the stereo frame
    cv2.imshow('Stereo Camera Feed', stereo_frame)

    # Break the loop if 'q' key is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

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