import os
import cv2
from google.colab.patches import cv2_imshow  # Import for displaying images in Colab

# Function to detect and crop the license plate
def detect_and_crop_license_plate_v2(img):
    # Convert to grayscale
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    
    # Apply Gaussian blur to reduce noise and improve edge detection
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)

    # Apply adaptive thresholding for better edge detection
    thresh = cv2.adaptiveThreshold(blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                   cv2.THRESH_BINARY, 11, 2)
    
    # Perform edge detection
    edges = cv2.Canny(thresh, 50, 150)
    
    # Find contours in the edge-detected image
    contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    for contour in contours:
        # Approximate the contour
        epsilon = 0.02 * cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, epsilon, True)

        # Check if the approximated contour has 4 points (rectangle)
        if len(approx) == 4:
            # Compute the bounding box of the contour
            x, y, w, h = cv2.boundingRect(approx)
            
            # Filter by area to eliminate small contours
            area = cv2.contourArea(contour)
            if area < 500:  # Adjust this threshold based on your images
                continue
            
            # Draw the bounding box on the original image
            cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)  # Draw a green rectangle
            
            # Extract the region of interest (ROI)
            roi = img[y:y + h, x:x + w]
            
            # Check if the ROI has the characteristics of a license plate
            aspect_ratio = w / float(h)
            if 2 < aspect_ratio < 5:  # Typical aspect ratio of license plates
                return img, roi  # Return the image with bounding box and the cropped license plate
    
    return img, None  # Return the original image with no license plate detected

total = 0
c = 0

# Ruta donde se encuentran las imágenes
image_dir = '/content/drive/MyDrive/LICENSE_PLATES_RECOGITION_L&V/combined_folder_last(onlyspain)'

# Obtener una lista de todos los archivos en el directorio
image_files = [f for f in os.listdir(image_dir) if os.path.isfile(os.path.join(image_dir, f))]

# Procesar cada imagen en la carpeta
for image_file in image_files:
    # Construir la ruta completa de la imagen
    image_path = os.path.join(image_dir, image_file)

    # Cargar la imagen
    img = cv2.imread(image_path, cv2.IMREAD_COLOR)

    # Verificar si la imagen se cargó correctamente
    if img is None:
        print(f"Error al cargar la imagen {image_file}")
        continue

    # Llamar a la función para detectar y recortar la matrícula
    detected_image, license_plate = detect_and_crop_license_plate_v2(img)

    # Visualize the original image with bounding box and cropped license plate
    if license_plate is not None:
        print(f"Matrícula detectada en la imagen {image_file}")
        c += 1
        
        # Use the visualize function
        visualize([detected_image, license_plate], 
                  ["Original with Detected Plate", "Cropped License Plate"],
                  suptitle=f"Detection for {image_file}")
    else:
        print(f"No se detectó matrícula en la imagen {image_file}")

    total += 1

# Imprimir el total de imágenes procesadas
accuracy = c / total if total > 0 else 0
print(f"TOTAL IMAGES: {total}")
print(f"DETECTED LICENSE PLATES: {c}")
print(f"ACCURACY: {accuracy:.2f}")

THE DETECTION IS AWFUL. PLEASE FIX IT