Lecture Digital Image Processing 2017: Getting Started
Lecture Digital Image Processing 2017: Getting Started
Lecture Digital Image Processing 2017: Getting Started
These exercises are designed to get the first experiences with MATLAB. MATLAB is a
programing environment for numerical calculations and algorithms and has been shown
to be useful for quick prototyping.
Getting Started
After starting MATLAB a command line window with three subwindows will appear.
The large subwindow on the right hand side is the command line window where you can
type commands.
You can use MATLAB like a pocket calculator. Type and check the result:
>> 5 ∗ 7
>> 2 + 3/2
You can also assign the result to a variable1 :
>> a = 4∧ 2
>> b = a + 2
You can suppress the output by entering a semicolon behind the command:
>> c = b/2;
MATLAB provides all arithmetical and logical operators2 you expect to find on a pocket
calculator:
1
You can get a help page for all MATLAB commands typing help <Commandname>, e.g.:
>> help sin
displays a help page that explains how to use the sine function in MATLAB.
Exercise:
1. Calculate the following terms with MATLAB:
4·7−8
=
34 − 1
esin 3.2 =
37
5 + log 2.9·1.7
=
9
+, − plus, minus A + B, A − B
∗ scaling and matrix multiplication s ∗ A, A ∗ B
0 transposition A0
.∗ element-wise multiplication A. ∗ B
.ˆ element-wise power A.ˆ2 or 2.ˆA
inv inverse of a square matrix inv(A)
max, min maximum or minimum element of a vector max(A), min(A)
sum sum of all elements of a vector sum(A)
mean the mean of a vector mean(A)
median the median of a vector median(A)
std standard deviation of the elements of a vector std(A)
eig Eigenvalues and Eigenvectors of square matrices [V, D] = eig(A)
Moreover, most functions like sin, exp, etc. can also be used for vectors. Then, the
functions are applied to each element of the vector individually. E.g.
>> exp([2 3])
2
yields the same result as
>> [exp(2) exp(3)]
Exercise:
2. Do the following calculations with MATLAB:
3 5 1
A= 2 0 1
−1 1 0
b = (−2, 1, −4)T
c = A−1 b
c=
You can evaluate individual elements of a matrix with the index operator (parenthesis):
>> A(2, 3)
yields the matrix element in the second row and third column of matrix A
>> b(3)
yields the third element of vector b
>> A(2, :)
yields the second row of matrix A
>> A(:, 3)
yields the third column of matrix A
The function length yields the size of a vector, size yields the size of a matrix (number
of rows, number of columns). With zeros (r,c) you can create a matrix with r rows
and c columns with all elements being zero, ones (r,c) creates a r × c matrix with all
elements being one.
Often it is helpful to have sequences of numbers like 1,3,5,7,... MATLAB offers a special
mechanism to create these kind of sequences with a starting value k, an increment d
and an end value n. The command to create such a sequence is k:d:n. If d is omitted,
the increment is set to one. E.g. the vectors (1, 3, 5, 7, 9, 11, 13) and (5, 4, 3, 2, 1) can be
generated with:
>> [1 : 2 : 13], [5 : −1 : 1]
3
Exercise:
3.
P100
• calculate the following term: k=1 k · (101 − k). Thereto, create an increasing
sequence ~u and a decreasing sequence ~v and calculate ~u · ~v T . Write down the
MATLAB commands and the result.
Result:
2D-Plotting
MATLAB supports two-dimensional plots of points and functions. The plot command
takes as arguments vectors of x- and y-coordinates. E.g. if you want to display a sine
curve you must create some sample points first and give it to the plot command:
>> x = 0 : 0.01 : 2 ∗ pi; % create x-coordinates between 0 and 2π
>> y = sin(x); % create the respective y-coordinates
>> plot(x, y,0 r−0 ); % plot the sine curve
The third argument of the plot command controls the style in which the points and
curves are plotted, i.e. the color, the point style, and the line style. You can get a list
of all style options with ‘help plot’. When calling the plot command a new figure is
drawn and the old figure is removed. If you want to keep the old figure and add a new
curve to it, call ‘hold on’ first. To make a new plot command erase the old figure, call
‘hold off’. E.g. to add a cosine curve to a the sine plot call:
>> hold on
>> plot(x, cos(x),0 b − −0 )
4
Exercise:
4.
• plot the sinc function in the interval between -10 and 10 with a red solid line
1 1
• add to the same figure a plot of the functions πx and − πx with a black dotted
line. Resize the figure to maximal y-values of ±1.5 with the axis-command (see:
help axis)
M-Files
Often, you want to do the same calculation several times. Then it is very inconvenient
to type all commands again and again. For this reason MATLAB offers the possibility
to write script files which you can use to save sequences of commands and that you can
execute several times. In MATLAB, these files must have the filename extension .m
which indicates that the file contains a MATLAB program. You can create such a script
file by clicking (right mouse button) in the subwindow Current Folder and selecting the
menu item New File/script or by clicking in the HOME -Ribbon on the new script icon.
Give it a meaningful name and start to edit the file. After finishing, you can execute
the scriptfile with typing its name (without extension .m) or pressing the run-Button
(shortcut F5-Key) in the EDITOR-Ribbon.
Exercise:
5. Create a script file that executes all commands that are necessary to generate the
figure from the exercise above. Close the old figure and execute the script to create the
figure again. (For the report: Depict this figure in the document)
Beside the possibility to write scripts which are executed as if the commands would be
typed in the console there is the possibility to write user-defined functions which take
arguments and return result values. An M-File that starts with the following lines is
interpreted as function:
The function-name must be identical to the name of the M-File. The subsequent com-
ment line is used to describe the function. It is printed when ‘help function-name’ is
called.
Like other programing languages, MATLAB has some built-in commands to implement
conditional execution of statements and loops like if, for, and while. Here are some
examples of functions that illustrate the use of these commands:
5
function [ s ] = signof (x)
% calculate the sign of x, i.e. -1 if x is negative, +1 if x is positive,
% and 0 if x=0
if x==0
s=0;
elseif x>0
s=1;
else
s=-1;
end
function [ s ] = euclideanlength ( x )
% calculate the Euclidean length of vector x
s=0;
for i=1:length(x)
s=s+x(i)*x(i);
end
s=sqrt(s);
function [ n ] = smallestsquare ( x )
% calculates the smallest square number that is larger than x
n=1;
while n*n<=x
n=n+1;
end
Exercise:
6. Write a function
pPin MATLAB that calculates the Euclidean distance between two
2 T
vectors u and v: i (ui − vi ) . Give the result for u = [44, 12, −45] and v =
T
[−3, 34, 18] .
On the related Moodle site, the zip-file 01 Templates.zip will be put which provides
templates for a generic script-file as well as a generic function-file. The headers are
meant to be used as template in all your files, the provided code shall show some coding
rules (especially a well documented file) and some basic functions and good practices
(e. g. putting the functions into an additional folder).
6
Image Processing
MATLAB contains some commands to do image processing. Greylevel images are stored
as matrices. They can be imported from files, displayed, and manipulated. The most
important commands are:
imread read an image file from the I = imread (’flower.png’);
working directory
imread read an image file from the xy I = imread (’\xy\flower.png’);
directory
double converts an image with UINT8 J = double(I)
values into a double matrix
uint8 converts a matrix with double J = uint8(I)
values into a matrix with UINT8
(8bit) numbers
rgb2gray convert pixel or image from J = rgb2gray( I );
RGB to grey values
imshow display an image I imshow( I );
imagesc also displays an image, respec- imagesc( J );
tively a matrix
colormap change the colormap that is used colormap(gray(256));
to display images
imhist Display the histogram of images imhist( J );
fspecial create convolution kernels like f = fspecial(’gaussian’,3,0.5);
Gaussian filters, etc.
imfilter image filtering by convoluting K = imfilter( J, f );
the image with a filter
deconvwnr apply Wiener deconvolution to deconvwnr( J, f, 0.1 );
an image
fft2 2D-Fourier transform fft2(g);
ifft2 inverse 2D-Fourier transform fft2(g);
Important remarks: The double conversion of the image read with imread() is nec-
essary to perform later arithmetic operations on. For the purpose of displaying it in
grayscales with imshow() use a conversion back to UINT8 (256 grey levels). An auto-
mated mapping to 256 values is (mostly) working when using imshow(I,[]).
If you use imagesc() take special care on the colormapping, as it is a more basic function,
that can also be used to visualize matrices.
7
Exercise:
6. Perform the following steps of image processing:
• calculate the size of the image, the minimal, maximal, and average grey value of
the image.
size= , minimum= , maximum= , average=
• use the function J = imadjust( I ) to enhance the contrast and display the en-
hanced image and the new histogram (use the ’name’ property of the figure to
give the image a title describing the content). Add a screenshot of both to your
lab report.
8
Assignment for Lab session 1 - Project 1.1
Write program code that calculates depth of field and hyperfocal distance for given
parameters. The necessary code shall be subdivided into three m-files. A doc file has to
be contained in the specified folder!
1. Write a m-file called assignment 1 run.m. In this file parameters are given and some
user output is produced.
2. Write a function called hyperfocal.m having the following header:
Taking parameters focal length [mm] and epsilon [µm], giving back hyper f in meters.
3. Write a function called calculate deltag.m having the following header:
Taking the parameters focal length in mm, epsilon in µm and object dist in meters. The
return values delta g, delta gl, delta gr are all in meters.
What your code shall do: If assignment 1 run.m is started, the depth of field and hy-
perfocal distance shall be displayed on the command window for the two cases:
In addition, for parameters of case two a plot shall be displayed in a figure, showing
delta gl if the object distance is increased in steps of 10 cm from 1 m to 10 m (Hint:
You’ll need a for loop around the function call). XY-Labels must be in correct units [m]!
Deliverables