#Contrast normalization:
#http://homepages.inf.ed.ac.uk/rbf/HIPR2/stretch.htm
#See also: http://en.wikipedia.org/wiki/Normalization_%28image_processing%29

#Basic idea: we want to set the brightest pixel to 1, and the darkest pixel to 0

def imshow_gs_noscaling(gs):
    '''Display the grayscale image gs while bypassing imshow()'s automatic 
    contrast normalization'''
    rgb_im = zeros(gs.shape+(3,))
    
    #Set the three channels to gs
    rgb_im[:,:,0] = gs
    rgb_im[:,:,1] = gs
    rgb_im[:,:,2] = gs
    imshow(rgb_im)


i = imread('bieber.jpg')/255.0 #color image whose range is   
                               #0..1 (at most)
                               
i_darker = .5*i # (a darker image of i                               

figure(1); imshow(i)
figure(2); imshow(i_darker)


gs = (i_darker[:, :, 0]+i_darker[:, :, 1]+i_darker[:, :, 2])/3
figure(3); imshow_gs_noscaling(gs)
#Contrast-normalize 
normalized = (gs-min(gs.flatten()))/(max(gs.flatten())-min(gs.flatten()))
figure(4); imshow_gs_noscaling(normalized)

'''
Contrast normalization makes the image always have the darkest pixel as 0 
and the brightest pixel as 1. If we contrast-normalize images before matching 
them, they will be contrast-invariant.

Note that for images whose darkest pixel is 0, normalizing by dividing by
the norm of the image |I| has a similar effect to normalizing by dividing by
max(I) -- in both cases, the matching becomes contrast-invariant.
'''
