import numpy as np
import matplotlib.pyplot as plt
import imageio.v3 as iio

def norm_minmax(img, C, m):
    img = (img - img.min())/(img.max() - img.min())
    img *= C
    img -= m
    return img

def histogram(img, L):

    accum = np.zeros((L,))
    h, w = img.shape
    for i in range(h):
        for j in range(w):
            accum[img[i, j]] += 1

    accum = np.zeros((L,))
    for h in range(L):
        accum[h] = np.sum(img == h)

    return accum

def acc_histograma(h, L):

    accum_h = np.zeros((L,))
    accum_h[0] = h[0]
    for i in range(1, L):
        accum_h[i] = accum_h[i-1] + h[i]

    return accum_h

def equalisation(img, acc_h, L):

    new_img = np.zeros_like(img)

    h, w = img.shape
    for i in range(h):
        for j in range(w):
            resolution = float(h*w)
            new_img[i, j] = (L-1.0)*(acc_h[img[i, j]]/resolution)

    return new_img

def do_everything(img):
    img = 0.25*img[..., 0] + 0.5*img[..., 1] + 0.25*img[..., 2]
    img = img.astype(np.uint8)
    h = histogram(img, 256)

    plt.figure(figsize=(6, 6))
    plt.bar(range(256), h)
    plt.show()

    h_acc = acc_histograma(h, 256)
    img_eq = equalisation(img, h_acc, 256)

    h = histogram(img_eq, 256)
    plt.figure(figsize=(6, 6))
    plt.bar(range(256), h)
    plt.show()

    plt.imshow(img, cmap='grey')
    plt.show()
    plt.imshow(img_eq, cmap='grey')
    plt.show()

def main():
    
    
    # dummy = np.random.randint(0, 8, (10, 10))
    # print(dummy)

    # h = histogram(dummy, 8)

    # plt.figure(figsize=(6, 6))
    # plt.bar(range(8), h)
    # plt.show()

    # h_acc = acc_histograma(h, 8)
    # dummy = equalisation(dummy, h_acc, 8)
    # plt.figure(figsize=(6, 6))
    # plt.bar(range(8), h_acc)
    # plt.show()

    # h = histogram(dummy, 8)
    # plt.figure(figsize=(6, 6))
    # plt.bar(range(8), h)
    # plt.show()

    # img = iio.imread('IMG_6491 Small.jpeg')
    # do_everything(img)

    # img = iio.imread('IMG_6490 Small.jpeg')
    # do_everything(img)

    # img = iio.imread('IMG_6489 Small.jpeg')
    # do_everything(img)

    img = iio.imread('IMG_6486 Small.jpeg')
    do_everything(img)

    img = iio.imread('IMG_6488 Small.jpeg')
    do_everything(img)



if __name__ == "__main__":
    main()
