import cv2
import os

# Set the camera index (change to the appropriate index if needed)
camera_index = 1

# Create a directory to save captured images
output_dir = 'camera1_images'
os.makedirs(output_dir, exist_ok=True)

# Initialize the camera
cap = cv2.VideoCapture(camera_index)

# Check if the camera is opened successfully
if not cap.isOpened():
    print(f"Error: Could not open camera {camera_index}")
    exit()
i = 0
# Capture and save 12 images
while i < 12:
    # Capture a frame from the camera
    ret, frame = cap.read()

    # Check if the frame is captured successfully
    if not ret:
        print("Error: Could not read frame")
        break

    # Display the captured image
    cv2.imshow('Captured Image', frame)

    # Wait for a key event (0 means wait indefinitely)
    key = cv2.waitKey(5) & 0xFF

    # Save the captured image if the 's' key is pressed
    if key == ord('s'):
        img_path = os.path.join(output_dir, f'captured_image_{i+1}.jpg')
        cv2.imwrite(img_path, frame)
        print(f"Image {i+1} saved: {img_path}")
        i += 1

    # If 'q' key is pressed, exit the loop
    elif key == ord('q'):
        break

# Release the camera and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()
print("Image capture complete.")
