• Data types: Fundamental data-type in Matlab is array or Matrix. It also consists of integers, doubles, character strings, structures and cells.
• Data Classes
• Even though we work with integer coordinates, the values of pixels are not restricted to be integers in MATLAB. The various data classes supported by MATLAB are:
• Name
• --------
Description
----------------
• double - double precision, floating point numbers (8 bytes per element)
• uint8 -unsigned 8-bit integers in the range [0-255] (1 byte per element)
• uint16 - unsigned 16-bit integers in the range [0,65535]
• uint32 - unsigned 32-bit integers in the range [0,4294967295]
• int8 - singed 8-bit integers in the range [-128,127]
• int16 - singed 16-bit integers in the range [-32768,32767]
• int32 - singed 32-bit integers in the range [2147483648,2147483647]
• single- single precision floating-point numbers (4 bytes per element)
• char - characters (2 bytes per element using Unicode rep.)
• logical - values are 0 or 1 (1 byte per element)
• All numeric computations (first 8 entries in the above table) in MATLAB are done using double quantities.
• uint8 is the frequently used 8-bit image.
•
• The syntax for converting between data classes:
B = data_class_name(A)
• where data_class_name is one of the allowed data classes of MATLAB.
• (eg) Let A is an array of class uint8.
• A double precision array B is obtained as B = double(A).
• Converting any numeric data classes to logical results in an array with logical 1s in locations where the input array had nonzero values and logical 0s in places where the input array contained 0s.
• The toolbox provides the following functions that perform the necessary scaling to convert between image classes and types.
• Name
• --------
Converts Input to:
-----------------------
• im2uint8 uint8
Valid Input Image Data class
-------------------------------------logical,uint8,uint16 and double
• im2uint16 uint16
• mat2gray double (in the range[0,1]) logical,uint8,uint16 and double double
• im2double double
• im2bw logical logical,uint8,uint16 and double uint8,uint16 and double
• Consider a 2 X 2 image f of class double with the following values:
•
• f = -0.5
0.5
0.75
1.5
• Performing the conversion
• >>g = im2uint8(f)
• Yields the result
• g = 0 128
• 191 255
• We see that im2uint8 sets to 0 all values in the input that are less than 0, sets to 255 all values in the input that are greater than 1 and multiplies all other values by 255.
• Rounding the results of the multiplication to the nearest integer completes the conversion.
• Converting an arbitrary array of class double to an array of class double scaled to the range [0,1] is accomplished by using the function mat2gray. Its syntax is:
• g = mat2gray(A, [Amin, Amax])
• where image g has values in the range 0 (black) to 1
(white).
• The specified parameters Amin and Amax are such that values less than Amin in A become 0 in g, and values greater than Amax in A correspond to 1 in g.
• Sets the values of Amin and Amax to the actual minimum and maximum values in A.
• >> f=imread('cameraman.tif');
• >> g=im2double(f);
• >> h=mat2gray(g) ;
• Consider the class uint8 image
• >> h = uint8([25, 50; 128 200]);
• Performing the conversion
• >> g = im2double(h);
• Yields the result
• g = 0.0980
0.1961
• 0.5020
0.7843
• Here conversion is done by simply dividing each value of the input array by 255.
• If the input is of class uint16 the division is by 65535.
• The conversion between binary and intensity image types is done using the function im2bw, whose syntax is:
• g = im2bw(f, T)
• This function produces a binary image g, from an intensity image, f, by thresholding.
• The output binary image g has values of 0 for all pixels in the input image with intensity values less than threshold T, and 1 for all other pixels.
• The value specified for T has to be in the range [0,1], regardless of the class of the input.
• IPT uses a default value of 0.5 for T.
• If the input is an uint8 image, im2bw divides all its pixels by 255 and then applies either the default or a specified threshold.
• If the input is of class uint16, the division is by 65536.
• Let us convert the following double image
• >> f = [1 2; 3 4]
•
• f = 1 2
3 4
• to binary such that values 1 and 2 become 0 and other 2 values become 1.
First we convert it to the range [0,1]:
• >> g = mat2gray(f)
• g = 0 0.3333
• 0.6667 1.0000
• Then we convert it to binary using a threshold, say, of value 0.6:
• >> gb = im2bw(g,0.6)
•
• gb = 0 0
1 1
• We get a binary array directly using relational operators.
• >> gb = f > 2
• gb = 0 0
1 1
Here if the (intensity) value of the matrix is greater than two (threshold), we get a 1 (true) otherwise a 0 (false).
•
•
•
• An array of dimension 1 X N is called a row vector. The elements of such a vector are accessed using one-dimensional indexing. Thus v(1) is the first element of vector v. The elements of vectors in MATLAB are enclosed by square brackets and are separated by spaces or commas.
• >> v = [1 3 5 7 9];
• >>v(2)
• Yields
• ans = 3
• A row vector is converted to a column vector by the transpose operator (.’):
• >> w = v’
• We get
•
• w = 1
3
5
7
9
• To access blocks of elements, we use colon notation. To access the first 3 elements of v:
• >> v(1:3)
• ans = 1 3 5
• We can access the second through the fourth elements
• >> v(2:4)
• ans = 3 5 7
• We can access all the elements from 3rd onwards:
• >> v(3:end)
• ans = 5 7 9
• If v is a vector, writing
• >> v(:)
• Produces a column vector.
• Writing
• >> v(1:end)
• Produces a row vector.
• >> v(1:2:end)
• ans = 1 5 9
• Here 1:2:end says to start at 1, count up by 2 and stop when the count reaches the last element. The steps can be negative:
• >> v(end:-2:1)
• ans = 9 5 1
• We can pick the first, fourth and fifth elements of v using the command
• >> v([ 1 4 5 ])
• ans = 1 7 9
• Matrices in MATLAB are represented as a sequence of row vectors enclosed by square brackets and separated by semicolons. (eg)
• >> A = [ 1 2 3; 4 5 6; 7 8 9]
• Displays a 3 X 3 matrix as:
•
• A = 1 2 3
4 5 6
• 7 8 9
• To select elements in a matrix, we need 2 indices, one for row location and other for column location.
• >> A(2,3) extracts the element in the second row and third column:
• ans = 6
• The colon operator is used in the matrix indexing to select a 2dimensional block of elements out of a matrix. (eg)
• >> C3 = A(:,3)
• C3 = 3
•
• 6
9
• This is analogous to writing A(1:3,3), which picks the third column of the matrix. Similarly, we can extract the second row as:
• >> R2 = A(2, :)
• R2 = 4 5 6
• To extract the top two rows:
• >> T2 = A(1:2, 1:3)
•
• T2 = 1 2 3
4 5 6
• >> A(end, end)
• ans = 9
• >> A(end, end-2)
• ans = 7
•
• >> A(2:end, end:-2:1)
• ans = 6 4
9 7
•
•
• To create a matrix B equal to A but its last column as 0s, we use:
• >> B = A;
• >> B(:, 3) = 0
• B = 1 2 0
4 5 0
7 8 0
• One can use vectors to index into a matrix. (eg)
• >> E = A([1 3], [2 3])
•
• E = 2 3
8 9
• The notation A([a b], [c d]) picks out the elements in A with coordinates (row a, column c), (row a, column d),
(row b, column c) and (row b, column d).
• Thus here we have selected the element in row 1 column 2, the element in row1 column 3, the element in row 3 column 2 and the element in row 3 column 3.
• A single colon as an index into a matrix selects all elements of the array (on a column by column basis) and arranges them in the form of a column vecgtor.
•
•
• >> v = T2(:)
• v = 1
4
2
•
• 5
3
• 6
• This colon is useful when we want to say find the sum of all the elements of a matrix:
• >> s = sum(A(:))
• s = 45
• One can flip the image vertically using the command:
• >> f=imread('cameraman.tif');
• >> fp = f(end:-1:1,:);
• >> imshow(fp)
• We can obtain the section of an image using the command:
• >> fs = f(50:225, 20:200);
• The sub sampled image is obtained using the command:
• >> fss = f(1:2:end, 1:2:end);
• For an array A of size M X N, the command:
• >> k = size(A, 1);
• Gives the size of A along its first dimension
(number of rows in A).
• The second dimension of an array is: size(A, 2) gives the number of columns in A.
• A singleton dimension is any dimension, dim, for which size(A, dim) = 1.
• d = ndims(A) gives the number of dimensions of array A.
• The 7 important array-generating functions are:
• zeros(M,N) – generates an M X N matrix of 0s of class double
• ones(M,N) – generates an M X N matrix of 1s of class double
• true(M,N) – generates an M X N logical matrix of 1s
• false(M,N) – generates an M X N logical matrix of 0s
• magic(M) – generates an M X M “magic square” – an array in which the sum along any row, column or main diagonal is the same
• rand(M,N) – generates an M X N matrix whose entries are uniformly distributed random numbers in the inverval [0,1]
• randn(M,N) – generates an M X N matrix whose numbers are normally distributed (Gaussian) random numbers with mean 0 and variance 1.
• >> A = 2*ones(3,3)
• A = 2 2
•
• 2
2
• >>magic(3)
2
2
•
•
• ans = 8
3
4
2
2
2
1
5
9
6
7
2
•
•
>> B = rand(2, 4)
• B = 0.9501 0.6068 0.8913 0.4565
0.2311 0.4860 0.7621 0.0185
•
• >> B = randn(2,4)
• B = -0.4326 0.1253 -1.1465 1.1892
-1.6656 0.2877 1.1909 -0.0376
• Square brackets with no elements between them create a null matrix.
• (eg) X = []
• If matrix A is an m X n matrix, it can be reshaped into a p X q matrix, if m X n = p X q, with the command reshape(A,p,q). (eg) for a 6 X 6 matrix A
• Reshape(A,9,4) transforms A into a 9 X 4 matrix.
• >> a = [1 2 3 4 5 6; 7 8 9 10 11 12]
•
• a = 1 2 3 4 5 6
7 8 9 10 11 12
•
•
• >> reshape(a,3,4)
• ans = 1 8 4 11
7 3 10 6
2 9 5 12
• A row can be appended to an existing matrix provided the row has same length as the length of the rows of the existing matrix.
•
• The same is true with columns also. The command A =
[A u] appends the column vector to the columns of A, while A = [A; v] appends a row vector v to the row of A.
• 1
• A = 0
0
0
1
0
0
0 , u = [5 6 7]
1
•
•
• 1
• Then, A = [A; u] produces A = 0
0
5
0
1
0
6
0
0
1
7
• A(2,:) = [ ] -
2nd row of matrix A
• A(:, 3:5) = [ ] -
3rd to 5th columns of A deletes the deletes the
• A([1 3], :) = [ ] -
1st and 3rd row of A deletes the
• U(5:length(u)) = [ ] deletes all elements of vector U except 1 through 4.
• eye(m,n) - returns an m by n matrix with 1s along the main diagonal.
• diag(v) = generates a diagonal matrix with vector v on the diagonal
• diag(A) - extracts the diagonal of matrix A as a vector
• diag(A,1) – extracts the first upper off-diagonal vector of matrix A.
• rot90(A)rotates the matrix A by 90degrees
• fliplr(A) flips a matrix A from left to right
• flipud(A) - flips a matrix A from up to down
• tril(A) - extracts the lower triangular part of a matrix A.
• triu (A) - extracts the upper triangular part of a matrix A.
• >> u=linspace(0,20,5)
• produces u = 0 5 10 15 20
• logspace(a,b,n) - generates a logarithmically spaced vector of length n from 10^a to 10^b.
• v = logspace(0,3,4) generates v = [1 10 100 1000].
• Matlab has a set of built-in special matrices such as hadamard, hankel, hilb, invhilb, kron, pascal, toeplitz, vander, magic etc.
• u = v(v >= 15) finds all elements of vector v such that vi ≥
15 and stores them in vector u.
• find – finds indices of non-zero elements of a matrix
• find(x) returns [ 2 3 4] for x = [ 0 3 5 8]
• [r c] = find(A>100) returns the row and column indices i and j of A, in vectors r and c, for which Aij > 100.
• conj(A) produces a matrix with conjugate elements.
• imag(A) extracts the imaginary part of A
• real(A) extracts the real part of A
• >> a = [5+2i 7-4i; 3 -8j]
•
• a = 5.0000 + 2.0000i 7.0000 - 4.0000i
3.0000 0 - 8.0000i
•
• >> conj(a)
• ans = 5.0000 - 2.0000i 7.0000 + 4.0000i
• 3.0000 0 + 8.0000i
• >> imag(a)
• ans = 2 -4
0 -8
• fix – round towards 0.
• fix([-2.33 2.66]) = [-2 2].
• floor – round towards -∞
• floor([-2.33 2.66]) = [-3 2].
• ceil - round towards +∞
• ceil([-2.33 2.66]) = [-2 3].
• round – round towards the nearest integer
• round([-2.32 2.66]) = [-2 3].
• rem - remainder after division, same as fix(a./b.)
• If a = [-1.5 7], b = [2 3], then rem(a,b) = [-1.5 1].
• There are 3 kinds of operators in MATLAB.
They are:
• Arithmetic operators that perform numeric computations.
• Relational operators that compare operands quantitatively and logical operators that perform the functions AND,
OR and NOT.
• Matrix arithmetic operations follow the rules of linear algebra.
• Array arithmetic operations are carried out element by element and can be used with multidimensional arrays.
• The period (dot) character (.) differentiates array operations from matrix operations.
• (eg) A*B is the traditional matrix multiplication whereas
A.*B is the array multiplication and here the output is the same size as A and B.
• But the matrix and array operations are the same for addition and subtraction, the character pairs .+ and ._ are not used.
• Oper.
• -------
• +
• -
• .*
Name
-------
Array and matrix Addition
Array and matrix subtract
Array multiplication
• *
• ./
• .\
• /
• \
• .^
• ^
• .’
• ‘
•
• +
• -
Matrix multiplication
Array right division
Array left division
Matrix right division
Matrix left division
Array power
Matrix power
Vector & matrix transpose
Vector & matrix complex
Conjugate transpose
Unary plus
Unary minus
Matlab function
------------------plus(A,B) minus(A,B) times(A,B) mtimes(A,B) rdivide(A,B) ldivide(A,B) mrdivide(A,B) mldivide(A,B) power(A,B) mpower(A,B) transpose(A) ctranspose(A) uplus(A) uminus(A)
Comments
------------a +b, A + B, or a + A a –b, A – B, or a – A
C=A.*B; C(I,J)=A(I,J)*B(I,J)
A*B, std. matrix multiplicat.
C=A./B; C(I,J)=A(I,J)/B(I,J)
C=A.\B; C(I,J)=B(I,j)/A(I,J)
A/B; A*inv(B)
A\B; inv(A)*B
C(I,J)=A(I,J)^B(I,J)
A.’
A’
+A is same as 0+A.
-A is same as 0-A or -1*A
• Here A and B are matrices or arrays and a and b are scalars. All operands can be real or complex.
•
-----------imadd imsubtract immultiply
Descriptions
---------------
Adds two images or adds a constant to an image.
Subtracts two images or subtracts a constant from an image.
Multiplies two images (between pair of corresponding elements) or multiplies a constant times an image.
Divides two images (between pair of corresponding elements) or imdivide
Divides an image by a constant.
imabsdiffComputes the absolute difference between two images.
imcomplement Complements an image.
imlinecomb Computes a linear combination of two or more images.
The IPT functions support integer data classes whereas the MATLAB math operators require the inputs to be of double type.
• imadd is used when we use additive noise models. It is also used in digital watermarking to embed the watermark image with the cover image.
• imsubtract is used in video processing techniques for motion detection. (ie) we take 2 successive frames of a video and subtract them to find any moving objects.
• immultiply is used when we use the multiplicative noise models. It is also used in digital watermarking to embed the watermark image with the cover image
• imdivide can be used to divide the intensity value of all the pixels of an image by a constant if it is too bright.
• imabsdiff is useful when we want to compress a video. Here the first frame is transmitted as such. For the second frame, we can send only the absolute difference between the first and second frame.
• imcomplement is useful to create a negative of an image and also the positive of an image from its negative
• >> f=imread('bird.gif');
• >> g=imread('lena.gif');
• >> h=imadd(f,g);
• >> imshow(h)
• >> f=imread('bird.gif');
• g=imread('lena.gif');
• h=imsubtract(f,g);
• >> imshow(h)
• >> f=imread('bird.gif');
• g=imread('lena.gif');
• h=immultiply(f,g);
• >> imshow(h)
• >> f=imread('bird.gif');
• g=imread('lena.gif');
• h=imdivide(f,g);
• >> imshow(h)
• >> f=imread('bird.gif');
• g=imread('lena.gif');
• h=imabsdiff(f,g);
• >> imshow(h)
• >> f=imread('lena.gif');
• >> g=imcomplement(f);
• >> imshow(g)
• >> A = [1 2; 3 4];
• >> B = [5 6; 7 8];
• >> C = plus(A,B)
• C= 6 8
• 10 12
• >> E=times(A,B) % does element wise multiplication
• E =5 12
• 21 32
• >> F=mtimes(A,B) % does matrix multiplication
• F =19 22
• 43 50
• >> G=rdivide(A,B) % does element wise division
•
• G = 0.2000 0.3333
0.4286 0.5000
• >> H=ldivide(A,B) % divides B by A – element wise
• H = 5.0000 3.0000
• 2.3333 2.0000
• >> K= mrdivide(A,B) % matrix division of A by B (ie) A*inv(B)
•
• K = 3.0000 -2.0000
2.0000 -1.000
• >> J = mldivide(A,B) % matrix division of B by A (ie) B*inv(A)
• J = -3 -4
• 4 5
• >> L = power(A,B) % array power – A^B
•
• L = 1 64
2187 65536
•
• >> M = mpower(A,2) % one argument should be scalar
• M = 7 10
15 22
• Matlab supports the following relational operators:
• Operator Name
• ---------- -------
• <
• <=
• >
• >=
• ==
• ~=
Less than
Less than or equal to
Greater than
Greater than or equal to
Equal to
Not equal to
• >> A = [1 2 3; 4 5 6; 7 8 9]
• >> B = [0 2 4; 3 5 6; 3 4 9]
• >> A == B
• Ans = 0 1 0
•
• 0 1 1
0 0 1
• Here in locations where corresponding elements of A and B match
1s are obtained otherwise 0s are obtained.
• >> A >= B
• ans = 1 1 0
•
• 1 1 1
1 1 1
• Produces a logical array with 1s where the elements of A are greater than or equal to the corresponding elements of B and 0s elsewhere.
• Matlab supports the following logical operators:
•
• Operator
• ----------
&
Name
-------
AND
•
• ~
| OR
NOT
• These operators can operate on both logical and numeric data.
• Matlab treats a logical 1 or nonzero numeric quantity as true and a logical 0 or numeric 0 as false in all logical tests.
• >> A = [ 1 2 0; 0 4 5]
• >> B = [ 1 -2 3; 0 1 1]
• >> A & B
• ans = 1 1 0
• 0 1 1
• And operation produces a 1 at locations where both operands are nonzero and 0s elsewhere.
•
Functions
----------xor (exclusive OR) all any
Description
-------------xor function returns a 1 only if both operands are different; otherwise xor returns a 0.
It returns a 1 if all elements in a vector are nonzero; otherwise it returns a 0. It operates columnwise on matrices.
It returns a 1 if any of the elements in a vector is nonzero; otherwise any returns a 0. It operates columnwise on matrices.
>> A = [1 2 3; 4 5 6]
>> B = [0 -1 1; 0 0 2]
>> xor(A,B) ans = 1 0 0
1 1 0
>> all(A) ans = 1 1 1
>> any(B) ans = 0 1 1
• Function Value returned
• ---------------------------
• i or j Imaginary unit, as in 1 + 2i
• NaN or nan Not-a-Number (eg 0/0)
• pi 3.14159265358979
The eval function
• This function evaluate text strings and execute them if they contain Matlab commands.
• (eg) eval(‘x = 5*sin(pi/3)’)
• x = 4.3301
• It is same as typing x = 5*sin(pi/3) at command prompt.
Important built-in-functions for character string manipulations are: findstr – finds the specified substring in a given string
>> s='Vellore Institue of Technoloyg'
>> findstr(s,'of') ans = 18 int2str – converts integers to strings
>>int2str(‘Ram’) ans = 82 97 109 strncmp – compares the first n characters in a given string strcat – concatenates strings horizontally ignoring trailing blanks lower – converts any upper case letters in the string to lower case.
>> lower('VIT') ans = vit