Download as rtf, pdf, or txt
Download as rtf, pdf, or txt
You are on page 1of 22

Images in MATLAB:

What is a pixel? A pixel is the smallest unit of the picture that can be
manipulated. Images in any computer are represented by many small
points of color. When the points are small enough, we can represent
almost any amount of detail. See example below:

The simplest way to represent an image is using 1-bit monochrome. Imagine


taking an nxn matrix. Each element in the matrix is a 1 or 0, where 1 is white
and 0 is black. By placing the white and black in specific positions of a large
enough matrix, you can get the following picture.

A slightly more complicated way to represent an image is using an 8-bit (1byte) grayscale. In this case, each element of your nxn matrix actually takes
8 bits (or eight 1s and 0s), and represents the intensity of light from white
to black. Since eight 1s or 0s can represent a total of 2^8 = 256 diferent
numbers, there is a total of 256 diferent intensities you can have between
totally black (00000000) and totally white (11111111). Usually, we use 8
bits to represent the numbers from 0 to 255. This allows you to create more
complicated images as seen in the example below:

To store colors in computers, we use color channels. Usually we use three


colors: red, green, and blue. When the colors are mixed properly, your eye
perceives any color in the rainbow. Imagine your screen is a matrix of pixels.
Behind each pixel are three color channels. Each channel will output a
specified intensity of red, green, or blue light into the pixels. The mixed
colors will allow you to see some color on that pixel. Thus, we need a total of
three bytes of info for each pixel, one byte for each color channel. To
properly represent a colored picture in MATLAB, we need to use a 3-D array;
specifically an nxnx3 array. Each separate page of the array is like a
grayscale image, where each pixel specifies some intensity. However, each
intensity specified this time is for a color channel. The first page is red, the
second page is green, and the third page is blue. See the example below:

To read an image into MATLAB, use the imread() function. Save the following
image as a jpeg to your MATLAB folder and name it
'Low_Library_Columbia.jpg.

>> x = imread('Low_Library_Columbia.jpg');

When you type the above into MATLAB after saving the file, the picture will
be stored a 3-D
matrix in the variable x. If you check on the size of x, you will get the
following:
size(x)
ans =
2112

2816

To show the matrix x as a picture in MATLAB use the image() function.


>> image(x) % should display the picture as a figure in MATLAB.
We can access the 3-D image matrix as we have before. Try
image(x(:,:,1)). This should show you what the picture looks like when
only the red channel is shown. To call on the other channels simply call on
rd
the 2nd and 3 pages of the 3-D matrix.
>> x(1,1,1)
ans =
116
% Here we called on the intensity of the red channel for the pixel in row one
and column one of the picture.
You can directly change pictures by changing the intensity of each
channel of the picture. For example:
>> x(1:100,1:100,1) = 255;
>> x(1:100,1:100,2) = 255;
>> x(1:100,1:100,3) = 255;
>> image(x)
% Here we have set reset the intensities in the upper left corner of the
pictures by simply changing the value of the intensity. When you image(x),
you should see a white square in the upper left corner of your picture. See
example below:

Histograms in MATLAB:
The histogram function in MATLAB comes in the form of N = hist(array,
bins). The function takes two inputs, the array of numbers that you want to
graph and the number of bins/groups you want to separate your numbers
into. The hist function then gives you the frequency of the numbers that
appears in each bin/group. If you do not specify an output, the function will
automatically plot the histogram. If you do specify an output, the output will
store the frequency data in a row vector, where each element represents
the frequency of numbers that appears in a specific bin/group of numbers.
>> hist(randn(1,10000),100);
350

300

250

200

150

100

50

0
-4

-3

-2

-1

% Typing the line above in MATLAB should provide the graph above.
Randn() is a function that randomly gives values following the Gaussian
distribution. Thus the graph should appear as the commonly seen Gaussian
bell curve.
>> N =
hist(randn(1,10000),100)
N=
Columns 1
through 18
2 0 5

3 1

2 4

7 7 11 14 16 17 20 16 25 30 34

Columns 19
through 36
45 5543 73 81 92 108 115 130 144 148 156 169 197 208
188 234 233
Columns 37

through 54

259 296 320 276 302 284 307 297 317 308 293 299 285 295
245 271 255 227
Columns 55 through 72
264 221 179 181 179 150 126 128 96 105
34
39 36

94 77 75 53 57

Columns 73 through 90
27

2812 15 10 6

8 7

5 2

1 2

4 2

1 1

Columns 91 through 100


0 0 0

0 0

0 0

0 0

% Setting the hist function to an actual output stores the frequency


data into the output variable name as a row vector. You can plot(N) to
look at what the peaks of the histogram should be.
Image Histograms in MATLAB:
Image histograms work a little differently from hist in MATLAB. The built-in
function imhist() can graph one color channel of your picture into a histogram
with 256 bins. There are 256 bins because there is a total of 256 diferent
intensities for each color in MATLAB. The function graphs the frequency of
the appearance of each intensity value. Note: the imhist() function can only
graph one color channel at a time, so you can only input one page of your 3D image matrix at a time. For example:
>> x = imread('Low_Library_Columbia.jpg');
>> imhist(x(:,:,1))

% Here we have graphed the red channel of the picture using the imhist()
function. We see a large frequency of high intensity red in the picture.
Image Matching Using Histograms:
Imagine a robot moving through New York City. When it is on the street, it
can access military satellites and calculate its position using GPS to within a
few centimeters of its actual position. However, once the robot enters a
building and loses a direct line of site with the satellites GPS, it no longer
works. The robot immediately becomes lost. How can we avoid this problem?
One
idea that robotic scientists have been trying out is matching images. If the
robot had a memory bank of pictures at various points in the building, then
the robot could match the scenes it sees with the pictures in the memory
bank to figure out where in the building it is. The robots use omnicams
(catadioptric cameras) to see. A catadioptric system is a system that uses
both lenses and mirrors. When positioned correctly it can give you a 360
degrees image of the world. See examples below:

However, if you take an image and rotate it X degrees, you will find that you
have a diferent picture. At least you cant match the pictures pixel by pixel
without rotating one of the pictures. The robot will face this problem when
comparing the pictures. If the robot is in a slightly diferent orientation each
time it is at the same area, we will be unable to match the pictures taken.
But, the histograms generated from pictures will be the same even if the
pictures are rotated. Thus, we can make a database of image histograms.
Each time the robot takes a picture it can then compare histograms together
to find its position.
When you compare the histograms though, you need to be aware that just
summing up the total difference for each pixel will not allow you to compare
images of the same size. If there is the same amount of pixels for two
images, then the sum of the difference for the frequency of each intensity
will always equal 0. To get around this problem make to square the
difference or take the absolute value of the diference and then find the

sum. See example below:

5.jpg
>>
>>
>>
>>
>>

9.jpg

x = imread('5.jpg');
y = imread('9.jpg');
N = imhist(x(:,:,1));
M = imhist(y(:,:,1));
sum(N-M)

ans =
0
% Since the pictures have the same number of pixels, even if they are
completely diferent pictures the sum of the diference of the histograms
will always be zero.
>> sum((N-M).^2)
ans =
10874514
>> sum(abs(N-M))
ans =
1225
6
% To get a number that actually compares how close two pictures
are, use the squared diference or the absolute diference.

Numerical Derivatives, Integrals, and Function Handles


Numerical Derivatives:
Recall that the derivative of a function can be written in the form of
, where dy

dx
and dx are infinitesimal changes in y and in x respectively. To
approximate the
y
derivative, we can calculate
instead.
x
MATLAB provides a function called diff that will take the diference
between adjacent elements. (In essence, dif(x) is equivalent to x
.) You will get an array with one element shorter than the original
array.
Example:
>> x = [1:5]
x=
1

2 3

>> diff(x)
ans =
1

1 1

We can calculate diff(y)./diff(x) to approximate the derivative,


for the data. Example :
2
'
Lets try to plot y = x and its derivative y = 2 x :
>> x=0:0.1:4;
>> y = x.^2;
>> x2=0:0.1:3.9;
>> y2=dif(y)./dif(x);
>> plot(x,y,'g-',x2,y2,'r--')
>> legend('x^2','derivative of x^2')

dy

Note: The reason that we set x2 to have one fewer value than
x is that y2 is the result of diff on y and x, which produces one
fewer value than x.
Similarly, let try to find and plot the derivative of sin(x):
>>
>>
>>
>>
>>
>>

x = 0: pi/20:2*pi;
y = sin(x);
x2 = 0:pi/20:2*pi-pi/20;
y2 = dif(y)./dif(x);
plot(x,y,'g-',x2,y2,'r')
legend('sin(x)','derivative of sin(x)')

Numerical Integration:
We can also use MATLAB to calculate the integral of a function. Recall
the trapezoid method to find the area under a curve:

To find approximately the area under this curve, we can divide


the curve into segments, try to place a trapezoid under each
segment, and sum up all the trapezoidal contributions.
MATLAB provides a function called trapz that approximates the
integral of a function via the trapezoid method.
The trapz function has the form of
>>trapz(x,y)
Example:

Lets try to approximate the exact


value of

sin(x) dx .
0

We know that

sin(x) dx =

cos( x)
0

>> x = 0: pi/100:pi;

= cos( ) ( cos(0)) = (1) (1) = 2

>> y = sin(x);
>> trapz(x,y)
ans =
1.999
8
To compute the numerical integral of a function, we can also use
the quadrature function, quad(). The trapezoid method above is a
specific type of quadrature method. The way quadrature works is
by recursively calling a function, evaluating it at certain points, and
finding the sum. The exact mechanism of how quadrature works is
beyond the scope of this lecture.
The quad method takes the form of
>>quad(function, a, b)
where function is the function handle of the function that you are
trying to integrate and a and b specify the range of the x values
(the limits of integration).
Before we can continue with the discussion of the quad() function, we
first need to learn about function handles.
Function Handles
We can create a function handle by prepending an @ sign to an
EXISTING function. The function can either be built-in to MATLAB or
created by you and saved in an m- file. The function handle can be
thought of as a reference to the actual function. The most important
use of function handle is that we can treat the handle as a variable
and pass it into other functions so they can use them too.
Example:
squaref.m
function y = squaref(x)
% This function take a value and return the square of it.
y = x .^ 2;

We can create a function handle for squaref by entering


>> s = @squaref;
What the function handle does is that it provides a means
of calling a function indirectly.

Now you may use the function handle as though it were the
squaref
function itself by passing in an appropriate input argument.
>> s(10)
ans =
100
To use the quad() function, we need to pass the function handle of
the function which we are trying to integrate to it.
Example:
2

Lets try to integrate the y = x function from 0 to 1


2

The first thing we need is WRITE the y = x function OURSELVES!


Our squaref
function does exactly this. So lets just create a function handle
for it:
>> s = @squaref;
Next, let us call the quad function with a = 0 and b = 1
>> quad(s, 0, 1)
ans =
0.3333
Lets calculate the integral by hand and verify the results:
1
1 31 1 3 1
1
2
x dx = 3 x 0 =3 (1) 3 (0) 3=
0
As we can see, the quad function works as intended.
Note:
Instead of actually creating the function handle
separately and then passing it into quad, we could have
done it directly, as shown below:
>>quad(@squaref, 0, 1)
And the same result would have been produced.

Solving Ordinary Diferential Equations (ODEs)

dy
A simple first order diferential question has the general form
= f (t,y)
dy
where
dt
dt
is the change in y with respect to time (the derivative of y), and f (t, y) is
any
function of t and y.
Heres an extremely simple diferential equation:

dy

= y . We can solve

this ODE by

dt
separation of variables and then integrate. The resulting equation is y =
t
Ce , where C is a constant. In order to solve for a specific solution, we
must provide an initial condition, such as y(0)=1, so that we can solve
t
for C. In this case, if y(0)=1, C is equal to 1, and our answer is y = e .
We can solve the ODE in MATLAB quite easily using the built-in ODE
solvers.
MATLAB provides a large set of ODE solvers for us to use, each with its
own degree of
precision. The ODE solver we are going to use is ode45.
The ODE solver takes the form of
>>[t,y] = ode45(odefunction, tspan, y0)
where odefunction is the handle for the function that gives us the
tspan is the

dy

dt
range of t values, and y0 is the initial condition. It returns two outputs, t,
for the t
values, and y, for the y values.
So lets try to solve
dt

dy

= y in MATLAB.

First step is to create our ODE function, simpleode.m


function dy_dt = simpleode(t,y)
%Simple ode function
dy_dt=-y;

Please note, that the order of the inputs (t,y) matters. If the function is
instead
declared as simpleode(y,t), you will get an incorrect result.
The next step is to call the ode45 function. Remember that the ode45
produces 2
outputs.
>>[t,y] = ode45(@simpleode, [0,5],[1]);

Finally, lets plot our y vs. t graph:


>> plot(t,y)

Note:
t
This graph should make sense, as the solution to the ODE is y = e ,
which is an exponentially decaying function.
Consider the following problem:
An object is dropped from a height of 500 meters. Find an equation
that gives us the position of the object as a function of time.
Recall in physics that a falling object can be modeled using the equation
v = a * t, where v = velocity, a = acceleration due to gravity, and t =
time. We will assume that the acceleration due to gravity is -9.81m/s2.
If we let y(t) be the height of an object at
time t, we can see that velocity is
(recall that velocity is the change
e in
q
u
al
to
dy
dt
distance with respect to time). If we

su ute v =
bs
tit

dy

dt

and a = 9.81 into the

equation v = a * t , we will get the following diferential equation:


9.81* t . If we

dy

dt
were to solve this equation using separation of variables and then
integrate, we
2
would get the equation y = 4.90t + C, where C is a constant. Given our
2
initial condition, where at t=0, y=500 meters, we have 500 = 4.90 * (0)
+ C , and solving for C would give us C = 500 . So the equation that gives
2
us the position of the object as a function of time is y = 4.90t + 500.
Now lets try to solve
dt

dy

= 9.81* t in MATLAB.

The first thing we need to do is create our ODE function,


velocity_function.m
function dy_dt = velocity_function(t,y)
% ODE function that models the equation dy_dy=a*t
dy_dt = -9.81.*t;

The next step is to call the ode45 function. Remember that the
ode45 produces 2 outputs.
>>[t,y] = ode45(@velocity_function, [0,
10], 500); Finally, lets plot our y vs. t
graph:
>> plot(t,y)

We can use polyfit() to find an equation of a polynomial that best fit the
curve.
>> y=polyfit(t,y,2)
y=
-4.9050 -0.0000 500.0000
2

This gives us the same equation, y = 4.90t + 500.


Reference on solving and plotting ODEs:
http://laser.ceb.cam.ac.uk/wiki/images/e/e5/NumMeth_Handou
t_7.pdf

You might also like