import cv2

def main():
    # Open the default camera (camera index 0)
    cap = cv2.VideoCapture(0)

    while True:
        ret, frame = cap.read()

        # Convert the frame to grayscale for easier processing
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # Apply Gaussian blur to reduce noise and improve contour detection
        blurred = cv2.GaussianBlur(gray, (15, 15), 0)

        # Use adaptive thresholding to create a binary image
        _, thresholded = cv2.threshold(blurred, 127, 255, cv2.THRESH_BINARY)

        # Find contours in the thresholded image
        contours, _ = cv2.findContours(thresholded, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        # Filter the largest contour (assumed to be the hand)
        if len(contours) > 0:
            largest_contour = max(contours, key=cv2.contourArea)
            hull = cv2.convexHull(largest_contour)

            # Calculate the aspect ratio to distinguish between open and closed hand
            x, y, w, h = cv2.boundingRect(hull)
            aspect_ratio = float(w) / h

            # Determine gesture based on aspect ratio
            if aspect_ratio < 0.8:
                gesture = "Closed Hand"
            else:
                gesture = "Open Hand"

            # Draw the hand contour and display the gesture
            cv2.drawContours(frame, [hull], -1, (0, 255, 0), 2)
            cv2.putText(frame, gesture, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

        # Display the frame
        cv2.imshow("Hand Gesture Recognition", frame)

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

    # Release the camera and close all windows
    cap.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()
