Digital Image Processing
(Spring 2013)


Tutorial 

    1create a row vector
v = [1 3 5 7 9];
or
v = [1:2:9];

    2. create a column vector
v = [1 3 5 7 9]';

    3. create a matrix of size m*n
A = zeros(m, n);

    4. access to the element of A in row r and column c
x = A(r, c);
A(r, c) = 125;

    5. access  to a submatrix of matrix A, with row from r1 to r2 and column from c1 to c2 
B = A(r1:r2, c1:c2);
          A(r1:r2, c1:c2) = B; (B needs to be a (r2-r1+1)*(c2-c1+1) matrix)

    6. for loops
for i = 1:10
               A(i, i) = 0;
end

    7. while loops    
          i = 1;
while ( i <= 10 )
A(i, i) = 0;
i = i + 1;
end

    8. if statement   
if (x < 10)
y = 1;
elseif (x < 20)
y = 2;
else
y = 3;
end

    9. switch statement   
switch(x)
case 1
    y=1;
case 2
    y=2;
case 3
    y=3; 
end

    10. read and show an image   
I = imread('lenna.jpg');
imshow(I);
(if it is a gray image, I is a height*width matrix; if it is a color image, I is a  height*width*3 image)

    11. read a color image and convert it to a gray image  
I = imread('lenna.jpg');
[height, width, channel] = size(I);
double_I = double(I); % important, since default type of each pixel is a uint8 (one Byte), the operations on these pixel maybe cause overflow

gray_I = zeros(height,  width);
for i=1:height
    for j=1:width
           gray_I(i,j) = ( double_I(i,j,1)double_I(i,j,2)double_I(i,j,3)) / 3; % (R+G+B) / 3
    end
end

% show the orignal image and the processed image in the same figure
subplot(1,2,1); 
imshow(I);
subplot(1,2,2);
imshow(gray_I, []); % for uint8 (like I), the value should be in the range of [0,255]; while for double (like gray_I), the value should be in the range of [0,1], so here we add an extra parameter [] to let imshow normalize gray_I for us