import numpy as np
import cv2
import argparse
import matplotlib.pyplot as plt
import math
from convolution import convolution


def dnorm(x, mu, sd):
    return 1 / (np.sqrt(2 * np.pi) * sd) * np.e ** (-np.power((x - mu) / sd, 2) / 2)


def gaussian_kernel(size, sigma, verbose=False):
    kernel_1D = np.linspace(-(size // 2), size // 2, size)
    for i in range(size):
        kernel_1D[i] = dnorm(kernel_1D[i], 0, sigma)
    kernel_2D = np.outer(kernel_1D.T, kernel_1D.T)

    kernel_2D *= 1.0 / kernel_2D.max()

    if verbose:
        plt.imshow(kernel_2D, interpolation='none', cmap='gray')
        plt.title("Kernel ( {}X{} )".format(size, size))
        plt.show()

    return kernel_2D

# sigma=math.sqrt(kernel_size)


def gaussian_blur(image, kernel_size, sigma, verbose=False):
    kernel = gaussian_kernel(
        kernel_size, sigma, verbose=verbose)
    return convolution(image, kernel, average=True, verbose=verbose)


if __name__ == '__main__':
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--image", required=True,
                    default='B1.jpg', help="Path to the image")
    ap.add_argument("-s", "--sigma", required=True,
                    default=1, help="sigma value")

    args = vars(ap.parse_args())

    image = cv2.imread(args["image"])
    sigma = int(args["sigma"])
    kernel_size = (2*sigma + 1)

    gaussian_blur(image, kernel_size, sigma, verbose=True)
