Matlab preparation

68
MATLAB Presented By S.Rakoth Kandan

description

 

Transcript of Matlab preparation

Page 1: Matlab preparation

MATLAB Presented By

S.Rakoth Kandan

Page 2: Matlab preparation

MATLAB Stands for MATrix Laboratory.

Program for doing numerical computation.

Originally designed for solving linear algebra type problems using matrices.

Page 3: Matlab preparation

Command Window type commands

Current Directory View folders and m-files

Workspace View program variables Double click on a variable to see it in the Array Editor

Command History view past commands save a whole session using diary

Page 4: Matlab preparation

Image Types:4 Basic types of images are supported in

MATLAB:Gray-scale Images = uint 8 [0,255], uint16[0,65535],

int16[-32768,32767], single, double [0,1]

Binary Images = Logical Array 0s and 1s.

Indexed Images = uint8 or 16,int16,logical,single or double. M-by-3 of class double

RGB Images. M-by-n-by-3 uint8,uint16,single or double

Page 5: Matlab preparation

Image co-ordinate system:

Pixel co-ordinate system:Express location in an image to use pixels.

Image is treat as grid of discrete systems.

Top to Bottom(Row) and Left to Right(Column).

Integer values & range from 1,2,3 on both row and column Example: I(2,3).. 2-Row, 3-Column.

Page 6: Matlab preparation

Spatial co-ordinate system:

In this system pixel is treated as discrete.

Instead of row and column we are using the X & Y.

Location of image are position on a plane.

Pixel coordinate system is discrete and spatial coordinate system is continuous system. Ranges from 0.5 & 0.5 on both X & Y planes is possible.

Page 7: Matlab preparation

Non-Default Spatial co-ordinate system.

In some situations we may want to use this kind of systems.

We are choosing this system when the image point is (19.0,7.5) rather than (0.5,0.5)

In this system we have to specify the Xdata and Ydata when we display the image. The default value is Xdata is [1 size(A,2)] and Ydata is [1size(A,1)] .

Page 8: Matlab preparation

Spatial Domain Techniques:

In this we are directly dealing with image pixels.

The pixels are manipulated to achieve desired enhancement.

The value of a pixel with coordinates (x;y) in the enhanced image ‘F’ is the result of performing some operation of the pixels in the neighborhood of (x:y) in the input image ‘f’.

Page 9: Matlab preparation

Frequency Domain Technique:

In frequency domains image is first transferred into frequency domain.

Fourier Transform of the image is computed first.

All the enhancement operations are performed on the fourier transform of the image and then the inverse fourier transform is performed to get the resultant image.

Page 10: Matlab preparation
Page 11: Matlab preparation

Display Indexed Image:An indexed image consists of a data matrix, X, and a colormap matrix ,map.

imshow(X,map) (or)

imtool(X,map)

Display Grayscale Image:

imshow(i) (or)

imtool(i)

Page 12: Matlab preparation

Display Binary Image:In a binary image,each pixel assumes one of only two discrete values :0(off) and 1(on).

BW=imread(‘circles.png’);imshow(BW) (or)imtool(BW)

Display RGB Image:RGB is stored in MATLAB as an m-by-n-by-3 data where each my-by-n page defines R,G,B components of each pixel.

RGB=imread(‘peppers.png’);imshow(RGB)

Page 13: Matlab preparation

How to read the image :

close all I=imread(‘pout.tif’);

How to show the image:

Imshow(I)

How the image appears in workspace: whos

Page 14: Matlab preparation

Cntd…

image - Create and display image object (MATLAB).

imagesc - Scale data and display as image(MATLAB).

colorbar - Display colorbar (MATLAB).colormap - Sets the color map of the image.montage - Display multiple image frames.truesize - Adjust display size of image.warp - Display image as texture-mapped

surface.

Page 15: Matlab preparation

Color Space of RGB and HSVThere are two main types of color spaces that are used with images: RGB and Hue-Saturation- Value(HSV).

Page 16: Matlab preparation

Importing and Exporting Images in MATLABImage Processing Toolboximfinfo- Returns info about graphics file.imread - Read image from graphics file.imwrite- Write image to graphics file.

Example:imfinfo(‘canoe.tif’)[X, map] = imread(‘canoe.tif’);imshow(X, map);imwrite(X, map, ‘canoe2.bmp’);

Page 17: Matlab preparation

Image EnhancementOne of the most basic ways to enhance an

image is to change its brightness and its contrast, and this can be done is by working with the image's histogram.– By stretching the color distribution– By equalizing the distribution of colors to use the full range– By adjusting the scaling of the colors

If you are separating an object from its background, thresholding is a technique that could be used as well.

Page 18: Matlab preparation

Improve Image Contrast:

figure,imhist(I);I2=histeq(I2)

Dividing a figure window into multiple display:

[X1,map1]=imread(‘forest.tif’);[X2,map2]=imread(‘trees.tif’);subplot(1,2,1),imshow(X1,map1);subplot(1,2,2),imshow(X2,map2);

Page 19: Matlab preparation

Use the sub image function to display multiple images:

[X1,map1]=imread(‘forest.tif’);[X2,map2]=imread(‘trees.tif’);figure,subplot(1,2,1),imshow(X1,map1);figure,subplot(1,2,2),imshow(X2,map2);

Page 20: Matlab preparation

False Contouring:a=imread(‘nature.jpg’);Imshow(a),title(‘original image’);

figure,imshow(grayslice(a,128),gray(128));Title(‘Image with 128 gray level’)figure,imshow(grayslice(a,64),gray(64));Title(‘Image with 64 gray level’)figure,imshow(grayslice(a,32),gray(32));Title(‘Image with 32 gray level’)figure,imshow(grayslice(a,16),gray(16));Title(‘image with 16 gray level’)

Page 21: Matlab preparation

Image Alignment:

When the alignment is off in an image, you can apply some basic spatial transformation techniques.

Rotate the image (imrotate)Crop the image (imcrop)Resize the image (imresize)

With the imtransform function, you can transformyour image to any geometric shape as well.

Page 22: Matlab preparation

Image Rotation:Syntax: B = imrotate(A,angle,method)

B = imrotate(A,angle,method,'crop')

B – Output imageA – Input imageangle – Degrees of rotation in the counter

clockwise directionmethod – Type of interpolation:

[{nearest}, bilinear, bicubic]'crop' – Returns only central portion of B which isthe same size as A.

Page 23: Matlab preparation

Rotate an image:i=imread(‘circuit.tif’);j=imrotate(I,35,’bilinear’);imshow(i)figure,imshow(j)

Image cropping:

i=imread(‘circuit.tif’);j=imcrop(i);

Page 24: Matlab preparation

Noise: Reducing NoiseWhere does noise come from?• Scanner resolution• Film grain (granularity)• Hardware (interference patterns)Common types of noise:• Whitenoise (Gaussian)• Local variance (Gaussian with intensity-

dependent variance)• Salt and pepper• Speckle

Page 25: Matlab preparation

Filter: A filter can be used to reduce the effect of noise

in an image. The Image Processing Toolbox provides three main methods of filtering:

• Linear filtering• Median filtering• Adaptive filtering

Different methods are better for different kinds of noise.

In the following section we will investigate the types of methods, and what type of noise they are most effective in reducing.

Page 26: Matlab preparation

How Do I Model Noise?The function imnoise allows different types of

noise to be modeled.Syntax:

J = imnoise(I,type,parameters)I – Image

type – gaussian, localvar, poisson, salt & pepper, speckle

parameters – additional parameters needed given the type of noise

Page 27: Matlab preparation

Linear FilteringA linear filter computes each output pixel value according to a linear combination of the input pixel's neighborhood.

The basics of linear filtering are done through correlation and convolution.

In the Image Processing Toolbox both these operations are performed using the imfilter command

Page 28: Matlab preparation

Filtering using imfilterSyntax

B = imfilter(A,H)B = imfilter(A,H,option1,option2,...)

A – Input imageH – The filter, also known as the correlation or

convolution kernel.options – Boundary options, output size option,correlation and convolution optionNote: By default imfilter performs correlation.

Page 29: Matlab preparation

Special Linear FiltersThe function fspecial creates a variety of 2-D

filters.Syntax:

h = fspecial(type, parameter)h – two-dimensional correlation kernel type – one of the specified special filter types:gaussian,sobel,prewitt,laplacian,log,motion,av

erage, circular averaging(disk), and a contrast sharpening (unsharp) filter

parameters – particular to the type of filter chosen

Page 30: Matlab preparation

Median Filtering:When noise causes the pixels to vary greatly from the original value (salt and pepper), a median filter is more effective in reducing the noise.

Syntax:

B = medfilt2(A,[m n])A – Input imageB – Output image[m n] – Neighborhood block size to be used to

calculate the median.

Page 31: Matlab preparation

Adding Noise to image:i=imread(‘eight.tif’);imshow(i)j=imnoise(I,’salt&pepper’,0.02);figure,imshow(j)

Noise removing using Average & Median Filter:i=imread(‘eight.tif’);imshow(i)j=imnoise(I,’salt&pepper’,0.02);figure,imshow(j)k=filter2(fspecial(‘average’,3),j)/255;figure,imshow(k)l=medfilt2(j,[3 3]);figure,imshow(l)

Page 32: Matlab preparation

Adaptive FilterThe wiener2 adaptive filter tailors itself to the local image variance adaptively. If the variance is large, it minimally smoothes the image. If the variance is small, it performs more smoothing. This type of filter is effective in reducing the effects of Gaussian white noise.

Syntax: [J,noise] = wiener2(I,[m n],noise)

I – Input image[m n] – Size neighborhood block used to

calculate the median.J – Output image, noise – Noise variance

Page 33: Matlab preparation

Noise removing by Adaptive Filter:

RGB=imread(‘saturn.jpg’);i=rgb2gray(RGB);j=imnoise(I,’gaussian’,0,0.025);imshow(j)k=wiener2(j,[5 5]);figure, imshow(k)

Page 34: Matlab preparation

Edge Detection:i=imread(‘coins.png’);imshow(i)BW1=edge(i,’sobel’);BW2=edge(I,’canny’);imshow(BW1)figure,imshow(BW2)

Page 35: Matlab preparation

Image Negative: i=imread('rakoth.jpg');

figure,imshow(i);IM2=imcomplement(i);figure,imshow(IM2)

Pixel region tool in the image:himage=imshow(‘pout.tif’);

hpixelinfopanel=impixelinfo(himage);

hdrangepanel=imdisplayrange(himage);hpixreg=impixelregion(himage);

Page 36: Matlab preparation

Image Dithering:

rgb=imread('rose.jpg');figure,imshow(rgb)

[X_no_dither,map]=rgb2ind(rgb,8,'nodither'); figure,imshow(X_no_dither,map);[X_dither,map]=rgb2ind(rgb,8,'dither');figure,imshow(X_dither,map)

Page 37: Matlab preparation

Histogram:A histogram of an image shows the current level of contrast (the distribution of gray levels).

Histogram Equalization:The histeq function can be used to equally

distribute the histogram and enhance the contrast.

i=imread('rose.jpg'); j=rgb2gray(i); k=histeq(j); imshow(i) figure,imshow(j)

figure;imhist(k)

Page 38: Matlab preparation

Histogram Adjustment:

Intensity adjustment is a technique for mapping an image's intensity values to a new range (imadjust).

I = imread('cameraman.tif');J = imadjust(I,[0 0.2],[0.5 1]); imshow(I)figure, imshow(J)

Page 39: Matlab preparation

Create a adaptive histogram equalization:

i=imread('Rose.jpg');j=rgb2gray(i);

k=adapthisteq(j,'clipLimit',1,'Distribution','rayleigh');

figure,imshow(i);figure,imshow(j);figure,imshow(k);

Page 40: Matlab preparation

Line Detection:

i=imread(‘circuit.tif’);roti=imrotate(I,33,’crop’);figi=imshow(roti);BW=edge(roti,’canny’);figure,imshow(BW);[H,theta,rho] = hough(BW);

Page 41: Matlab preparation

Linear Filtering:

I = imread(‘peppers.png');h = ones(5,5) / 25;I2 = imfilter(I,h);imshow(I), title('Original Image');figure, imshow(I2), title('Filtered

Image')

Page 42: Matlab preparation

Image Arithmetic:

With just simple addition, subtraction, multiplication and division a number of different image processing techniques can be implemented.

With addition and multiplication an image contrast can be increased that facilitates edge detection process.

With subtraction and division changes can be detected from one image to another.

Page 43: Matlab preparation

imabsdiff - Compute absolute difference of two images

imadd - Add two images or add constant to image

imcomplement - Complement image

imdivide - Divide two images or divide image by a constant

imlincomb - Compute linear combination of images

immultiply - Multiply two images.

imsubtract - Subtract two images.

Page 44: Matlab preparation

Brightness Enhancement:

Image addition makes it possible to superimpose an image on top of another or control the brightness of an image.Each resulting pixel is the sum of the respective pixels of the two images, of the same size and of the same class.

a=imread('amaze.jpg'); b=double(a)+50; figure,imshow(a);figure,imshow(uint8(b));

Page 45: Matlab preparation

Brightness Suppression: a=imread('face.jpg');b=double(a)-50;figure,imshow(a);figure,imshow(uint8(b));

Image Multiplication:imread(‘moon.tif’);J = immultiply(I, 1.2);subplot(1,2,1),imshow(I)subplot(1,2,2),imshow(J)

Page 46: Matlab preparation

Image Subtraction

Can you see anything different about the two images?

Page 47: Matlab preparation

Using subtraction, you can identify the following differences

[im1, map1] = imread(‘change1.gif’); [im2, map2] = imread(‘change2.gif’);im_diff = imsubtract(im1, im2);imshow(im_diff)colormap(jet)set(gca, ‘clim’, [0 60]);

Page 48: Matlab preparation

Divide an image by a constant factor:

I = imread('rice.png'); J = imdivide(I,2);subplot(1,2,1), imshow(I)subplot(1,2,2), imshow(J)

Page 49: Matlab preparation

IMAGE CONVERSION:

ind2gray – indexed image to intensity image.ind2rgb – indexed image to RGB image.gray2ind – intensity image to indexed image.rgb2gray – RGB image or colormap to grayscale.rgb2ind – RGB image to indexed image.

mat2gray – matrix to intensity image.im2bw – image to binary image by thresholding.im2double – image array to double precision.im2uint8 – image array to 8-bit unsigned integers.im2uint16 – image array to 16-bit unsigned

integers.

Page 50: Matlab preparation

Grayscale image into indexed images:

I = imread('cameraman.tif');[X, map] = gray2ind(I, 16);imshow(X, map);

Convert image into double:

RGB=imread(‘rose.jpg’);RGB2=im2double(RGB);

Convert image into 16-bit signed integers:

i=imread(‘car.jpg’);i2=im2int16(i);

Page 51: Matlab preparation

RGB 2 Gray Conversion:

i=imread('office.jpg');j=rgb2gray(i);figure,imshow(i);figure,imshow(j);figure,imhist(j);

Page 52: Matlab preparation

Convert image into single:

i=imread(‘cat.jpg’);i2=im2single(i)

To get information about image:

h = imshow('bag.png');info = imfinfo('bag.png');imageinfo(h,info);

Page 53: Matlab preparation

Convert RGB image into indexed:

i=imread('nature.jpg'); [X,map]=rgb2ind(i,24,'dither'); figure,imshow(X,map)figure,imshow(X,map)

Image Resize:

I = imread('rice.png');J = imresize(I, 0.5);figure, imshow(I), figure, imshow(J)

Page 54: Matlab preparation

Resize an indexed image:

[X, map] = imread('trees.tif');[Y, newmap] = imresize(X, map,

0.5);imshow(Y, newmap)

Resize an RGB image:

RGB = imread('peppers.png');RGB2 = imresize(RGB, [64 NaN]);

Page 55: Matlab preparation

Add Constant Image:

I = imread('rice.png');J = imadd(I,50);subplot(1,2,1), imshow(I) subplot(1,2,2), imshow(J)

Page 56: Matlab preparation

Region-Based ProcessingRegion-based processing allows you to select a region of interest (ROI), and process only upon the selected area. A ROI is defined using a binary mask – The mask contains 1's for all pixels that are part of the region of interest and 0's everywhere else.

Types of region-based processing that can be done:Specify a region of interest (roipoly, roicolor)Filter a region (roifilt2)Fill in a region (roifill)

Page 57: Matlab preparation

Specifying a Region of InterestA region of interest can be specified using one of the Image Processing functions or with any user defined binary mask.

The options are:Using roipoly, allows you to specify a polygonal region of interest. When called with no inputs a cursor can be used to create a polygon.Using roicolor, where you can define the regionof interest based on a color or intensity range.Using Boolean indexing to create a binary mask.

Page 58: Matlab preparation

Filling ROI:load treesI = ind2gray(X,map);imshow(I)I2 = roifill;imshow(I2)

Page 59: Matlab preparation

Circular Correlation:

x=[5 10;15 20];h=[3 6;9 12];h1=fliplr(h);h2=flipud(h1);x1=fft2(x);h3=fft2(h2);y1=x1.*h3;y2=ifft2(y1);

Page 60: Matlab preparation

Interchange Between Two Images:a=imread('face.jpg');

b=imread('ship.jpg');

ffta=fft2(double(a));

fftb=fft2(double(b));

mag_a=abs(ffta);

ph_a=angle(ffta);

mag_b=abs(fftb);

ph_b=angle(fftb);

newfft_a=mag_a.*(exp(i*ph_a));

newfft_b=mag_b.*(exp(i*ph_b));rec_a=ifft2(newfft_a);

rec_b=ifft2(newfft_b);

Page 61: Matlab preparation

Inverse 2fft:

a=imread('bulb.jpg');[m n]=size(a);b=fft2(a)c=(1/(m*n))*fft2(b);subplot(2,2,1),imshow(a)subplot(2,2,2),imshow(uint8(c))

Page 62: Matlab preparation

Logarithmic Transformation Code:

a=imread(‘face.jpg’);L=255;c=L/log10(1+L);d=c*log10(1+double(a));figure,imshow(a);figure,imshow(uint8(d));

Page 63: Matlab preparation

Unsharp Masking:

a=imread(‘bulb.jpg’);h=fspecial(‘unsharp’);b=imfilter(a,h);figure,imshow(a);figure,imshow(b);

Page 64: Matlab preparation

Blur Image:

a=imread('flight.jpg');b=rgb2gray(a);h=fspecial('motion',10,25);MotionBlur_b=imfilter(b,h,'replicate');figure,imshow(a);figure,imshow(MotionBlur_b)

Page 65: Matlab preparation

Morphology & SegmentationOne way we can solve the problem of identifying objects is using morphological techniques to segment the objects.

Morphology – technique used for processing image based on shapes.

Segmentation – the process used for identifyingobjects in an image.

Page 66: Matlab preparation

Structuring ElementTo process an image according to a given shape,

we need to first define the shape, or structuring element.

The Image Processing Toolbox provides a function for creating a structuring element that can be used, strel.

Syntax SE = strel(shape,parameters)SE – Structuring elementshape – Flat ['arbitrary' 'pair' 'diamond‘,'disk'

'rectangle' 'line' 'square''octagon'],Nonflat['arbitrary']

parameters – Associated with the selected shape

Page 67: Matlab preparation

Morphological:

a=imread('office.jpg');b=[1 1 1;1 1 1;1 1 1];a1=imdilate(a,b);a2=imerode(a,b);figure,imshow(a1);figure,imshow(a2)

Page 68: Matlab preparation

Opening & Closing:

a=imread('light.jpg');b=[1 1 1;1 1 1;1 1 1];a1=imopen(a,b);a2=imclose(a,b);figure,imshow(a1);figure,imshow(a2);