# Import necessary libraries
import cv2
import numpy as np
import pygame
import time

# Function to calculate bubble ratio
def calculate_bubble_ratio(image, threshold=128):
    _, binary_image = cv2.threshold(image, threshold, 255, cv2.THRESH_BINARY)
    bubble_pixels = np.sum(binary_image == 255)
    total_pixels = image.size
    bubble_ratio = bubble_pixels / total_pixels
    return bubble_ratio

# Audio parameters
music_file = './LatinBgm2.mp3'  # Update with the path to your music file
freq = 16000
bitsize = -16
channels = 1
buffer = 2048

# Connect to USB camera
cap = cv2.VideoCapture(0)

# NAME_1 for the number of times the bubble ratio is less than 35%
NAME_1 = 0

# Real-time image capture, bubble ratio calculation, and display
while True:
    time.sleep(1)  # Wait for 3 seconds
    ret, frame = cap.read()
    if not ret:
        print("영상 데이터 감지 안됨!")
        break

    # Convert the frame to grayscale
    grayscale_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Calculate the bubble ratio
    bubble_ratio = calculate_bubble_ratio(grayscale_frame)

    # If the bubble ratio is less than 35%, increment the NAME_1
    if bubble_ratio < 0.40:
        NAME_1 += 1

    # If the NAME_1 reaches 10, play the sound and break the loop
    if NAME_1 >= 10:
        pygame.mixer.init(freq, bitsize, channels, buffer)
        pygame.mixer.music.load(music_file)
        pygame.mixer.music.play()
        clock = pygame.time.Clock()
        while pygame.mixer.music.get_busy():
            clock.tick(30)
        pygame.mixer.quit()
        print("Bubble ratio was less than 35% for 10 times. Stopping the program.")
        break

    # Print the bubble ratio and the NAME_1
    print("거품 비율:", bubble_ratio)
    print("카운터:", NAME_1)

    # Display the frame
    cv2.imshow('Frame', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

code check 