import cv2
import numpy as np
import subprocess

# Define the FFmpeg command to read from the camera
ffmpeg_command = [
    'ffmpeg',
    '-f', 'v4l2',  # Input format
    '-i', '/dev/video0',  # Camera device
    '-f', 'rawvideo',  # Output format
    '-pix_fmt', 'bgr24',  # Pixel format
    '-an',  # Disable audio
    '-sn',  # Disable subtitles
    '-'
]

# Start the FFmpeg process
process = subprocess.Popen(ffmpeg_command, stdout=subprocess.PIPE, bufsize=10**8)

# Set the width and height for the camera resolution
width = 1920
height = 1080

while True:
    # Read a frame from the FFmpeg output
    raw_frame = process.stdout.read(width * height * 3)  # 3 bytes per pixel for BGR
    if not raw_frame:
        break  # Exit the loop if no more frames

    # Convert the byte data to a numpy array and reshape it to an image
    frame = np.frombuffer(raw_frame, np.uint8).reshape((height, width, 3))

    # Display the frame using OpenCV
    cv2.imshow('Camera Stream', frame)

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

# Clean up
process.stdout.close()
process.wait()
cv2.destroyAllWindows()
