%% IMAGES_BASICS
% few elements from Matlab programming 
% related to basic image processing
%
% *Course homepage:* http://cmp.felk.cvut.cz/cmp/courses/Y33ROV/

%% clear the workspace ...
% ... and update Matlab caches
clear all
rehash

%% image representation in Matlab
% 2- or 3-dimensional array
imrgb = imread('http://cmp.felk.cvut.cz/cmp/courses/Y33ROV/Y33ROV_ZS20082009/imgs/avbot2www.jpg');
imgray = rgb2gray(imrgb);
whos('imrgb','imgray')

%% Display images
figure(1); clf
imshow(imrgb);
title('RGB image')
axis on
figure(2); clf
imshow(imgray)
title('Gray scale image')
axis on

%% Data types pitfalls
% For some image arithmetics it will be needed to change the default
% |integer| data type into |double|. 
% 
% Matlab *DOES* recognize data types, even in functions for displaying
% and saving. Be aware of it! This caused many confusions in past.
%
% for type |uint8| Matlab expects values 
% 
% $$0 \leq x \leq 255$$
% 
% and for type |double| it expects
%
% $$0 \leq x \leq 1$$
%
imrgb_float = double(imrgb);
imgray_float = double(imgray);
figure(3); clf
subplot(2,2,1); subimage(imrgb);
title('RGB image with integers');
subplot(2,2,2); subimage(imrgb_float);
title('RGB image with floats');
subplot(2,2,3); subimage(imgray);
title('gray image with integers');
subplot(2,2,4); subimage(imgray_float);
title('gray image with floats');

%% Saving images and figures
% 
% * functions: |imwrite| and |print|
% * lossless compressed png format is better for saving graphs, see: http://www.libpng.org/pub/png/
%

% saving bitmaps
imwrite(imgray,'examples_of_saving.png');

% saving (printing) graphics (figures)
% activate the proper figure
figure(3);
% save as png bitmap
print -dpng figure3.png
% or as function
% save as color encapsulated postscript
% eps file may get very big. However, it is very useful for publishing.
print('-depsc','figure3.eps')

%% Indexing of gray images
% is pretty straightforward

% Subimage by specifing coordinates
imgray_sub = imgray(1:200,51:250);
% find all pixels where the intensity exceeds threshold
threshold = 128;
idx = imgray<threshold;
% indexing by a logical conditions
imgray_changed = imgray;
imgray_changed(idx) = 0;

figure(4); clf; imshow(imgray_sub); axis on;
figure(5); clf; imshow(imgray_changed); axis on;

