%%%%%%
% Histograms
%%%%%%
im=readImage('lena.tif');
showimage(im);
H=hist(im(:),10);

figure;bar(H);   xlabel('gray level'); %histogram

NH=H/sum(H);  %normalized histogram
sum(NH)
figure;bar(NH);  xlabel('gray level');

A=cumsum(NH);  %Accumulated histogram
bar(A); xlabel('gray level');


%%%%%%
% contrast
%%%%%%

im_size = size(im);
fprintf('\n image min is %d \n',min(im(:)));  % min value of image
fprintf('\n image max is %d \n',max(im(:)));  % max value of image

new_im1=floor(im./2);   % decreases the image contrast

fprintf('\n new image min is %d \n',min(new_im1(:))); % min value of new image
fprintf('\n new image max is %d \n',max(new_im1(:))); % min value of new image

showImage(new_im1);
H=hist(new_im1(:), 1:256);
figure;bar(H);

av=sum(im(:)) / (im_size(1)*im_size(2))       %image average
new_av=sum(new_im1(:)) / (im_size(1)*im_size(2))   %new image average

new_im2=new_im1 - new_av + av;           %increasing the new image average
new_av=sum(new_im2(:)) / (im_size(1)*im_size(2))   %new image average
showImage(new_im2);
H=hist(new_im2(:), 1:256);
figure;bar(H);


%%%%%%
%autofocus
%%%%%%

im=readimage('lena.tif');
O=[1 1 1 1 1 ]/5;
bim=conv2(conv2(im,O,'same'),O','same');
bbim=conv2(conv2(bim,O,'same'),O','same');

showimage(im);
showimage(bim);
showimage(bbim);

h=hist(im(:),100);  figure; bar(h);
bh=hist(bim(:),100);  figure;  bar(bh);
bbh=hist(bbim(:),100);  figure;   bar(bbh);

std(im(:))   %std of the original image
std(bim(:))   %std of the blured image
std(bbim(:))  %std of the severe blured image


%%%%%%%%
%thresholding
%%%%%%%%

im=readimage('lighthouse.tif');
showimage (im);
H=hist(im(:),1:255);
figure; bar(H);
im1=im;
ind=find(im<210);
im1(ind)=0;
im(find(im>=210)) = 255;
showimage(im1);

% 1 liner: 
im1 = (im >=210).*255;
showimage(im1);

im2=zeros(size(im));
ind=find(im>130 & im<150);
im2(ind)=255;
showimage(im2);


%%%%%%%%%%
%Histogram Clipping
%%%%%%%%%%

im=readimage('darkimage.tif');
showImage(im);
H=hist(im(:),1:255);
figure; bar(H);

min(im(:)), max(im(:))
alpha=255/70; % tone map image to range [70 255]
beta=255-alpha*110;

% im1=alpha.*im + beta;

for i=41:110
   ind=find(im==i);
   im1(ind)=alpha*i+beta;
end;
for i=111:255
   ind=find(im==i);
   im1(ind)=255;
end;

showimage(im);
showimage(im1);

H=hist(im(:),1:255);
H1=hist(im1(:),1:255);
figure; bar(H); axis([0 256 0 4500]);
figure; bar(H1); axis([0 256 0 4500]);


%%%%%%%%%%%%
%histogram equalization
%%%%%%%%%%%%
im2=floor(histeq(im/255,255)*255);
showImage(im2);
H2=hist(im2(:),1:255);
figure; bar(H2); axis([0 256 0 4500]);



