import numpy as np
from PIL import Image, ImageDraw
import math

# Lecture de l'image et conversion en niveaux de gris
img_pil = Image.open('in/circle3_countours.png').convert('L')
img_np = np.array(img_pil)

# Calcul de la taille de la diagonale de l'image
width, height = img_np.shape
taille_diagonale = np.ceil(np.sqrt(width * width + height * height)).astype(int)


# Initialisation de l'accumulateur
accumulator = np.zeros((width, height), dtype=np.uint64)

# Pour chaque pixel de contour
ys, xs = np.nonzero(img_np)
for y, x in zip(ys, xs):
    # Pour chaque valeur de phi
    for angle in np.linspace(-math.pi/2, math.pi/2, 360 , endpoint=False):

        x_center = x + int(30 * np.cos(angle))
        y_center = y + int(30 * np.sin(angle))

        if x_center < width and y_center < height:
            accumulator[x_center, y_center] += 1

# Visualisation de l'accumulateur, normalisé entre 0 et 255
accumulator = (accumulator - accumulator.min()) / (accumulator.max() - accumulator.min()) * 255
Image.fromarray(accumulator.astype(np.uint8)).save('out/circle3_accumulateur.png')

# Analyse de l'accumulateur pour décider des lignes détectées
nombre_cercles_detectés = 9
detections = np.argsort(accumulator, axis=None)[-nombre_cercles_detectés:] # Ordre croissant

# Visualisation des lignes détectées
img_pil = img_pil.convert('RGB')
img_pil_draw = ImageDraw.Draw(img_pil)

for i in range(nombre_cercles_detectés):
    x, y = np.unravel_index(detections[i], accumulator.shape)

    leftUpPoint = (x - 30, y - 30)
    rightDownPoint = (x + 30, y + 30)
    # Dessin de la ligne
    img_pil_draw.ellipse([leftUpPoint, rightDownPoint], fill=None, outline='red', width=3)

# Sauvegarde de l'image
img_pil.save('out/circle3_cercles.png')




