import os
import sys
from numpy import *
import PIL
from PIL import Image

# Code  written by Geoff Daniell
# 25.6.26 restore6.py, new version with many changes

# GLOBAL CONSTANTS FIXING THE PROPERTIES OF THE RESTORED IMAGE

# Set debug value to get diagnostic information.
# debug=0: no information; debug=1: numerical values of restoration 
# parameters are printed; debug=2: intermediate images saved; debug=3: both.

debug = 0
#
# White point in LUV colour space, these values are extremely critical 
# for achieving a good white colour in the resored images
# White balance is in version6  automatically adjusted for each image
# Historically best
U0 = 0.2005; V0 = 0.4665

#############################################################################
# routines
#############################################################################

def binchop(f, x1, x2):
    f1=f(x1); f2=f(x2)
    while abs(x1 - x2) > 0.25:
        x_new=0.5*(x1 + x2)
        f_new=f(x_new)
        if f1*f_new <= 0: x2=x_new; f2=f_new
        else:             x1=x_new; f1=f_new
    return x1

#---------------------------------------------------------------------------

def simplex(x0, scale, F, eps, debug):
# Minimises function F in n dimensions using Nelder-Meade method starting
# from vector x0.  Parameter debug is not used.
# Exits if has found set of points with (|high| - |low|)/(|high| + |low|) < eps
# or number of function evaluations exceeds 5000.
# On exit returns coordinates of minimum and True or False, depending on 
# number of function evaluations used.
    ok = False
# Get number of dimensions.
    n = len(x0)
# Set up initial simplex.
    p = [x0[:] for i in range(0,n+1)]
    for i in range(0,n): p[i][i] += scale[i]
    psum = [sum([p[i][j] for i in range(0,n+1)]) for j in range(0,n)]
    nfunc = 0
# Get function value at vertices.
    y = [F(p[i]) for i in range(0,n+1)]
    while True:
# Get highest.
        hi = y.index(max(y))
# Set this value very low and get next highest.
        (y[hi], ysave) = (-1e10, y[hi])
        next_hi = y.index(max(y))
        y[hi] = ysave
# Get lowest.
        lo = y.index(min(y))
# Test for convergence.
        if 2.0*abs(y[hi] - y[lo])/(abs(y[hi]) + abs(y[lo])) < eps:
            ok = True
            break
# Exit if failed to converge.
        if nfunc > 5000: break
        if debug:
#            print(p)
            print(y[lo])
        nfunc += 2
        (ynew, p, y, psum) = trial(p, y, psum, n, F, hi, -1.0)
# If new point better try going further.
        if ynew <= y[lo]:
            (ynew, p, y, psum) = trial(p, y, psum, n, F, hi, 2.0)
# If the new point is worse than the next highest ...
        elif ynew >= y[next_hi]:
            ysave = y[hi]
            (ynew, p, y, psum) = trial(p, y, psum, n, F, hi, 0.5)
# If getting nowhere shrink the simplex.
            if ynew >= ysave:
# Loop over vertices keeping the lowest point unchanged.
                for i in range(0,n+1):
                      if i == lo: continue
                      pnew = [0.5*(p[i][j] + p[lo][j]) for j in range(0,n)]
                      p[i] = pnew
                      y[i] = F(pnew)
            nfunc += n
            psum = [sum([p[i][j] for i in range(0,n+1)]) for j in range(0,n)]
        else: nfunc -= 1
    return (p[lo], ok)

def trial(p, y, psum, n, F, hi, dist):
# Compute point pnew along line from p[hi] to centroid excluding p[h1].
    a = (1.0 - dist)/n
    b = a - dist
    pnew = [a*psum[j] - b*p[hi][j] for j in range(0,n)]
    ynew = F(pnew)
# If improvement accept and adjust psum.
    if ynew < y[hi]:
        y[hi] = ynew
        psum = [psum[j] + (pnew[j] - p[hi][j]) for j in range(0,n)]
        p[hi] = pnew
    return (ynew, p, y, psum)

#-------------------------------------------------------------------------------------}

def rgb2LUV(rgb):
# Converts rgb colour values to L* u* v*.
    (r, g, b) = rgb
    rr=expand[r]; gg=expand[g]; bb=expand[b]
    X = rr*0.4124 + gg*0.3576 + bb*0.1805
    Y = rr*0.2126 + gg*0.7152 + bb*0.0722
#    Z = rr*0.0193 + gg*0.1192 + bb*0.9505
    d = rr*3.6593 + gg*11.4432 + bb*4.115 + 1e-10
    U = 4.0*X/d
    V = 9.0*Y/d 
    Lstar = 24.9914*(Y**0.333333) - 16.0 if Y > 0.8856 else 9.03296*Y
    ustar = 13.0*Lstar*(U - U0)
    vstar = 13.0*Lstar*(V - V0)
    return (Lstar, ustar, vstar)

#-----------------------------------------------------------------------------

def Y(r,g,b):
# Computes the colourXYZ Y parameter which is used to order the colours found.
    Y = expand[r]*0.2126 + expand[g]*0.7152 + expand[b]*0.0722 + 1e-10
    return Y

#-------------------------------------------------------------------------------------}

def lightenhance(im, F, uvfac, offset):
# Adjusts the lightness of the final image using the F values and the 
# saturation using the uvfac param3ter and the white balance using offset.
# See notes for explanation.
# Note U and V are not Ustar and Vstar and these values are not calculated.

    (w, h) = im.size
# Decompress the image using the gamma value.
    RGB = im.point(xpand)
# Split the image into R, G, and B monochrome images.
    RGB = list(RGB.split())
# Put red, green and blue components into numpy arrays. From now on the 
# computation is done using numpy arrays.
    r = array(list(RGB[0].getdata()))
    g = array(list(RGB[1].getdata()))
    b = array(list(RGB[2].getdata()))
# Get the XYZ colour components of the image as whole arrays. Z is not used.
    X = r*0.4124 + g*0.3576 + b*0.1805
    Y = r*0.2126 + g*0.7152 + b*0.0722
    d = r*3.6593 + g*11.4432 + b*4.115 + 1e-10
    del r,g,b
# Convert these to L*, U* and V*.
    Lstar = where(Y > 0.8856, 24.9914*(Y**0.333333) - 16.0, 9.03296*Y)
    u = 4.0*X/d - U0 - offset[0]
    v = 9.0*Y/d - V0 - offset[1]
    del X,Y,d
# Scale the lightness L* using values in array
    Lstar = Lstar.astype(int)
    newLstar = F[Lstar]
# Convert scaled L* to Y parameter.
    newY = where(newLstar <= 8.0, newLstar*0.110705, \
                 6.40657e-5*(newLstar + 16.0)**3)
# Factor to change Lstar, newLstar = 0 only if old Lstar = 0 
    Lfactor = Lstar/(newLstar + 1e-6)

# scale u and v to keep U* and V8 the same
# Apply saturation adjustment to U and V.
    newU = uvfac[Lstar]*Lfactor*u + U0 + offset[0]
    newV = uvfac[Lstar]*Lfactor*v + V0 + offset[1]

# Convert scaled U and V to X,Y,Z.
    X = 2.25*newY*newU/newV
    Y = newY
    Z = 0.25*newY*(12.0 - 3.0*newU - 20.0*newV)/newV
    del newLstar, newY, newU, newV
# Convert to r,g,b.
    r =  X*3.2406 - Y*1.5372 - Z*0.4986
    g = -X*0.9689 + Y*1.8758 + Z*0.0415
    b =  X*0.0557 - Y*0.2040 + Z*1.0570
# clip values to between 0 and 255
    r = clip(r, 0, 255)
    g = clip(g, 0, 255)
    b = clip(b, 0, 255)
# convert to 8 bits to reassemble as image
    r=r.astype('uint8')
    g=g.astype('uint8')
    b=b.astype('uint8')
# Make new empty monochrome images.
    newr = Image.new("L", (w,h))
    newg = Image.new("L", (w,h))
    newb = Image.new("L", (w,h))
# Insert the pixels from the numpy arrays.
    newr.putdata(r)
    newg.putdata(g)
    newb.putdata(b)
# Merge the monochrome images into a RGB image.
    newim = Image.merge("RGB", (newr, newg, newb))
# Perform the gamma compression on the enhanced image.
    newim = newim.point(cmpress)
    return newim

#-------------------------------------------------------------------------------------}

def xpand(c):
# Function used in converting the compressed RGB values in the image to 
# actual intensity values.
    C = c/255.0
    if C > 0.04045: C = ((C + 0.055)/1.055)**2.4
    else: C = C/12.92
    return int(100.0*C + 0.5)

#-------------------------------------------------------------------------------------}

def cmpress(c):
# The reverse of xpand(c) above.
    C = c/100.0
    if C > 0.0031308: C = 1.055*(C**0.4166666) - 0.055
    else: C = 12.92*C
    return int(C*255.0 + 0.5)

#-------------------------------------------------------------------------------------}

def get_colours(im):
# Computes the list of distinct colours in the image and number of pixels.
# Colours with few pixels are omitted
    pixels = list(im.getdata())
    cols = []
# Allow space for 4096 separate colirs.
    N = 4096
    rgb = zeros(N, int)
    for C in pixels:
# Construct n using 4 most significant bits of r, g and b.
        (r, g, b) = C
        c = ((r << 4) & 0xf00) | (g & 0xf0) | (b >> 4)
# If this colour has not yet occurred flag that it has and add colour to list
        if not rgb[c]: cols.append((C, c))
        rgb[c] += 1

    colours, colbits = list(zip(*cols))
    numpxls = rgb[array(colbits)]

    N = im.width*im.height
    good_colours = numpxls > 0.01*N/len(colours)

    colours = (array(colours))[good_colours]
    numpxls = numpxls[good_colours]

# return the colours and pxl numbers as lists
    return (list(colours), list(numpxls))

#-------------------------------------------------------------------------------------}

def get_LUV(im):
# Decompress the image using the gamma value.
    RGB = im.point(xpand)
# Split the image into R, G, and B monochrome images.
    RGB = list(RGB.split())
# Put red, green and blue components into numpy arrays. From now on the 
# computation is done using numpy arrays.
    r = array(list(RGB[0].getdata()))
    g = array(list(RGB[1].getdata()))
    b = array(list(RGB[2].getdata()))
# Get the XYZ colour components of the image as whole arrays. Z is not used.
    X = r*0.4124 + g*0.3576 + b*0.1805
    Y = r*0.2126 + g*0.7152 + b*0.0722
    d = r*3.6593 + g*11.4432 + b*4.115 + 1e-10
    del r,g,b
# Convert these to L*, U* and V*.
    Lstar = where(Y > 0.8856, 24.9914*(Y**0.333333) - 16.0, 9.03296*Y)
    u = 4.0*X/d
    v = 9.0*Y/d
#    del X,Y,d
    return(Lstar, u, v)

#-------------------------------------------------------------------------------------}

def first_search(colours):
# Sort colours by lightness
    colours.sort(key=lambda C1: Y(C1[0],C1[1],C1[2]))
# Convert to separate colour maps for each channel 
    colmap = list(zip(*colours))
# Define colours of 'ideal' image.
    gammatarg = 1.0
    numcols = len(colours)
    C = array(list(range(numcols)))
    ideal = (255.0*C/numcols)**gammatarg

# Optimises lambda and sigma separately for each colour channel.
    output_params = []
    for CH in [R, G, B]:
# Convert colour values in channel CH to array for speed
        cols = array(colmap[CH])
# function to be minimised,.
# A lambda expression is used to get data into a function of parameters only
        func = lambda p: first_colour_measure(p, cols, ideal)
# Initial values of parameters and steps
        scale = [0.02, 0.02]; x0 = [1.0, 1.0]
        (params, ok) = simplex(x0, scale, func, 1e-4, False)
        if not (ok):
            print("The program  has failed to obtain a satisfactory \
                   restoration; the result shown may be poor.")
        output_params += params

    if debug & 1: 
        fit = output_params
        print("FIRST RESTORE")
        print('lambda parameters %6.3g%6.3g%6.3g' % (fit[0], fit[2], fit[4]))
        print('sigma parameters %6.3g%6.3g%6.3g' % (fit[1], fit[3], fit[5]))

    return output_params

#-------------------------------------------------------------------------------------}

def first_colour_measure(p, cols, ideal):
# Calculates measure of misfit between actual colours and ideal colours.
# This is to be minimised in the first stage of restoration.
# cols is array
    lamc, sigc = p
    trial_cols = 255.0*sigc*(cols/255.0)**lamc
    return sum((trial_cols - ideal)**2)

#-------------------------------------------------------------------------------------}

def second_search(colours):
# A lambda expression is used to get data into a function of parameters only
    func = lambda p: second_colour_measure(p, colours)
# Initial values of lambda and sigma parameters for second restoration.
    scale = [0.02, 0.02, 0.02, 0.02, 0.02, 0.02]
    x0 = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
    fit = simplex(x0, scale, func, 1e-4, False)[0]
    
    if debug & 1:
        print("SECOND RESTORE")
        print('lambda parameters %6.3g%6.3g%6.3g' % (fit[0], fit[2], fit[4]))
        print('sigma parameters %6.3g%6.3g%6.3g' % (fit[1], fit[3], fit[5]))

    return fit

#-------------------------------------------------------------------------------------}

def second_colour_measure(p, cols):
# Calculates the quatity to be minimised in the final restored image.
# cols is list of tuples.
# L0 sets the lightness scale and was formerly set globally.
    L0 = 50.0
    lam = p[0:6:2]; sig = p[1:6:2]

# Convert to separate colour maps for each channel 
    colmap = list(zip(*cols))
# Apply the lambda and sigma correction to each colour
    for C in [R, G, B]:
        map(lambda c: int(255*sig[C]*(c/255.0)**lam[C]), colmap[C])
# Make sure that no r,g or b values are outside permitted range.
        colmap[C] = clip(colmap[C], 0, 255)

# Convert back to list of colour tuples.
    cols = list(zip(colmap[R], colmap[G], colmap[B]))
# Convert the rgb values to L*, U* and V* and append to lists.
    LUVcols = map(rgb2LUV, cols)
# Separate into lists of Lstar, Ustar and Vstar
    (Lstar, Ustar, Vstar) = list(zip(*LUVcols))
# Convert the lists to numpy arrays for fast processing.
    L = array(Lstar); U = array(Ustar); V = array(Vstar)
# Set nLUV to the length of the lists.
    nLUV = float(len(U))
# Compute the average L and its offset from specified value L0.
    Lbar = sum(L)/nLUV
    Loff = Lbar - L0
# Compute parameters for function to me minimised, see notes.
    Ldash = L/L0 - 1.0
    UL0 = sum(U)/nLUV;
    UL1 = sum(U*Ldash)/nLUV
    UL2 = sum(U*Ldash*Ldash)/nLUV

    u0 = UL0; u1 = 3.0*UL1; u2 = 2.5*(3.0*UL2 - UL0)

    VL0 = sum(V)/nLUV
    VL1 = sum(V*Ldash)/nLUV
    VL2 = sum(V*Ldash*Ldash)/nLUV

    v0 = VL0; v1 = 3.0*VL1; v2 = 2.5*(3.0*VL2 - VL0)

    minimum=[Loff**2, u0**2, 0.3333333*u1**2, 0.2*u2**2, \
                      v0**2, 0.3333333*v1**2, 0.2*v2**2]
    return sum(minimum)

#-------------------------------------------------------------------------------------}

def combine_params(fit1, fit2):
# Given two sets of lambda and sigma parameters, compute a single set that
# will produce the same outcome.
    lam1 = fit1[0:3]; sig1 = fit1[3:6]
    lam2 = fit2[0:3]; sig2 = fit2[3:6]
    lam = [0,0,0]; sig = [0,0,0]
    for C in [R,G,B]:
        sig[C] = sig2[C]*sig1[C]**lam2[C]
        lam[C] = lam1[C]*lam2[C]
    return [lam[0], lam[1], lam[2], sig[0], sig[1], sig[2]]

#-------------------------------------------------------------------------------------}

def restore_an_image(image, fit):
# Restores image using lambda and sigma values in fit..
    Lambda = [fit[0], fit[2], fit[4]]
    Sigma  = [fit[1], fit[3], fit[5]]
# Split the RGB image into three monchrome images.
    RGB=list(image.split())
# Apply restoration operation to each channel.
    for C in [R,G,B]:
        RGB[C] = RGB[C].point(lambda I: \
            int(255*Sigma[C]*(I/255.0)**Lambda[C]+0.5))
# Recombine the monochrome images.
    return Image.merge("RGB", (RGB[0], RGB[1], RGB[2]))

###############################################################################

def restore(im, photoname):
# Restores main image, photoname is simply used for constructing directory names.
# Create a small image for speed.
    (width, height) = im.size
    small_image = im.resize((int(width/8), int(height/8)), resample=PIL.Image.NEAREST)

    if debug & 2:
        newfilename=os.path.join(directory, "restored", "before" + photoname)
        small_image.save(newfilename, icc_profile=im.info.get('icc_profile'))

# Get colourmap of small image. the underscore discards the numbers of pixels
    colours, _  = get_colours(small_image)

# First restoration of small image.
    first_fit = first_search(colours)

# Restore the small image.
    first_restored_small = restore_an_image(small_image, first_fit)

# Save the intermediate result.
    if debug & 2:
        newfilename=os.path.join(directory, "restored", "first_restored" + photoname)
        first_restored_small.save(newfilename, icc_profile=im.info.get('icc_profile'))

# Get the colourmap of the restored image.
    colours, _ = get_colours(first_restored_small)

# second restoration
    second_fit = second_search(colours)

# Combine the parameters of the two restorations.
    combined_fit = combine_params(first_fit, second_fit)

    if debug & 1:
        fit = combined_fit
        print("COMBINED FIT")
        print('lambda parameters %6.3g%6.3g%6.3g' % (fit[0], fit[2], fit[4]))
        print('sigma parameters %6.3g%6.3g%6.3g' % (fit[1], fit[3], fit[5]))

# Restore the small image with the combined parameters.
    combined_restored_small = restore_an_image(small_image, combined_fit)

# Restore main image
    restored_image=restore_an_image(im, combined_fit)

# Save the intermediate result. 
    if debug & 2:
        newfilename = os.path.join(directory, "restored", "combined_restored" + photoname)
        combined_restored_small.save(newfilename, icc_profile=im.info.get('icc_profile'))

# Save the restored image
#    newfilename = os.path.join(directory, "restored", "restored_image" + photoname)
#    restored_image.save(newfilename, icc_profile=im.info.get('icc_profile'))

##############################################################################
# Additional processing
###############################################################################

# Get properies of restored image
    colours, numpix = get_colours(combined_restored_small)
    LUVcols = list(map(rgb2LUV, colours))

# Convert to LUV arrays
    (Lstar, Ustar, Vstar) = list(zip(*LUVcols))
# Convert the lists to numpy arrays for fast processing.
    Lstar = array(Lstar); Ustar = array(Ustar); Vstar = array(Vstar)
    N = len(Lstar)  

# needed for white balance
    u = Ustar/(13.0*Lstar)
    v = Vstar/(13.0*Lstar)

#----------------------------------------------------------------------------

# default lightness correction
    F0 = array(list(range(0, 101))); F0[0] = 1.0

# lightness distribution before
    nL = [0 for l in range(0,101)]
    for l in Lstar: nL[int(l)] += 1

# set up array F1
    F1 = array(list(range(0, 101))); F1[0] = 1.0

# set up lut for enlightening colours
    FL = 0.0
    B1 = 2; B2 = 2
    A = 1.0e6/6 + (B2 +  B1)*1.0e4/2 + B1*B2*1.0e2

    f = lambda z: FL - \
        (-z*z*z/3.0 + (100 + B2 - B1)*0.5*z*z + B1*(100 + B2)*z)/A
    for l in range(0,101):
        FL += nL[l]/N
        F1[l] =  binchop(f, 0.0, 100.0)

# Save Lstar for sdaturation calculation, avoids Lstar = 0
    old_Lstar = Lstar
    F1 = F1.astype(int)

# improve the lightness distribution
    Lstar = Lstar.astype(int)
    Lstar = F1[Lstar]
    Lstar = clip(Lstar, 0, 100)

#---------------------------------------------------------------------------

# Default saturation correction
    uvfac0 = ones(101, float)
    uvfac1 = ones(101, float)

    S = (sqrt(Ustar**2 + Vstar**2)/old_Lstar)

    L2S2 = sum(Lstar*Lstar*S*S); LS2 = sum(Lstar*S*S); LS = sum(Lstar*S)
    S2 = sum(S*S); S1 = sum(S)
    D = L2S2* S2 - LS2*LS2

    Sbar = 0.5
    alpha = Sbar*(LS*S2 - S1*LS2)/D
    beta = Sbar*(S1*L2S2 - LS*LS2)/D
    
    newS = zeros(101, float)
    for i in range(0, 101): uvfac1[i] = (alpha*i + beta)

#---------------------------------------------------------------------------
# white balance

# use only Ustar**2 + Vstar**2 < ~200 and Lstar > ~80
    pale = (Ustar**2 + Vstar**2 < 200) & (Lstar > 80)

    numpix = array(numpix)
# compute ok in case there are no grey pixels
    ok = len(nonzero(pale)[0])
    n =  sum(numpix[pale])*len(nonzero(pale))    

    offset = (0.0, 0.0)
    if ok:
        u_off = sum(u[pale]*numpix[pale])/n  
        v_off = sum(v[pale]*numpix[pale])/n  
        offset = (u_off, v_off)

# enhance the image
    enhancedlight_image = lightenhance(restored_image, F1, uvfac1, offset)

# save the enlightened image
    newfilename=os.path.join(directory, "restored",  "restored_image_" + photoname)
    enhancedlight_image.save(newfilename, icc_profile=im.info.get('icc_profile'))

#############################################################################
#############################################################################

#default parameters
directory = os.getcwd()
# save current directory
savedir = directory

# The original parsing of arguments has been left unchanged although not used
#gammatarg=1.0
#sat_choice=1
#parse parameters
#for param in sys.argv:
#    Dir=param.find("dir=")
#    if Dir>=0: directory=param[Dir+4:]
#    gam=param.find("Light-Dark=")
#    if gam>=0: gammatarg=float(param[gam+11:])
#    sat=param.find("saturate=")
#    if sat>=0: sat_choice=eval(param[sat+9:])

R = 0; G = 1; B = 2

# set parameters here for colour balance, these seem about optimum
#grey=50.0; u_off=2.0;  v_off=2.0

# Make look up table for conversion to LUV, needs to be bigger than 256.
expand = [0.0 for c in range(0,360)]
for c in range(0,256):
    C = c/255.0
    if C > 0.04045: C = ((C + 0.055)/1.055)**2.4
    else: C = C/12.92
    expand[c] = 100.0*C

# Make a list of files to process.
os.chdir(directory)
filelist = os.listdir(directory)
jpegs = []; JPEGS = []; tiffs = []; TIFFS = []
for File in filelist:
    if File.find(".jpg") > 0:  jpegs.append(File)
    if File.find(".JPG") > 0:  JPEGS.append(File)
    if File.find(".tiff") > 0: tiffs.append(File)
    if File.find(".TIFF") > 0: TIFFS.append(File)

# In windows the file searching is NOT case sensitive.
if JPEGS != jpegs: jpegs += JPEGS
if TIFFS != tiffs: tiffs += TIFFS

for photo in jpegs + tiffs:
# Strip off directory name and .jpg to get file name.
    photoname = os.path.split(photo)[1]
    print("")
    print(photoname)
# Open photo
    im = Image.open(photoname)
# Restore the image.
    restored_image = restore(im, photoname)
# Ignore the result if restoration failed..
    if restored_image == None: continue
# Save file to subdirectory 'restored'..
#    newfilename = os.path.join(directory, "restored", photoname)
#    restored_image.save(newfilename, icc_profile=im.info.get('icc_profile'))

# Return to saved directory.
os.chdir(savedir)

