#!/usr/bin/python
# -*- coding: Latin1
#Ceci est un filtre de debouchage de photographies, aussi appelé masque de contraste, 
#il permet de rattrapper une photo trop contrasté, un contre jour, ...

#Écrit par Jérôme Kieffer, avec l'aide de la liste python@aful, en particulier A. Fayolles et F. Mantegazza
#avril 2006
#necessite numarray et PIL.
#Licence GPL v.2 

import Image,ImageChops,sys,os,ImageFile,numarray

if len(sys.argv)<2:
	raise "enter the filename of the image to enhance"
	sys.exit(0)

infile=sys.argv[1]
if not os.path.isfile(infile):
	raise "Input file does not exist"
if len(sys.argv)>2:
	if os.path.isfile(sys.argv[2]):
		raise "Output file exists already"
	else:
		outfile=sys.argv[2]
else:
	outfile=os.path.splitext(infile)[0]+"-filtered"+os.path.splitext(infile)[1]

i= Image.open(infile)
x,y=i.size
ImageFile.MAXBLOCK=x*y

img_array = numarray.fromstring(i.tostring(),type="UInt8").astype("UInt16") 
img_array.shape = (x, y, 3) 
red, green, blue = img_array[:,:,0], img_array[:,:,1],img_array[:,:,2]
desat_array = (numarray.minimum(numarray.minimum(red, green), blue) + numarray.maximum( numarray.maximum(red, green), blue))/2
inv_desat=255-desat_array

#F*(2P+F-2PF/W)/W all calculation made in 16 bit
#result_red=red*(2*inv_desat+red-2*inv_desat*red/255)/255
#result_green=green*(2*inv_desat+green-2*inv_desat*green/255)/255
#result_blue=blue*(2*inv_desat+blue-2*inv_desat*blue/255)/255
#image_r = Image.fromstring("L", (x, y), result_red.astype("UInt8").tostring())
#image_g = Image.fromstring("L", (x, y), result_green.astype("UInt8").tostring())
#image_b = Image.fromstring("L", (x, y), result_blue.astype("UInt8").tostring())
#Image.merge("RGB", (image_r,image_g,image_b)).save(outfile,quality=85,progressive=True,Optimize=True)


#this method is a bit faster but gives a result a bit worse

k=Image.fromstring("L",(x,y),inv_desat.astype("UInt8").tostring()).convert("RGB")
S=ImageChops.screen(i,k)
M=ImageChops.multiply(i,k)
F=ImageChops.add(ImageChops.multiply(i,S),ImageChops.multiply(ImageChops.invert(i),M))
F.save(outfile,quality=85,progressive=True,Optimize=True)
