Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB •...

22
Matlab Laboratory of Artificial Intelligence. Luca Cosmo

Transcript of Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB •...

Page 1: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Matlab

Laboratory of ArtificialIntelligence.

Luca Cosmo

Page 2: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Loading Data from File

We need to process large quantities of data.

Data are usually stored in binary or ASCII files.

• ASCII files store data as sequence of characters in ASCII

format. It is human readable.

• Binary Files store raw data in binary format.

Most significant bit from right

Data: 100 (int) Text editor Bits

Saved in ASCII 100 1 0 0 0 1 1 0 0

0 0 0 0 1 1 0 0

0 0 0 0 1 1 0 0

Saved in Binary d 0 0 1 0 0 1 1 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

0 0 0 0 0 0 0 0

Page 3: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Open File

To get a file handle in Matlab use

fileID = fopen(filename, permission)

Permission describes the type of access read, write, append, or update:• 'r' Open file for reading (default).

• 'w' Open or create new file for writing.

Discard existing contents, if any.• 'a' Open or create new file for writing.

Append data to the end of the file.• 'r+','w+','a+' To read and write to the same file

If we want read data from the file data.txt:

>> f = fopen('data.txt','r');

Page 4: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Binary File

Read matrices from file:

A = fread(fileID, sizeA, precision)

sizeA , number of elements to read from file:• inf read the file to the end and put the elements in a column vector.

• n read n elements from the file into a column vector

• [m,n] read m*n elements from the file and fill a m-by-n matrix in

column order

precision, input and output number format• 'source' read numbers from file as ‘source’.

The elements of the output matrix will be double.• 'source=>output‘ read numbers from file as ‘source’.

The elements of the output matrix will be ‘output’.

Possible values for ‘source’ and ‘output’ are:bit, ubit, int, uint, uchar, single, double, …

Page 5: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Binary File

Move inside a file using fseek:

>> fseek(f,10,'bof') %move forward of 10 bytes

Write binary files.

Write into the file the matrix A by column using the ‘precision’

number format:

fwrite(fileID, A, precision)

CLOSE THE FILE.

Remember to close the file after using it:

fclose(fid); %close the file identified by fid

fclose all; %close all opende files

Page 6: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Example

%Create file for writing

fid=fopen('test.dat','w');

%reshape the vector 1:9 into

%a 3by3 matrix (by column)

A = reshape(1:9,3,3)’

%write the A matrix as uint8

fwrite(fid,A,'uint8');

fclose(fid);

%open test.dat for reading

fid=fopen('test.dat','r');

%read the first column of the matrix

col = fread(fid,3,'int8')

%read the fourth number as a bit sequence

bit_4 = fread(fid,8,'ubit1')

fclose(fid);

A =

1 2 3

4 5 6

7 8 9

col =

1

4

7

bit_4 =

0

1

0

0

0

0

0

0

Page 7: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

ASCII file

importdata reads numeric ASCII files into a matrix:

A = importdata(filename, delimiter)

delimiter is the character used into the file to separate

column elements. If no specified it is inferred from the file.

Each row in the file is a row in the resulting matrix.

>> A = importdata('A.txt');

A =

1 2 3

4 5 6

7 8 NaN

1;2;3

4;5;6

7;8;

File: A.txt

Page 8: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

ASCII file

Read formatted text from file:

A = fscanf(fileID, format, sizeA)

sizeA, number of elements to read from file:• inf read the to the end of file;

• n read at most n elements;

• [m,n] read at most m*n elements from the file in column order

and fill a m-by-n matrix in column order. n can be inf.

Format can be:‘%d’ (integers), ‘%f’ (floating point),

‘%c’ (chars), ‘%s’ (strings), …

Page 9: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

ASCII file

We can write text into a file using:

fprintf(fileID, format, A, ...)

fprintf writes the element of A matrix (by column)

applying the format specified by the format string.

Matlab uses formatting operators similar to C.

Example:

A = 1:4;

fprintf(f,'%d, ',A);1, 2, 3, 4,

File content:

Page 10: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Plotting Data

Draw multiple graphs on the same figure

Use subplot to create a grid on current figure:

sublot(n,m,current_index)

n and m are the rows and column of the grid,

current_index is the cell in which we want to draw the

next plot.

m

n

current_index

Page 11: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Plotting Data

Draw multiple functions plotUsually the plot function overwrite the previous plot:

>> plot(1:100,0.1:0.1:10)

>> plot(1:100,log(1:100))

We can use the command hold to add a

new graphic to the same graph.

>> plot(1:100,0.1:0.1:10)

>> hold on; %Do not replace the current graph

>> plot(1:100,log(1:100))

>> hold off; %Replace the current graph

0 10 20 30 40 50 60 70 80 90 1000

0.5

1

1.5

2

2.5

3

3.5

4

4.5

5

0 10 20 30 40 50 60 70 80 90 1000

1

2

3

4

5

6

7

8

9

10

Page 12: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Plotting Data

Animating a graph.We can update the graph simply replacing the current

graphics with the updated one.

time=0;

while(time<10)

tic

plot(0:0.01:2*pi,sin(time+(0:0.01:2*pi)))

drawnow; %Force redrawing

time = time + toc; %Add to time the elapsed time

end

We can force Matlab to redraw the graph with the updated function by calling drawnow.

Page 13: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Histogram plot

The command hist can be used to display the frequency

distribution of elements in a given vector.

hist(Y)bins the elements of Y in 10 equally spaced containers and display

a bar plot showing the number of elements in each bin.

%generate normally distributed pseudorandom vector

y = randn(10000,1);

%display the distribution histogram with 10 bins

hist(y)

%display the distribution histogram with 100 bins

hist(y,100)

%display the distribution histogram with

%lenght(vec) bins centered in the values of vec

vec=-6:0.05:6;

hist(y,vec)

Page 14: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Images in MATLAB

• Matlab represent images like matrices.

• For an grayscale image of NxM pixels we have a matrix

of N rows and M columns.

• The indices of the matrix correspond to the image pixels

coordinate.

• Each cell contains the intensity of the corresponding

pixel with a value from 0 to 255 (uint8).

255 255 255 27 9

255 255 14 24 42

255 14 30 45 30

27 22 41 25 27

9 32 28 29 38

1 2 3 4 5

1

2

3

4

5

Page 15: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

232 235 237 233 233

242 234 227 224 224

228 218 214 217 223

226 219 208 200 210

235 232 208 182 192

RGB images

• Three dimensional Matrix NxMx3

• The first and second indices identify the pixel coordinates.

• The third index identifies the channel.

• my_image(x,y,:) is a vector with the three components

(RGB) of the pixel at coordinates x and y.

234 237 237 234 232

241 234 225 223 223

226 216 210 213 220

219 213 201 193 204

225 223 199 174 184

242 245 243 238 236

250 240 231 227 225

232 222 216 218 222

226 218 206 196 205

231 226 202 175 184

Page 16: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Draw Matrices

You can draw a matrix as an image using the color to

represent the value.

imagesc(A,[min max])

Draws the matrix A, the values are scaled between 0 and 1 using the min and max [a_ij=(a_ij-min)/(max-min)].imagesc(A) version uses the minimum and maximum of

A as min and max.

The resulting values are used as

parameter on a colormap.

[X,Y]=meshgrid(1:1000,1:1000);

C=X.*Y;

imagesc(C)

100 200 300 400 500 600 700 800 900 1000

100

200

300

400

500

600

700

800

900

1000

Page 17: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Draw Matrices

Change colormap.You can set different colormaps

for the input data using colormap.

>> imagesc(C)

>> colormap('JET')

>> colormap('hot')

>> colormap('gray')

To display the side colorbar use >> colorbar

200 400 600 800 1000

100

200

300

400

500

600

700

800

900

1000

1

2

3

4

5

6

7

8

9

10x 10

5

200 400 600 800 1000

100

200

300

400

500

600

700

800

900

1000

1

2

3

4

5

6

7

8

9

10x 10

5

200 400 600 800 1000

100

200

300

400

500

600

700

800

900

1000

1

2

3

4

5

6

7

8

9

10x 10

5

Page 18: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Draw Matrices

If we give a m by n by 3 matrix to imagesc it is displayed as

a RGB image.

RGB(:,:,1) = C;

%reflect matrix along the second diagonal[/]

RGB(end-(0:end-1),end-(0:end-1),2) = C;

RGB(:,:,3) = zeros(size(C));

%manually rescale values beteen 0 and 1

imagesc(RGB./max(RGB(:)))

100 200 300 400 500 600 700 800 900 1000

100

200

300

400

500

600

700

800

900

1000

Page 19: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Classifier Examples

Matlab provides some inbuilt classifiers.

Classify: assign an “element” to a class.

Two phases:

1. Training with groundtruth data

(feature_vector, class) TRAINING CLASSFIER

2. Classify new elements using CLASSIFIER

(feature_vector) CLASSIFIER class

Some classifiers:

• KNN classifier

• SVM classifier

Page 20: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

KNN Classifier

KNN classifier classifies an element (described by a feature

vector) based on its neighbors on the training set.

load fisheriris

%Init training set

T_featurevec = meas(51:end,3:4);

T_class = species(51:end);

%init query features vector

Q_fv = [5 2;5.3 1.2];

Q_class = knnclassify(Q_fv,T_featurevec,T_class)

%Draw scatter plot

featurevec=[T_featurevec;Q_fv];

classes=cat(1,T_class,strcat('C: ',Q_class));

%draw a scatte plot assigning each group a different color

gscatter(featurevec(:,1),featurevec(:,2),classes);

Page 21: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

SVN Classier

Linear SVN split the elements of two classes by a iperplane

in the feature space.

load fisheriris

%Init training set

T_featurevec = meas(51:end,3:4);

T_class = species(51:end);

Q_fv = [5 2;5.3 1.2];

%train the svm

svmClassifier =

svmtrain(T_featurevec,T_class,'showplot',true);

%use the trained svn to classify new elements

species = svmclassify(svmClassifier,Q_fv, 'showplot',true);

Page 22: Short introduction to Matlab - Univecosmo/material/matlab... · 2014-03-06 · Images in MATLAB • Matlab represent images like matrices. • For an grayscale image of NxM pixels

Cross Validation

Split the training set into N subsets use N-1 sets to train the

classifier and 1 set to measure the classification error ratio.

%for each element returns the index of its group

CV = crossvalind('Kfold',size(xdata,1),10);

error = [];

for i = 1:10

test = (CV == i);

train = ~test;

%train the classifier with the current training set

%and classify the remaining elements

class =

knnclassify(xdata(test),xdata(train),group(train));

%Save the error ratio for this test set

error(i)= (class~=group(test))./sum(test);

end