% dip05_0.m          gr12oct16  16oct23
% a few basic Matlab operations
clear all;
return

%%       %-------------- input image formats
% imformats;   pause;          
% help imread;    pause;

f = imread('.\img\lena.tif');
[m,n] = size(f)
whos f,  min(f(:)),   max(f(:)),  pause;

figure(1);  imshow(f);   %----- display an image
impixelinfo;
figure(2);  imshow(f, []);      % shifts min(f) to black, max(f) to white!
impixelinfo; 
return;

%%        %------------------ conversion
f1 = double(f);   min(f1(:)),   max(f1(:))   
f2 = im2double(f);   min(f2(:)),   max(f2(:))    %  beware: different output ranges!
figure(1);  imshow(f1);                 %  white output: out of range
figure(2);  imshow(f2);


%%           %------------------ save an image in JPEG
for q = 100:-10:10,
  imwrite(f,'qwqw.jpg','quality',q);      % quality range: 0-100
  K = imfinfo('qwqw.jpg');
  image_bytes = K.Width * K.Height * K.BitDepth / 8
  if q==100, K, image_bytes, end
  compression_ratio = image_bytes / K.FileSize
  figure(1), imshow(f); 
  g = imread('qwqw.jpg');
  figure(2), imshow(g);
  mse = mean( (double(f(:))-double(g(:))).^2 )
  PSNR = 10 * log10( 255^2 / mse )
  pause()
end

%%       % print, setting the resolution - useful for plots                             
% print -f2 -dtiff -r100 qwqw    
% help print;

%%       %------------------ basic manipulations
clf;
fa = f(1:2:end,1:2:end);  imshow(fa);   pause;     % subsample
fa = f(100:400,200:400);  imshow(fa);   pause;     % crop
fa = f(end:-1:1, :);  imshow(fa);   pause;         % upend		
plot(f(300,1:end));                                % plot row

%%      % ---------------  aliasing effect in a binary image
x = [0:200];
for a=0:.01:1
    y = a * x;
    plot(x,y,'k-'); hold on;
    end;
 hold off;

%%  --------------------- dithering
%%%%%%% 1-D example
y = [zeros(1,30), [0:.01:1], ones(1,29)];
yb = round(y);
yn = y+randn(size(y))*.2;
yn(yn<0) = 0;  yn(yn>1) = 1;
ynb = round(yn);
subplot(411); stem(y);
subplot(412); stem(yb);
subplot(413); stem(yn);
subplot(414); stem(ynb);

%% 2-D dithering
clf
A = ones(256,1)*[0:255];
% A = imread('.\img\lena.tif'); A = double(A);
A = ( A-min(A(:)) ) ./ ( max(A(:))-min(A(:)) ); % stretch and scale to [0, 1]

lev = graythresh(A) % Otsu

Ab = A;
Ab(A<=lev)=0;   Ab(A>lev)=1;

for sd = .01:.03:.3;
    
	An = A + randn(size(A))*sd;
	An(An<0) = 0;  An(An>1) = 1;

	Anb = An;
	Anb(An<=lev)=0;   Anb(An>lev)=1;

	imshow([A Ab; An Anb]);
	img_mean = [mean(A(:)), mean(An(:))]
	img_var = [std(A(:)), std(An(:))].^2  % increases by sd^2
	pause();
end

%% bit planes

 A = imread('.\img\lena.tif');
% A = imread('.\img\D18.gif');
% A = imread('peppers.png'); A = rgb2gray(A);
figure(1); imshow(A,[]); pause();
Ab = dec2bin(A);
Ab = reshape(Ab,size(A,1),size(A,2),8);
for k = 1:8
    Abit = uint8(Ab(:,:,k)); imshow(Abit,[]); pause()
end

 
 