import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from collections import Counter

image_path = os.path.join(os.getcwd(), '******.jpg')

image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), cv2.IMREAD_GRAYSCALE)

if image is None:
    print("Error: Image not loaded. Please check the file path.")
else:
    color_image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

    blurred_image = cv2.GaussianBlur(image, (5, 5), 0)

    edges = cv2.Canny(blurred_image, 2, 100)

    kernel = np.ones((3,3), np.uint8)
    edges = cv2.dilate(edges, kernel, iterations=2)
    edges = cv2.erode(edges, kernel, iterations=1)

    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    print(f"Number of contours found: {len(contours)}")

    pixel_threshold = *******


    contour_colors = {
        "purple": (153, 0, 153),   
        "blue": (255, 113, 25),    
        "green": (107, 176, 0),   
        "yellow": (0, 231, 242),   
        "orange": (0, 170, 246),   
        "red": (0, 75, 255)        
    }

    color_counter = Counter()

    for contour in contours:
        area = cv2.contourArea(contour)
        quotient = area / pixel_threshold
        if quotient < 0.1:
            color = contour_colors["purple"]
        elif 0.1 <= quotient < 0.3:
            color = contour_colors["blue"]
        elif 0.3 <= quotient < 0.5:
            color = contour_colors["green"]
        elif 0.5 <= quotient < 0.7:
            color = contour_colors["yellow"]
        elif 0.7 <= quotient < 0.9:
            color = contour_colors["orange"]
        elif quotient >= 0.9:
            color = contour_colors["red"]
        else:
            continue  

        color_counter[color] += 1

        cv2.drawContours(color_image, [contour], -1, color, thickness=cv2.FILLED)

    print(f"Number of contours after filtering: {sum(color_counter.values())}")

    output_image_path = os.path.join(os.getcwd(), '******.jpeg')

    color_image_rgb = cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB)

    plt.figure(figsize=(10, 10))
    plt.imshow(color_image_rgb)
    plt.axis('off')
    plt.savefig(output_image_path, dpi=1000, bbox_inches='tight', pad_inches=0)
    plt.close()

    print(f"High DPI image saved at: {output_image_path}")

    plt.bar([str(c) for c in color_counter.keys()], color_counter.values(), color=[np.array(c)/255 for c in color_counter.keys()])
    plt.xlabel('Color')
    plt.ylabel('Count')
    plt.title('Distribution of Contours by Color')
    plt.show()
