% Ex 8: Histgram equalization

img = hdrread( 'slate_mines.hdr' );
%img = hdrread( 'memorial.hdr' );

%%

img_in = img/100;
L_in = get_luminance( img_in );

l = log10(L_in); % work in log space


[H, x] = hist( l(:), 256 );
H = H / sum(H(:)) * 2;  % normalized image hostogram, scaled to 0-2

dx = x(2)-x(1);

% Redistribute bins if the slope greater than 1
if( 1 ) 
for kk=1:100

exceed = H > dx;
E = sum(H(exceed));
if( E < 0.001 )
    break;
end
H(exceed) = dx;
H(~exceed) = H(~exceed) + (E-dx*nnz(exceed))/nnz(~exceed);

end
end

cH = cumsum( H );   % cummulative mass function (also contrast equalization)

% tone-mapping function
l_out = interp1( x, cH, clamp( l, x(1), x(end) ) );

L_out = 10.^( l_out );

s = 0.75948;

% add colors
img_out = (img_in ./ repmat( L_in, [1 1 3] )).^s .* repmat( L_out, [1 1 3] );

subplot( 1, 3, 1:2 );

imshow( cat( 2, lin2srgb( img_in ), gog_iv_display_model( img_out, 2.2, 100, 1, 0, 0 ) ) );



subplot( 1, 3, 3 );

%l = linspace( x(1), x(end) );
%V = interp1( x, cH, l );

plot( x, cH );
hold on
plot( [x(1) x(end)], [0 x(end)-x(1)], '--k' );
hold off
xlabel( 'log Input luminance' );
ylabel( 'log Displayed luminance' );
ylim( [-0.2 2] );



