Вы находитесь на странице: 1из 56

Lecture notes

Digital Image Processing by Jorma Kekalainen

Digital Image Processing


Jorma Kekalainen

Digital Image Processing


Images in Matlab

Lecture weeks 7 and 8

Page 1

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matlab
Matlab is a data analysis and visualization tool which
has been designed with powerful support for matrices
and matrix operations.
Matlab has excellent graphics capabilities, and its own
powerful programming language.
One of the reasons that Matlab has become such an
important tool is through the use of sets of Matlab
programs designed to support a particular task.
These sets of programs are called toolboxes, and the
particular toolbox of interest to us is the image
processing toolbox.
Jorma Kekalainen

Digital Image Processing

390

Images in Matlab
The basic data structure in Matlab is the array, an
ordered set of real or complex elements.
This object is naturally suited to the
representation of images, real-valued ordered
sets of color or intensity data.
Matlab stores most images as two-dimensional
arrays (i.e., matrices), in which each element of
the matrix corresponds to a single pixel in the
displayed image.
Pixel or picture element usually denotes a single
dot on a computer display.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

391

Page 2

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
For example, an image composed of 200 rows and 300
columns of different colored dots would be stored in
Matlab as a 200-by-300 matrix.
Some images, such as true color images, require a threedimensional array, where the first plane in the third
dimension represents the red pixel intensities, the second
plane represents the green pixel intensities, and the third
plane represents the blue pixel intensities.
This convention makes working with images in Matlab
similar to working with any other type of matrix data, and
makes the full power of Matlab available for image
processing applications.

Jorma Kekalainen

Digital Image Processing

392

Example
Create the image of a ramp (256*256):

using for loops.

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

393

Page 3

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
for i = 1 : 256
for j = 1 : 256
A(i, j) =j -1;
end
end
image(A)
colormap(gray(256));
axis image;
Jorma Kekalainen

Digital Image Processing

394

Example
The image of a circle
(256*256) of radius 80
pixels centered at (128;
128):

Jorma Kekalainen

Lecture weeks 7 and 8

for i = 1 : 256
for j = 1 : 256
dist = ((i-128)^2 + (j-128)^2)^(.5);
if (dist < 80)
B(i,j) = 255;
else
B(i,j) = 0;
end
end
end
image(B);
colormap(gray(256));
axis image;

Digital Image Processing

395

Page 4

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
The image of a graded
circle (256*256):
C(i,j) = A(i,j)*B(i,j)/255

Jorma Kekalainen

for i = 1 : 256
for j = 1 : 256
C(i,j) = A(i,j)*B(i,j)/255;
end
end
image(C);
colormap(gray(256));
axis image;

Digital Image Processing

396

Example
Create the image of a ramp (256*256):

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

397

Page 5

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
>> A=ones(256,1)*(0:255);
D=uint8(A);
figure,imshow(A)
figure,imshow(D)
whos
Name
Size
Bytes Class

A
D

Jorma Kekalainen

256x256
256x256

Attributes

524288 double
65536 uint8

Digital Image Processing

398

Matlab function and command


A Matlab function is a keyword which accepts
various parameters, and produces some sort of
output, e.g., a matrix, a string, a graph or figure.
A command is a particular use of a function.
Examples of commands might be
>> sin(pi/3)
>> [c,emap]=imread('kids.tif');
>> figure,imshow(c)
>> figure,imshow(c,emap)
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

399

Page 6

Lecture notes

Digital Image Processing by Jorma Kekalainen

Matrix
Matlab's standard data type is the matrix.
All data are considered to be matrices of some
sort.
Images, of course, are matrices whose elements
are the gray values (or possibly the RGB values) of
its pixels.
Single values are considered by Matlab to be
(1*1) matrices, while a string is merely a (1*n)
matrix of characters; n being the string's length.
Jorma Kekalainen

Digital Image Processing

400

Grayscale images
Matrices can be handled very efficiently in
Matlab.
Images may be considered as matrices whose
elements are the pixel values of the image.
Suppose you will have a Matlab command
window open, and in it the Matlab prompt >>
ready to receive commands.
Type in the command
>> c=imread('coins.png');
Jorma Kekalainen

Digital Image Processing

Note: PNG Portable Network Graphics is a graphics file format.

Lecture weeks 7 and 8

401

Page 7

Lecture notes

Digital Image Processing by Jorma Kekalainen

c=imread('coins.png');
This takes the gray values of all the pixels in
the grayscale image coins.png and puts them
all into a matrix c.
This matrix c is now a Matlab variable, and so
we can perform various matrix operations on
it.
In general the imread function reads the pixel
values from an image file, and returns a matrix
of all the pixel values.
Jorma Kekalainen

Digital Image Processing

402

c=imread('coins.png');
A few notes about this command:
It ends in a semicolon; this has the effect of not
displaying the results of the command to the screen.
As the result of this particular command is a matrix of
size 246*300 = 73800 elements, so we don't want all
its values displayed.
The name coins.png is given in single quote marks.
Without them, Matlab would assume that coins.png
was the name of a variable, rather than the name of a
file.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

403

Page 8

Lecture notes

Digital Image Processing by Jorma Kekalainen

figure,imshow(c)
Now we can display this matrix as a grayscale image typing in
the command
>> figure, imshow(c)
This is really two commands on the one line.
Matlab allows many commands to be entered on the same
line; using commas to separate the different commands.
The two commands we are using here are:
figure, which creates a figure on the screen.
A figure is a window in which a graphics object can be placed.
Objects may include images, or various types of graphs.
imshow(c), which displays the matrix c as an image.
This is a display of the gray values of the pixels in the image.
Jorma Kekalainen

Digital Image Processing

404

figure,imshow ('coins.png')
If there are no figures open,
then an imshow command,
or any other command
which generates a graphics
object, will open a new
figure for displaying the
object.
However, it is good practice
to use the figure command
whenever you wish to
create a new figure.
We could display this image
directly, without saving its
gray values to a matrix, with
the command
>>imshow('coins.png')
Jorma Kekalainen

Lecture weeks 7 and 8

Note: Since coins.png is an 8-bit grayscale


image, the pixel values appear as integers in the
Digital Image Processing
405
range 0-255.

Page 9

Lecture notes

Digital Image Processing by Jorma Kekalainen

RGB (truecolor) images


An RGB image, sometimes referred to as
a truecolor image, is stored as an m-by-n-by-3 data
array that defines red, green, and blue color
components for each individual pixel.
The color of each pixel is determined by the
combination of the red, green, and blue intensities
stored in each color plane at the pixel's location.
Graphics file formats store RGB images as 24-bit
images, where the red, green, and blue components
are 8 bits each.
This yields a potential of 16 million colors.
The precision with which a real-life image can be
replicated has led to the nickname "truecolor image."
Jorma Kekalainen

Digital Image Processing

406

RGB (truecolor) images


An RGB Matlab array can be of class double, uint8, or uint16.
In an RGB array of class double, each color component is a value
between 0 and 1.
A pixel whose color components are (0,0,0) is displayed as black,
and a pixel whose color components are (1,1,1) is displayed as
white.
The three color components for each pixel are stored along the
third dimension of the data array.
For example, the red, green, and blue color components of the pixel
(10,5) are stored in RGB(10,5,1), RGB(10,5,2), and RGB(10,5,3),
respectively.
To display the truecolor image RGB, we can use imshow or
image function. E.g.,
image(RGB)

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

407

Page 10

Lecture notes

Digital Image Processing by Jorma Kekalainen

Read a truecolor image into


Matlab
Given one command at a time

Jorma Kekalainen

Digital Image Processing

408

Read a truecolor image into


Matlab
Given the whole command
block at the same time

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

409

Page 11

Lecture notes

Digital Image Processing by Jorma Kekalainen

Command sequence

F=imread('flowers.tif');
class(F)
size(F)
figure
image(F)
title('flowers.tif')
xlabel('Introduction to Image Processing')
truesize

Jorma Kekalainen

Digital Image Processing

410

RGB (truecolor) images


To determine the color of
the pixel at (2,3), look at
the RGB triplet stored in
(2,3,1:3).
Suppose (2,3,1) contains
the value 0.5176, (2,3,2)
contains 0.1608, and
(2,3,3) contains 0.0627.
The color for the pixel at
(2,3) is

The next figure shows an RGB


image of class double

0.5176 0.1608 0.0627


Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

411

Page 12

Lecture notes

Digital Image Processing by Jorma Kekalainen

True color or RGB images


Matlab handles 24-bit RGB images in much the same way as
grayscale.
We can save the color values to a matrix and view the result:
>> a=imread('autumn.tif');
>> figure,imshow(a)

Jorma Kekalainen

Digital Image Processing

412

True color or RGB images


Note that the pixel values now consist of a list of three values,
giving the red, green and blue components of the color of the
given pixel.
An important difference between this type of image and a
grayscale image can be seen by the command
>> size(a)
ans =
206 345 3
Now a is a three-dimensional matrix, also called a
multidimensional array.
We can think of a as being a stack of three matrices, each of
the same size.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

413

Page 13

Lecture notes

Digital Image Processing by Jorma Kekalainen

RGB values at a given location


To obtain any of the RGB values at a given location, we use
indexing.
For example
>> a(100,200,2)
returns the second color value (green) at the pixel in row
100 and column 200.
If we want all the color values at that point, we can use
>> a(100,200,1:3)
However, Matlab allows a convenient shortcut for listing all
values along a particular dimension; just using a colon on
its own:
>> a(100,200,:)
Jorma Kekalainen

Digital Image Processing

414

Example
>> a(100,200,2)

>> a(100,200,:)

ans =
25

ans(:,:,1) =
75

>> a(100,200,1:3)
ans(:,:,1) =
75

ans(:,:,2) =
25

ans(:,:,2) =
25
ans(:,:,3) =
ans(:,:,3) =
30

Jorma Kekalainen

Lecture weeks 7 and 8

30

Digital Image Processing

415

Page 14

Lecture notes

Digital Image Processing by Jorma Kekalainen

impixel
A useful function for obtaining RGB values is impixel; the
command
>> impixel(a,200,100)
ans =
75 25 30
returns the red, green, and blue values of the pixel at
column 200, row 100.
This command also applies to grayscale images:
>> impixel(c,100,200)
ans =
175 175 175
will return three values, but since c is a single twodimensional matrix, all three values will be the same.
Jorma Kekalainen

Digital Image Processing

416

Note
The order of indexing is opposite to the row,
column order for matrix indexing.

Jorma Kekalainen

Lecture weeks 7 and 8

>> a(100,200,:)
ans(:,:,1) =
75
ans(:,:,2) =
25
ans(:,:,3) =
30
>> impixel(a,200,100)
ans =
75 25 30
>> impixel(a,100,200)
ans =
161 161 155
Digital Image Processing

417

Page 15

Lecture notes

Digital Image Processing by Jorma Kekalainen

R, G, & B bands of a truecolor image


displayed with grayscale colormaps
F=imread('flowers.tif');
figure, imshow(F)
title('F=imread(''flowers.tif'')')
R=F(:,:,1); G=F(:,:,2); B=F(:,:,3); % Component images
figure, imshow(R)
title('R=F(:,:,1)')
figure, imshow(G)
title('G=F(:,:,2)')
figure, imshow(B)
title('B=F(:,:,3)')
GrayF=0.2989*R+0.5870*G+0.1140*B;
figure, imshow(GrayF)
title('GrayF=.2989*R+0.5870*G+0.1140*B')
Grayim=rgb2gray(F);
figure, imshow(Grayim)
Jorma Kekalainen
Digital Image Processing
title('Grayim=rgb2gray(F)')

418

True color image compared to


grayscale image
F=imread('flowers.tif');
figure, imshow(F)
title('F=imread(''flowers.tif'')')
R=F(:,:,1); G=F(:,:,2); B=F(:,:,3); % Component images
GrayF=.2989*R+0.5870*G+0.1140*B; % or GrayF=rgb2gray(F);
figure, imshow(GrayF)
title('GrayF=.2989*R+0.5870*G+0.1140*B')

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

419

Page 16

Lecture notes

Digital Image Processing by Jorma Kekalainen

Component images with grayscale


colormaps and grayscale image
R

Gray
B

Jorma Kekalainen

Digital Image Processing

420

Colormaps
Sometimes, the pixels are quantified to the interval [0,255].
These values are transformed through a colormap in the
computer to
Grayscale values, i.e. 0 black and 255 white or
Arbitrary colors (pseudocolors)

Sometimes, the pixels are floating point values.


These values are transformed to the interval [0,255] and
further through a colormap in the computer.
A true color image has 3 values per pixel.
These values are transformed individually through 3 color
maps in the computer and further to the red, green and
blue channel of the screen.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

421

Page 17

Lecture notes

Digital Image Processing by Jorma Kekalainen

True color map

To D/A-converter and
further to the red
Jorma Kekalainen
channel of the screen.

To D/A-converter and
further
to the green
Digital Image Processing
channel of the screen.

Over 16
million
colors

To D/A-converter and
further to the blue422
channel of the screen.

Read a truecolor image into Matlab

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

423

Page 18

Lecture notes

Digital Image Processing by Jorma Kekalainen

Crop the image


First, select a
region using
the magnifier.

Jorma Kekalainen

Digital Image Processing

424

Crop the image


First, select a
region using
the magnifier.

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

425

Page 19

Lecture notes

Digital Image Processing by Jorma Kekalainen

Crop the image

Jorma Kekalainen

Digital Image Processing

426

Crop the image


>> F=imread('flowers.tif');
>> class(F)
ans =
Uint8
>> size(F)
ans =
362 500 3
Here
Here it
is: it is:
>> figure
>> image(F)
>> title('flowers.tif')
>> xlabel('Introduction to Image Processing')
>> truesize
>> R=F(40:190,330:480,:);
>> figure
>> image(R)
>> truesize
>>
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

Now close the


other image

427

Page 20

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example

Jorma Kekalainen

Digital Image Processing

428

Indexed images

An indexed image consists of a data matrix, X, and a colormap matrix,


map.
map is an m-by-3 array of class double containing floating-point values in
the range [0, 1].
Each row of map specifies the red, green, and blue components of a single
color.
An indexed image uses "direct mapping" of pixel values to colormap
values.
The color of each image pixel is determined by using the corresponding
value of X as an index into map.
Values of X therefore must be integers.
The value 1 points to the first row in map, the value 2 points to the second
row, and so on.
Display an indexed image with the statements
image(X); colormap(map)

Note: A colormap is often stored with an indexed image and is automatically loaded with
the image when you use the imread function. However, you are not limited to using the
Jorma Kekalainen
429
default
colormapuse any colormapDigital
thatImage
youProcessing
choose.

Lecture weeks 7 and 8

Page 21

Lecture notes

Digital Image Processing by Jorma Kekalainen

Structure of an indexed image

The pixels in the image are represented by integers, which are pointers
(indices) to color values stored in the colormap.

The relationship between the values in the image matrix and the
colormap depends on the class of the image matrix. If the image
matrix is of class double, the value 1 points to the first row in the
colormap, the value 2 points to the second row, and so on. If the
image matrix is of class uint8 or uint16, there is an offsetthe
value 0 points to the first row in the colormap, the value 1 points
to the second row, and so on.
The offset is also used in
graphics file formats to
maximize the number of
colors that can be supported.
In the following image, the
image matrix is of class
double. Because there is no
offset, the value 5 points to
Jorma Kekalainen
the fifth
row of the colormap.

Digital Image Processing

430

Intensity images
An intensity image is a data matrix, I, whose values
represent intensities within some range.
An intensity image is represented as a single matrix,
with each element of the matrix corresponding to one
image pixel.
The matrix can be of class double, uint8, or uint16.
While intensity images are rarely saved with a
colormap, a colormap is still used to display them.
In essence, intensity images are treated as indexed
images.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

431

Page 22

Lecture notes

Digital Image Processing by Jorma Kekalainen

Intensity images
To display an intensity image, we can
use the imagesc ("image scale")
function, which enables us to set the
range of intensity values.
imagesc scales the image data to use
the full colormap. Use the two-input
form of imagesc to display an intensity
image.
E.g.:
imagesc(I,clims); colormap(gray);
The second input argument
to imagesc specifies the desired
intensity range. The imagesc function
displays I by mapping the first value in
the range to the first colormap entry,
and the second value to the last
colormap entry. Values in between are
linearly distributed throughout the
remaining colormap colors
Jorma Kekalainen

This figure depicts an


intensity image of class
double.

Digital Image Processing

432

Note
imagesc(C) displays C as an image.
Each element of C corresponds to a rectangular area in the
image.
The values of the elements of C are indices into the current
colormap that determine the color of each patch.
imagesc(...,clims) normalizes the values in C to the range
specified by clims and displays C as an image.
clims is a two-element vector that limits the range of data values in C.

These values map to the full range of values in the current


colormap.

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

433

Page 23

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
We can expand midrange color
resolution by mapping low
values to the first color and
high values to the last color in
the colormap by specifying
color value limits (clims).
If the size of the current
colormap is 81-by-3, the
statements
clims = [ 10 60 ]
imagesc(C,clims)
map the data values in C to
the colormap as shown beside.
Jorma Kekalainen

Digital Image Processing

434

Example

In this example, the left image maps


to the gray colormap using the
statements
>> load clown
figure
subplot(1,2,1)
imagesc(X)
colormap(gray)
axis image
title('Default CLim (= [1 81])')

Jorma Kekalainen

Lecture weeks 7 and 8

The right image has values between


10 and 60 scaled to the full range of
the gray colormap using the
statements
>> subplot(1,2,2)
clims = [10 60];
imagesc(X,clims)
colormap(gray)
axis image
title('CLim = [10 60]')

Digital Image Processing

435

Page 24

Lecture notes

Digital Image Processing by Jorma Kekalainen

Expanding midrange of grayscale


resolution

Jorma Kekalainen

Digital Image Processing

436

Display intensity image


Although it is
conventional to display
intensity images using a
grayscale colormap, it is
possible to use other
colormaps.
For example, the
following statements
display the intensity
image I in shades of
blue and green:
imagesc(I,[10 60]); colormap(winter);
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

437

Page 25

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note

To display a matrix A with an arbitrary range of values as an intensity


image, use the single-argument form of imagesc.
With one input argument, imagesc maps the minimum value of the data
matrix to the first colormap entry, and maps the maximum value to the
last colormap entry.
For example, these two lines are equivalent:
imagesc(A); colormap(gray)
imagesc(A,[min(A(:)) max(A(:))]); colormap(gray)

Jorma Kekalainen

Digital Image Processing

438

Example

>> load clown


figure
imagesc(X)
colormap(map)

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

439

Page 26

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example

Jorma Kekalainen

Digital Image Processing

440

imfinfo('clown.bmp')

imfinfo('clown.bmp')
ans =
Filename: 'C:\Users\ktkekjo\Documents\MATLAB\clown.bmp'
FileModDate: '17-Aug-2015 20:31:42'
FileSize: 65078
Format: 'bmp'
FormatVersion: 'Version 3 (Microsoft Windows 3.x)'
Width: 320
Height: 200
BitDepth: 8
ColorType: 'indexed'
FormatSignature: 'BM'
NumColormapEntries: 256
Colormap: [256x3 double]

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

441

Page 27

Lecture notes

Digital Image Processing by Jorma Kekalainen

Indexed color images


The command
>> imshow('ancienttrees.tif')
produces a nice color image of trees.
If we try saving it to a matrix first and then
displaying the result:
>> AT=imread('ancienttrees.tif');
>> figure,imshow(AT),
we obtain a dark, barely distinguishable image,
with single integer gray values, indicating that AT
is being interpreted as a single grayscale image.
Jorma Kekalainen

Digital Image Processing

442

Example

>> imshow('ancienttrees.tif')

Jorma Kekalainen

Lecture weeks 7 and 8

>> AT=imread('ancienttrees.tif');
>> figure,imshow(AT)

Digital Image Processing

443

Page 28

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
>> whos('AT')
Name
Size
AT
258x350

Bytes Class Attributes


90300 uint8

Jorma Kekalainen

Digital Image Processing

444

Example

load trees
>> T=ind2gray(X,map);
>> imshow(X,map)
>> figure,imshow(T)

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

445

Page 29

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note

load trees
T=ind2gray(X,map);
imshow(X,map)
figure,imshow(T)
figure,imagesc(X)
figure,imagesc(X),colormap(map)

Jorma Kekalainen

Digital Image Processing

446

Imfinfo

>> imwrite(X,map,'ancienttrees.tif')
>> imshow('ancienttrees.tif')
>> imfinfo('ancienttrees.tif')

ans =

Filename:
'C:\Users\ktkekjo\Documents\MATLAB\ancienttrees
.tif'
FileModDate: '23-kes-2015 16:40:36'
FileSize: 75764
Format: 'tif'
FormatVersion: []
Width: 350
Height: 258
BitDepth: 8
ColorType: 'indexed'
FormatSignature: [73 73 42 0]
ByteOrder: 'little-endian'
NewSubFileType: 0
BitsPerSample: 8
Compression: 'PackBits'

Jorma Kekalainen

Lecture weeks 7 and 8

PhotometricInterpretation: 'RGB Palette'


StripOffsets: [1x12 double]
SamplesPerPixel: 1
RowsPerStrip: 23
StripByteCounts: [1x12 double]
XResolution: 72
YResolution: 72
ResolutionUnit: 'Inch'
Colormap: [256x3 double]
PlanarConfiguration: 'Chunky'
TileWidth: []
TileLength: []
TileOffsets: []
TileByteCounts: []
Orientation: 1
FillOrder: 1
GrayResponseUnit: 0.0100
MaxSampleValue: 255
MinSampleValue: 0
Thresholding: 1
Offset: 73930

Digital Image Processing

447

Page 30

Lecture notes

Digital Image Processing by Jorma Kekalainen

Note
AT=imread('ancienttrees.tif');
imshow(AT)

Jorma Kekalainen

[AT,cmap]=imread('ancienttrees.tif');
figure,image(AT)
colormap(cmap)

Digital Image Processing

448

Colormap and index


In fact the image ancienttrees.tif is an example of
an indexed image, consisting of two matrices: a
color map, and an index to the color map.
Assigning the image to a single matrix picks up
only the index; we need to obtain the color map
as well:
>> [AT,map]=imread('ancienttrees.tif');
>> figure,imshow(AT,map)
Matlab stores the RGB values of an indexed
image as values of type double, with values
between 0 and 1.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

449

Page 31

Lecture notes

Digital Image Processing by Jorma Kekalainen

Colormap and index


>> whos
Name
AT
map

Size
258x350
256x3

Jorma Kekalainen

Bytes
90300
6144

Digital Image Processing

Class Attributes
uint8
double

450

Truecolor vs. colormapped image


>> ind(100,100,:) =200
>> ind(98:102,98:102,:)
200 198 200 198 200
198 200 198 103 200
198 200 200 200 200
198 198 200 200 200
198 200 200 103 103

Jorma Kekalainen

Lecture weeks 7 and 8

emap(ind(100,100,:)+1,:)=emap(201,:) = 0.9373 0.3725 0.5843


>> emap(199:203,:)
0.9294 0.4824 0.6902
0.2471 0.2353 0.3882
0.9373 0.3725 0.5843
0.8549 0.8157 0.8118
0.4196 0.3137 0.3451

Digital Image Processing

>> round(255*emap(199:203,:))
237 123 176
63 60 99
239 95 149
218 208 207
107 80 88

451

Page 32

Lecture notes

Digital Image Processing by Jorma Kekalainen

Colormapped vs. Truecolor in


Matlab

0.9020
0.9294
0.2471
0.9373
0.8549
0.4196
0.8902

0.3098
0.6902
0.3882
0.5843
0.8118
0.3451
0.4549

Jorma Kekalainen

red

0.2235
0.4824
0.2353
0.3725
0.8157
0.3137
0.3137

256

ind(100,100,:)+1=201

emap(198:204,:)

Colormap

Number+1 at
pixel location is
an index into a
colormap.

green

blue

Intensity values
are between 0
and 1.

*255 = [ 239 95 149 ]

Digital Image Processing

452

Example

Jorma Kekalainen

24-bit truecolor

Lecture weeks 7 and 8

Digital Image Processing

8-bit colormapped

453

Page 33

Lecture notes

Digital Image Processing by Jorma Kekalainen

Colormapped image, indices, and colormap


>> [AT,map] =imread('ancienttrees.tif');
Indices contained in
AT(98:102,98:102)
95 105 95 93 105
112 105 105 105 105
117 117 112 105 105
112 114 112 112 105
97 111 117 112 112

actual values in
map(112:116,:)
Index+1

0.8392
0.6471
0.8078
0.7098
0.9686

0.7098
0.8078
0.8078
0.8392
0.7098

0.8706
0.9373
0.6118
0.8706
0.8706

255*map(112:116,:)
214
165
206
181
247
Jorma Kekalainen

181
206
206
214
181

222
239
156
222
222

Digital Image Processing

454

Example: Converting a colormapped image


to true color
AT is a mxnx1, 8-bit
image.
Each pixel has a value
between 0 and 255.

map is the colormap that is stored in


ancienttrees.tif along with image. map is a 256x3
type-double matrix, each row of which lists a color
in terms of its R, G, and B intensities, which are
given as fractions between 0 and 1.

>> [AT,map] = imread('ancienttrees.tif');


>> ATtrue = uint8(reshape(map(AT+1,:),[size(AT) 3])*255);

The m x n x 3 matrix of
intensity values is
reshaped into a m x n x
3 image of type double.
The values are scaled
to lie between 0 and
255 then converted to
Jorma Kekalainen
type uint8.

Lecture weeks 7 and 8

By concatenating ATs columns, Matlab rearranges


AT into a m x n x 1 list. Each number in the list
(if it has 1 added to it) refers to a row of the
colormap. Then, map(AT+1,:) produces a m x n x 3
matrix of intensity values of type double between
0 and 1.
Digital Image Processing

455

Page 34

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Converting a colormapped image


to true color
>> [AT,map] = imread('ancienttrees.tif');
ATtrue = uint8(reshape(map(AT+1,:),[size(AT) 3])*255);
class(ATtrue)
size(ATtrue)
figure,imshow(ATtrue)
title('Converted to the true color image')
ans =
uint8
ans =
258 350 3
255*map(112:116,:)
214
165
206
181
247

181
206
206
214
181

222
239
156
222
222

Jorma Kekalainen

Digital Image Processing

456

How to make colormaps

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

457

Page 35

Lecture notes

Digital Image Processing by Jorma Kekalainen

Color bands of a truecolor image


displayed with grayscale colormaps

Jorma Kekalainen

Digital Image Processing

458

Color bands of a truecolor image


displayed with grayscale colormaps
>> I = imread('flowers.tif');

>> Red = I(:,:,1);


>> colormap(kcm);

>> Green = I(:,:,2);


>> colormap(kcm);

>> Blue = I(:,:,3);


>> colormap(kcm);

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

459

Page 36

Lecture notes

Digital Image Processing by Jorma Kekalainen

Color bands of a truecolor image


displayed with tinted colormaps

Jorma Kekalainen

Digital Image Processing

460

Color bands of a truecolor image


displayed with tinted colormaps
>> I = imread('flowers.tif');

>> Red = I(:,:,1);


>> colormap(rcm);

>> Green = I(:,:,2);


>> colormap(gcm);

>> Blue = I(:,:,3);


>> colormap(bcm);

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

461

Page 37

Lecture notes

Digital Image Processing by Jorma Kekalainen

Saving images as files


Assuming that
I contains the image
of the correct class,
that
cmap is a colormap,
and that
image_name is the
file-name that you
want.

Jorma Kekalainen

Digital Image Processing

462

Example

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

463

Page 38

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example: Scramble an image


D = imread('Dee.jpg');
r = randperm(333);%?
c = randperm(500);%?
Scr = D(r,c,:);
figure
image(Scr)
truesize
title('Scrambled Image')
xlabel('What is it?')

What are these


constants?
Jorma Kekalainen

Digital Image Processing

464

Example: Scramble/unscramble
an image
D = imread('Dee.jpg');
r = randperm(333);
The image can be unscrambled
c = randperm(500);
using the row and column
Scr = D(r,c,:);
permutation vectors, r and c.
figure
image(Scr)
truesize
title('Scrambled Image')
xlabel('What is it?')
pause
Unscr(r,c,:)=Scr;
figure
image(Unscr)
truesize
title('Unscrambled Image')

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

465

Page 39

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example

he= imread('he.tif');
r = randperm(300);
c = randperm(480);
Scrambled = he(r,c,:);
figure
image(Scrambled)
truesize
title('Scrambled Image')
xlabel('What is this?')
pause
Unscrambled(r,c,:)=Scrambled;
figure
image(Unscrambled)
truesize
title('Unscrambled Image')

The image can be unscrambled


usingJorma
the Kekalainen
row and column
permutation vectors, r and c.

Digital Image Processing

466

Scrambled/unscrambled

D = imread('Dee.jpg');
rng(2,'twister');
s=rng;
r = randperm(333);
c = randperm(500);
Scr = D(r,c,:);
figure
image(Scr)
truesize
title('Scrambled Image')
xlabel('What is it?')
imwrite(Scr,'Scrambled_Image.bmp',
'bmp');

Scrambled=imread('Scrambled_I
mage.bmp');
rng(2,'twister');
s=rng;
figure, imshow(Scrambled)
title('Scrambled image')
pause
r = randperm(333);
c = randperm(500);
Unscrambled(r,c,:)=Scrambled;
figure
image(Unscrambled)
truesize
title('Unscrambled Image')

Note: rng controls random number generation. Generator = 'twister' referred to the Mersenne
Jorma Kekalainen
Digital Image Processing
467
Twister
generator which is now Matlab startup
generator.

Lecture weeks 7 and 8

Page 40

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example

Jorma Kekalainen

Digital Image Processing

468

Note: rng

Save the current generator settings in s:


s = rng;
Call rand to generate a vector of random values:
First, initialize the random number generator to make the results in this
example repeatable.
rng(1,'twister');
Save the generator settings in a structure, s.
s = rng;
x = rand(1,10)
Restore the original generator settings by calling rng.
Generate a new set of random values and verify that x and y are equal:
rng(s);
y = rand(1,10)

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

469

Page 41

Lecture notes

Digital Image Processing by Jorma Kekalainen

Obtaining information about


graphics files
The imfinfo function enables you to obtain information about
graphics files in any of the standard formats.
The information we obtain depends on the type of file, but it always
includes at least the following:
Name of the file, including the folder path if the file is not in the
current folder
File format
Version number of the file format
File modification date
File size in bytes
Image width in pixels
Image height in pixels
Number of bits per pixel
Image type: RGB (truecolor), intensity (grayscale), or indexed

Jorma Kekalainen

Digital Image Processing

470

imfinfo('ancienttrees.tif')
>> imfinfo('ancienttrees.tif')
ans =
Filename: [1x50 char]
FileModDate: '23-kes-2015 16:40:36'
FileSize: 75764
Format: 'tif'
FormatVersion: []
Width: 350
Height: 258
BitDepth: 8
ColorType: 'indexed'
FormatSignature: [73 73 42 0]
ByteOrder: 'little-endian'
NewSubFileType: 0
BitsPerSample: 8
Compression: 'PackBits'
Jorma Kekalainen

Lecture weeks 7 and 8

PhotometricInterpretation: 'RGB Palette'


StripOffsets: [1x12 double]
SamplesPerPixel: 1
RowsPerStrip: 23
StripByteCounts: [1x12 double]
XResolution: 72
YResolution: 72
ResolutionUnit: 'Inch'
Colormap: [256x3 double]
PlanarConfiguration: 'Chunky'
TileWidth: []
TileLength: []
TileOffsets: []
TileByteCounts: []
Orientation: 1
FillOrder: 1
GrayResponseUnit: 0.0100
MaxSampleValue: 255
MinSampleValue: 0
Thresholding: 1
Offset: 73930

Digital Image Processing

471

Page 42

Lecture notes

Digital Image Processing by Jorma Kekalainen

Information about our image


Much of those information is not useful to us; but we
can see the size of the image in pixels, the size of the
file (in bytes), the number of bits per pixel (this is
given by BitDepth), and the color type (in those case
indexed).
For comparison, let's look at the output of a true
color file (showing only the first few lines of the
output):
>>imfinfo('flowers.tif')
and binary file
>> imfinfo('text.png')
Jorma Kekalainen

Digital Image Processing

472

>> imfinfo('flowers.tif')
>> imfinfo('flowers.tif')
ans =
Filename: [1x45 char]
FileModDate: '22-kes-2015 23:32:10'
FileSize: 547618
Format: 'tif'
FormatVersion: []
Width: 500
Height: 362
BitDepth: 24
ColorType: 'truecolor'
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

473

Page 43

Lecture notes

Digital Image Processing by Jorma Kekalainen

>> imfinfo('text.png')
Now we shall test this function on a binary image:
>> imfinfo('text.png')
ans =
Filename: [1x62 char]
FileModDate: '13-Oct-2002 08:48:20'
FileSize: 1322
Format: 'png'
FormatVersion: []
Width: 256
Height: 256
BitDepth: 1
ColorType: 'grayscale

Jorma Kekalainen

Digital Image Processing

474

Note
Matlab does not distinguish between grayscale and binary
images: a binary image is just a special case of a grayscale
image which has only two intensities.

>> whos
Name
Size
Te
256x256

Jorma Kekalainen

Lecture weeks 7 and 8

Bytes Class Attributes


65536 logical

Digital Image Processing

475

Page 44

Lecture notes

Digital Image Processing by Jorma Kekalainen

Data types and conversions


Elements in Matlab matrices may have a
number of different numeric data types; a few
of them are listed in table below.
These data types are also functions, we can
convert from one type to another.

Jorma
Kekalainen
Digital
Processing
Note:
There
are other data types; see
theImage
help
for datatypes.

476

Example
>> a=23;
>> b=uint8(a);
>> b
b=
23
>> whos a b
Name Size Bytes
Class
a
1x1 8
double array
b
1x1 1
uint8 array
Note: Even though the variables a and b have the same numeric value, they are of
different data types. An important consideration is that arithmetic operations are not
Jorma Kekalainen
Digital Image Processing
477
permitted
with the data types int8, int16,
uint8 and uint16.

Lecture weeks 7 and 8

Page 45

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
>> whos a b
Name Size
a
b

1x1
1x1

Bytes Class

Attributes

8 double
1 uint8

>> a/2
ans =
11.5000
>> b/2
ans =
12
Jorma Kekalainen

Digital Image Processing

478

Note
A grayscale image may consist of pixels whose values
are of data type uint8.
These images are thus reasonably efficient in terms
of storage space, since each pixel requires only one
byte.
Arithmetic operations are not permitted on this data
type; a uint8 image should be converted to double
before arithmetic is attempted.
However, most Image Processing Toolbox functions
accept uint8 and uint16 input.
Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

479

Page 46

Lecture notes

Digital Image Processing by Jorma Kekalainen

uint8 function - converts to 8-bit


unsigned integer

intArray = uint8(array)
converts the elements of an array into unsigned 8-bit (1-byte) integers of
class uint8.
Input argument array is array of any numeric class, such as single or
double.
If array is already of class uint8, the uint8 function has no effect.
Output argument intArray is array of class uint8.
Values range from 0 to 28 1.
The uint8 function maps any values in array that are outside the limit to
the nearest endpoint.
For example,
>> uint8(2^8)
ans =
255

Jorma Kekalainen

Digital Image Processing

480

Converting between different


image types
We can convert images from one image type to
another. Table lists Matlab's functions for converting
between different image types.
Function

Use

Format

rgb2gray

RGB to grayscale

y=rgb2gray(x);

rgb2ind

RGB to indexed

[ind,cmap]=rgb2ind(x);

ind2rgb

Indexed to RGB

y=ind2rgb(ind,cmap);

gray2ind

Grayscale to indexed

[ind,cmap]=gray2ind(x);

ind2gray

Indexed to grayscale

y=ind2gray(ind,cmap);

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

481

Page 47

Lecture notes

Digital Image Processing by Jorma Kekalainen

rgb2gray

% RGB to grayscale y=rgb2gray(x)


I=imread('flowers.tif'); figure, imshow(I)
RGBsize=size(I), title('flowers.tif'), xlabel('Original image')
J=rgb2gray(I);
RGBsize =
figure, imshow(J), Graysize=size(J), title('rgb2gray')
362 500
xlabel('RGB to gray')
Graysize =

362 500

Jorma Kekalainen

Digital Image Processing

482

Note: 4 color

rgb2ind

indsize = 362 500

% RGB to indexed [y,map]=rgb2ind(x)


emap =
[ind,emap]=rgb2ind(I,6);
0.1451
0.7451
figure,imshow(ind,emap), indsize=size(ind),emap
0.7412
title('rgb2ind'), xlabel('Indexed image with 6 colors') 0.2392

0.1176
0.2627
0.5451
0.2588
0.8706 0.6941
0.8706 0.8431

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

0.1412
0.2314
0.6392
0.4000
0.1490
0.8196

483

Page 48

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example
Read and display a truecolor uint8 JPEG image of a nebula.
RGB = imread('ngc6543a.jpg');
figure('Name','RGB Image')
imagesc(RGB)
title('ngc6543a.jpg')
axis tight
zoom(5)

Jorma Kekalainen

Digital Image Processing

484

Example
Convert RGB to an indexed image with 32 colors
[IND,map] = rgb2ind(RGB,32);
figure('Name','Indexed image')
imagesc(IND)
title('Indexed image with 32 Colors')
colormap(map)
axis tight
zoom(5)
Note: [X,map] = rgb2ind(RGB,n) converts the RGB image to an indexed image X using
minimum variance quantization. map contains at most n colors. n must be less than or
65,536.
The input image can be of class uint8, uint16, single, or double. If the length of map is
less than or equal to 256, the output image is of class uint8. Otherwise, the output image
is of class uint16.
Jorma Kekalainen
Digital Image Processing
485
The value 0 in the output array X corresponds to the first color in the colormap.

Lecture weeks 7 and 8

Page 49

Lecture notes

Digital Image Processing by Jorma Kekalainen

imfinfo('ngc6543a.jpg')
>> imfinfo('ngc6543a.jpg')
ans =
Filename: 'C:\Program
Files\MATLAB\R2013a\toolbox\matlab\demos\ngc6543a.jpg'
FileModDate: '01-Oct-1996 16:19:44'
FileSize: 27387
Format: 'jpg'
FormatVersion: ''
Width: 600
Height: 650
BitDepth: 24
ColorType: 'truecolor'

Jorma Kekalainen

Digital Image Processing

486

ind2rgb

% Indexed to RGB y=ind2rgb(x,map)


y=ind2rgb(ind,emap);
figure,imshow(y)
title('ind2rgb')
xlabel('Indexed to RGB using 6 colors')
emap, indsize=size(ind), RGBsize=size(y)
indsize =
362 500
RGBsize =
362 500

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

487

Page 50

Lecture notes

Digital Image Processing by Jorma Kekalainen

gray2ind

% Grayscale to indexed [y,map]=gray2ind(x,map)


[ind,map]=gray2ind(J);
figure, imshow(ind,map)
indsize=size(ind), mapsize=size(map)
title('gray2ind'), xlabel('Gray to indexed')
indsize =
362 500
mapsize =
64 3

Jorma Kekalainen

Digital Image Processing

488

ind2gray

% Indexed to grayscale y=ind2gray(x,map)


y=ind2gray(ind,map);
figure, imshow(y), title('ind2gray')
indsize=size(ind), mapsize=size(map),Graysize=size(y),
xlabel('Indexed to gray')
indsize =
362 500
mapsize =
64 3
Graysize =
362 500

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

489

Page 51

Lecture notes

Digital Image Processing by Jorma Kekalainen

Gray to RGB
z(:,:,1)=J;
z(:,:,2)=J;
z(:,:,3)=J;
figure, imshow(z)
title('Gray to RGB')
xlabel('Gray to RGB')
RGBsize=size(z)
Graysize=size(J)
RGBsize =
362 500
Graysize =
362 500

Note: There is not such a gray2rgb function, which create a color image. This
transform is done by simply replicating the gray values of each pixel: grays in an RGB
Jorma Kekalainen
Digital Image Processing
490
image
are obtained by equality of the
red, green and blue values.

Unique colormap - cmunique

Eliminate duplicate colors in colormap; convert grayscale or truecolor


image to indexed image
Syntax:
[Y,newmap] = cmunique(X,map)
[Y,newmap] = cmunique(RGB)
[Y,newmap] = cmunique(I)

Description:
[Y,newmap] = cmunique(X,map) returns the indexed image Y and associated
colormap, newmap, that produce the same image as (X,map) but with the
smallest possible colormap. The cmunique function removes duplicate rows
from the colormap and adjusts the indices in the image matrix accordingly.
[Y,newmap] = cmunique(RGB) converts the truecolor image RGB to the
indexed image Y and its associated colormap, newmap. The return value
newmap is the smallest possible colormap for the image, containing one entry
for each unique color in RGB.
[Y,newmap] = cmunique(I) converts the grayscale image I to an indexed image
Y and its associated colormap, newmap. The return value, newmap, is the
smallest possible colormap for the image, containing one entry for each
unique intensity level in I.

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

491

Page 52

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example

Eliminate duplicate entries in colormap


Use the magic function to define X as a 4-by-4 array that uses every value
in the range between 1 and 16.
X = magic(4);
Use the gray function to create an eight-entry colormap.
Then, concatenate the two eight-entry colormaps to create a colormap
with 16 entries, map.
In map, entries 9 through 16 are duplicates of entries 1 through 8.
map = [gray(8); gray(8)];
size(map)
ans = 16 3
Use cmunique to eliminate duplicate entries in the colormap.
[Y, newmap] = cmunique(X, map);
size(newmap)
ans = 8 3
cmunique adjusts the values in the original image X so that Y and newmap
produce the same image as X and map.

Jorma Kekalainen

Digital Image Processing

492

Example

figure
image(X)
colormap(map)
title('X and map')

figure
image(Y)
colormap(newmap)
title('Y and newmap')

The input image can be of class uint8, uint16, or double. The class of the output image Y is uint8
if the length of newmap is less than or equal to 256. If the length of newmap is greater than
Kekalainen
Digital Image Processing
493
256, Jorma
Y is of
class double.

Lecture weeks 7 and 8

Page 53

Lecture notes

Digital Image Processing by Jorma Kekalainen

Example

X = magic(4);
map = [gray(8); gray(8)];
size(map)
[Y, newmap] = cmunique(X, map);
size(newmap)
figure
image(X)
colormap(map)
title('X and map')
figure
image(Y)
colormap(newmap)
title('Y and newmap')

Jorma Kekalainen

Digital Image Processing

494

Exercise 1
Test and study all the previously presented
Matlab command sequences.

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

495

Page 54

Lecture notes

Digital Image Processing by Jorma Kekalainen

Exercise 2
Type in the command
>> help imdemos
This will give you a list of, amongst other
things, all the sample PNG images which come
with the Image Processing Toolbox.
(a) Make a list of these sample images, and
(b) for each image determine its type (binary,
grayscale, true color or indexed color), and its
size (in pixels)
Jorma Kekalainen

Digital Image Processing

496

Exercise 3
Pick a grayscale image, e.g., cameraman.tif.
Using the imwrite function,write it to files of
type JPEG, PNG and BMP.
What are the sizes of those files?

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

497

Page 55

Lecture notes

Digital Image Processing by Jorma Kekalainen

Exercise 4

Repeat the previous question with some


(a) a binary image,
(b) an indexed color image,
(c) a true color image.

Jorma Kekalainen

Lecture weeks 7 and 8

Digital Image Processing

498

Page 56

Вам также может понравиться