from scipy.signal import convolve2d
from numpy import sqrt, exp,mgrid,math,asarray



def smooth_image(image_file,sigma):

    grid = gaussian_grid(sigma)
    
    if image_file.mode == 'RGB':
        image_file.load()
        r, g, b = image_file.split()
        r = filter_image(r, grid)
        g = filter_image(g, grid)
        b = filter_image(b, grid)
        smooth = (r, g, b)
    
    else:
        smooth=filter_image(image_file, grid)  
    
    return smooth 


def gray(image, x, y, x2, y2):
    gray = (image[x, y] - image[x2, y2])**2
    return sqrt(gray)
    
def rgb(image, x, y, x2, y2):
    r = (image[0][x, y] - image[0][x2, y2])**2
    g = (image[1][x, y] - image[1][x2, y2])**2
    b = (image[2][x, y] - image[2][x2, y2])**2
    w=(sqrt(r),sqrt(g),sqrt(b),sqrt(r+b+g))
    return w


def gaussian_grid(sigma, alpha=4):
    length = int(math.ceil(sigma * alpha)) + 1
    m = length / 2
    n = m + 1
    x, y = mgrid[-m:n,-m:n]
    g = exp(m**2) * exp(-0.5 * (x**2 + y**2))
    return g / g.sum()


def threshold_f(size, K):
    return (K / size)


def filter_image(image, mask):
    layer = asarray(image).astype('float')
    layer = convolve2d(layer, mask, mode='same')
    return layer

