image processing using matlab – learning tool

70
IMAGE PROCESSING USING MATLAB – LEARNING TOOL LO SHING LOONG UNIVERSITI TEKNOLOGI MALAYSIA

Upload: skypillar88

Post on 03-Apr-2015

3.652 views

Category:

Documents


4 download

TRANSCRIPT

Page 1: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

IMAGE PROCESSING USING MATLAB – LEARNING TOOL

LO SHING LOONG

UNIVERSITI TEKNOLOGI MALAYSIA

Page 2: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

“I declare that this thesis entitled “Interference from HAPS Ground Station to a Radio-

relay station” is the result of my own research except as cited in the references. The

thesis has not been accepted for any degree and is not concurrently submitted in

candidature of any degree”.

Signature : ……………………..

Name : CHAN MING YIAN

Date : 20 MAY 2009

DECLARATION OF THESIS / UNDERGRADUATE PROJECT PAPER AND COPYRIGHT

Author’s full name :LO SHING LOONG Date of birth :8thFEBRUARY 1987

Title :IMAGE PROCESSING USING MATLAB – LEARNING TOOL

Academic Session : 2009/2010 I declare that this thesis is classified as :

CONFIDENTIAL (Contains confidential information under the Official Secret Act 1972)*

RESTRICTED (Contains restricted information as specified by the

organisation where research was done)*

OPEN ACCESS I agree that my thesis to be published as online open access (full text)

I acknowledged that Universiti Teknologi Malaysia reserves the right as follows :

1. The thesis is the property of Universiti Teknologi Malaysia. 2. The Library of Universiti Teknologi Malaysia has the right to make copies

for the purpose of research only. 3. The Library has the right to make copies of the thesis for academic

exchange.

Certified by :

____870208055131 DR. YUSRI YUNUS_ (NEW IC NO. /PASSPORT NO.) NAME OF SUPERVISOR Date : APRIL 2010 Date : APRIL 2010

NOTES : * If the thesis is CONFIDENTIAL or RESTRICTED, please attach with the letter from the organisation with period and reasons for confidentiality or restriction.

Page 3: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

“I hereby declare that I have read this thesis and in my

opinion this thesis is sufficient in terms of scope and quality for

the award of the degree of Bachelor of Electrical Engineering ”

Signature :

Name of Supervisor : DR. YUSRI YUNUS

Date : APRIL 2010

Page 4: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

IMAGE PROCESSING USING MATLAB – LEARNING TOOL

LO SHING LOONG

A thesis submitted in fulfillment of the requirements for the award of the degree of

Bachelor of Engineering (Telecommunication)

Faculty of Electrical Engineering

Universiti Teknologi Malaysia

APRIL 2010

Page 5: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

ii

DECLARATION

“I declare that this work as the product of my own effort with the exception of

excerpts cited form other works of which the sources were duly noted”

Signature :

Author’s Name :Lo Shing Loong

Date : April 2010

Page 6: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

iii

DECLARATION

Dedicated, in thankful appreciation for support, encouragement and

understandings to my beloved mother, father, brothers and sisters.

Page 7: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

iv

ACKNOWLEDGEMENT

First and foremost, I would like to express my heartily gratitude to my

supervisor, Dr. Yusri Yunus for the guidance and enthusiasm given throughout the

progress of this project.

My appreciation also goes to my family who has been so tolerant and supports

me all these years. Thanks for their encouragement, love and emotional supports that

they had given to me.

.

Page 8: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

v

ABSTRACT

The purpose for this study is to investigate a software application that can show

how the image is process in computer platform. The process will be done in converting

the picture to matrix model by using MATLAB program. Picture will be shown when

program is running successfully. Real image or picture will be resulted from the matrix

using the function in the MATHLAB. User can use varies of functions such as filter or

rotate depending on the user itself. In this study, the picture or real image used is from

Internet, scanner and etc. Basic mathematical calculation does not apply in this project

as it only used MATHLAB program. The significant of this project is to educated user to

learn how the image can be changes after the function indicated by the program.

Page 9: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

vi

ABSTRAK

Tujuan kajian ini adalah untuk mencari suatu aplikasi perisian yang dapat

menunjukkan bagaimana imej di proses dalam platform komputer. Proses ini akan

dilakukan dalam menukar imej-imej untuk model matriks dengan menggunakan

program MATLAB. Imej akan dipaparkan ketika program ini beroperasi dengan

jayanya. Imej tulen atau gambar akan dihasilkan dari matriks menggunakan fungsi di

MATHLAB. Pengguna boleh menggunakan fungsi bervariasi seperti penapis atau lain-

lain, bergantung pada pengguna itu sendiri. Dalam kajian ini, imej atau bayangan nyata

yang digunakan adalah dari Internet, scanner, dan lain-lain Dasar perhitungan matematik

tidak berlaku dalam projek ini kerana hanya menggunakan program MATHLAB.

Pengguna dididik untuk mempelajari bagaimana imej boleh berubah setelah melalui

berbagai fungsi yang ditunjukkan oleh program.

Page 10: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

vii

TABLE OF CONTENTS

CHAPTER TITLE PAGE

TITLE OF RESEARCH i

DECLARATION ii

ACKNOWLEDGEMENT iv

ABSTRACT v

TABLE OF CONTENT vii

LIST OF TABLE x

LIST OF FIGURES xi

1 INTRODUCTION

1.1 Introduction 1

1.2 Objective of The Project 3

1.3 Scope of Project 3

1.4 Outline of Thesis 3

1.5 Summary of Work 4

Page 11: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

viii

2 THEORETICAL BACKGROUND FOR IMAGE

PROCESSING

2.1 Introduction 8

2.2 Histogram 9

2.3 Blur/Deblurring Image Using Blind Deconvolution

Algorithm

9

2.4 Threshold/Edge Detection 9

2.5 Enhancing Multispectral Color Composite Images 10

2.6 Identify Round Object

2.7 Digital Filters

2.8 Low Pass Filter

2.9 High Pass Filter

10

11

11

14

3 METODOLOGY

3.1 Introduction 17

3.2 Blur/Deblurring Image Using Blind Deconvolution

Algorithm

3.3 Enhancing Multispectral Color Composite Images

Threshold / Edge Detection

19

20

3.4 Threshold / Edge Detection 20

3.5 Identify the Round Object

3.6 Rotate

3.7 Open Image

3.8 Reset

3.9 Save Image

3.10 Show Original Picture

21

22

23

24

24

25

Page 12: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

ix

4 RESULT AND DISCCUSION

4.1 Introduction 26

4.2 GUI (Graphical User Interface) 27

4.3 Image Processing Result 29

5 CONCLUSION AND RECOMMENDATION

5.1 Conclsion 35

5.2 Problems 36

5.3 Recommendation 37

REFERENCES 38

APPENDICES A 39

APPENDICES B 43

Page 13: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

x

LIST OF TABLES

TABLE NO TITLE PAGE

2.1

Effect of increasing the size of the neighborhood region

14

Page 14: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

xi

LIST OF FIGURES

FIGURE NO.

1.1

TITLE

Process block

PAGE

4

1.2 Gantt Chart of the project schedule for semester 1 6

1.3 Gantt Chart of the project schedule for semester 2 7

2.1 Filter 12

2.2 Coefficient values of low pass filter 13

2.3 Effect of low pass filter (a) matrix with bad element (b) matrix

after low pass filter

14

2.4 High pass filter coefficient set for 3x3 matrix convolution mask 15

2.5 Mask, data and element 16

3.1 Processing block 18

4.1 Step planning 26

4.2 layout of image processing program 29

4.3 Image opened in program 30

4.4 Image after simulated with blur and nois 30

4.5 Image after deblurred 31

4.6 Image enhanced after blurred 31

4.7 Image enhance after deblurred 32

4.8 Image rotated 32

4.9 Original image after threshold 33

4.10 Enhanced image after threshold 33

4.11 Original and modified image shows together 34

Page 15: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

CHAPTER I

INTRODUCTION

1.1 Introduction

Image processing is any form of signal processing for which the input is an

image, such as photographs; the output of image processing can be either an image or a

set of characteristics or parameters related to the image. Most image-processing

techniques involve treating the image as a two-dimensional signal and applying standard

signal-processing techniques to it. Image processing – converting the image to another

form by using direction in MATLAB/Toolboxes/Image Processing tables for example is

image input/output, color operation, image enhancement/ analysis and another method.

Image processing and computer vision practitioners tend concentrate on a

particular area of specialization. People refer to their research interests as “texture”,

“surface mapping”, “video tracking”, and the like. Nevertheless, there is a strong need to

appreciate the spectrum and hierarchy of processing levels.

Image processing is the manipulation of the image by using a computer, with the

objective to enhance or evaluate some aspect of an image which is not readily apparent

in its original form. This is done through the development and implementation of

processing means necessary to operate on the image. Processing image using a digital

computer provides the greatest flexibility and power for general image processing

Page 16: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

2

application, since the programming of a computer can be changed easily which allows

operation to be modified quickly.

Interest in image processing technique dates back to early 1920’s when digitized

pictures of world news events were first transmitted by submarine cable between

Newyork and London. However, application of digital image processing concepts did

not become widespread until the middle 1960’s, when third-generation digital computers

began to offer the speed and storage capabilities required for practical implementation of

image processing algorithms. Since then, this area has experienced vigorous growth and

has been subjected of study and research in such fields as engineering, computer science,

statistics, information science, physics, chemistry and medicine.

The result of these efforts have established the value of image processing

technique in of problem with application in diverse fields, including automated factory

controlled, astronomy, meteorology, agriculture, medicine, art and military application.

With the increasing availability of reasonably inexpensive hardware and some very

importance application on the horizon, image technology is expected to continue its

growth and to play an important role in the future.

From the MATLAB software we have the Toolbox for image processing and

Professional MATLAB. MATLAB is the interactive environment, scientists and

engineers are able to analyze and develop algorithms with exceptional improvements n

productivity and creativity. As a result of new algorithms with application-specific uses.

The MathWorks offers a series of application toolboxes that contain set of MATLAB ofr

the Linear algebra, high-speed computational kernel, extensive mathematical

functionality, data analysis, 2-D and 3-D graphic rapid algorithm development, matrix

based programming environment. In MATLAB Toolboxes professional version but

priced at a lower rate for academic use.

Page 17: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

3

1.2 Objective of The Project

The objective of this project is actually to educate newcomer to basic and

fundamental technique in image processing through integrated image processing

software. All fundamental algorithms of image processing will be exposed through this

package. This package will also provided easy-to-learn mechanisms turn user-friendly

by pop-up menu and graphic-orientation environment.

These operations include preprocessing, spatial filtering, image enhancement,

feature detection, image compression and image restoration involves process which

restores a degraded image to something close to the ideal. Generally, in computer vision,

especially in MATLAB program (image understanding or scene analysis) involves

technique from image processing, pattern recognition and artificial intelligent.

Particularly, MATLAB program offers many features and are more multifaceted then

any calculator. MATLAB toolbox is a tool for making mathematical calculations.

1.3 Scope of Project

Study and understand the image processing in varies method, mainly in

MATLAB. Create a GUI (Graphical User Interface) MATLAB program with several

functions.

1.4 Outline of Thesis

This thesis consists four chapters. In first chapter, it discuss about the objective

and scope of this project as long as summary of works. While Chapter 2 will discuss

Page 18: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

4

more on theory and literature reviews that have been done. It well discuss about types of

motor, various kind of speed measurement and controllers (thyristor, phase-lock loop

and PWM technique) that can be used to control the speed of the motor.

In Chapter 3, the discussion will be on the methodology hardware and software

implementation of this project. The result and discussion will be presented in Chapter 4.

Last but not least, Chapter 5 discusses the conclusion of this project and future work that

can be done.

1.5 Summary of Work

Every digital image processing system can be represented by a block diagram

containing three main elements, as shown in figure 1.1. The 4 major elements of every

image processing system include the following,

Figure 1.1 Process block

Image and MATLAB involves the conversion of scene into a digital

representation that can be processed by a digital computer. This can be performed by a

Image

MATLAB

Process Block

Processed Image

Page 19: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

5

sensor system specially designed to view a scene and provide a digital representation of

the scene.

Process block. When the images are installed in MATLAB, flowers picture for

example, the color of that image is first analyzed. In the process include several

functions of image processing technique.

Processed Image is the image display after the process. Gantt charts as shown in

Figure 1.2 and Figure 1.3 show the detail of the works of the project that had been

implemented in the first and second semester.

Page 20: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

6

Figure 1.2 Gantt Chart of the project schedule for semester 1

Page 21: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

7

Figure 1.3 Gantt Chart of the project schedule for semester 2

Page 22: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

CHAPTER II

THEORETICAL BACKGROUND FOR IMAGE PROCESSING

2.1 Introduction

Histogram is one of the technique most commonly used in contrast enhancement.

In many cases, the subjective contrast of an image is improved if one equalizes the

histogram of the histogram of gray-level of the picture elements argued that one should

make the histogram of the subjective brightness of the picture element uniform, or

equivalently making the gray-level histogram hyperbola is shape, it may hurt the further

machine analysis of the image.

Page 23: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

9

2.2 Histogram

Histogram is graphical presentations of the frequency count of the occurrence

each intensity (gray level) in the image. The horizontal axis of the graph represents the

tonal variations, while the vertical axis represents the number of pixels in that particular

tone. The left side of the horizontal axis represents the black and dark areas, the middle

represents medium grey and the right hand side represents light and pure white areas.

The vertical axis represents the size of the area that is captured in each one of these

zones.

2.3 Blur/Deblurring Image Using Blind Deconvolution Algorithm

The Blind Deconvolution Algorithm can be used effectively when no

information about the distortion (blurring and noise) is known. The algorithm restores

the image and the point-spread function (PSF) simultaneously. What happens is that

what should be seen as a sharp point gets smeared out, usually into a disc shape. In

image terms this means that each pixel in the source image gets spread over and mixed

into surrounding pixels. Another way to look at this is that each pixel in the destination

image is made up out of a mixture of surrounding pixels from the source image.

2.4 Threshold / Edge Detection

An image processing method distinguishes an object from within an image area

by determining a stable threshold value of light intensity values from within the image

area. Received light is converted into image data denoting light intensity values of the

received light at a plurality of points from within the image area. A bright portion

average value denoting an average of the light intensity values which exceed a

Page 24: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

10

predetermined threshold and a dark portion average value denoting an average of the

light intensity values which are less than the predetermined threshold are calculated. A

new threshold is obtained by applying the bright portion average value and the dark

portion average value to a predetermined dividing ratio. The object within the image

area is distinguished using the new threshold. The method is also applicable to the use

of multi value thresholds.

2.5 Enhancing Multispectral Color Composite Images

Enhance multispectral radiance or reflectance data to create an image that is

suitable for visual interpretation. Another way to enhance the true color composite is to

use a decorrelation stretch, which enhances color separation across highly correlated

channels.

Use decorrstretch to perform the decorrelation stretch. Again, surface features

have become much more clearly visible, but in a different way. The spectral differences

across the scene have been exaggerated.

2.6 Identify the Round Object

Classify objects based on their roundness using bwboundaries, a boundary

tracing routine. In this process, the MATLAB will convert the picture to black and white

first before to remove the noise (pixels which do not belong to the objects of interest)

inside the picture.

Estimate each object's area and perimeter. Use these results to form a simple

metric indicating the roundness of an object:

Page 25: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

11

Metric = 4*pi*area/perimeter^2.

This metric is equal to one only for a circle and it is less than one for any other

shape. The discrimination process can be controlled by setting an appropriate threshold.

In this example use a threshold of 0.94 so that only the pills will be classified as round.

2.7 Digital Filters

The digital filter can be categorized as a low pass or high pass filter depending

on which part of the frequency spectrum it affects. The effect on a composite electrical

analog signal containing all frequency components. The output signal of the high pass

filter will contain the high frequency components. The output signal of the low pass

filter will contain the DC bias and low frequency components. The specific cutoff

frequency cab be varied the selection of the value used in the filter, but that is beyond

the scope of this course.

The low frequency components in an image are characterized by a slow change

in the contrast or values of adjacent pixel in relation to high frequency components, due

to the rapid change in contrast encountered at the edge of an object.

2.8 Low Pass Filter

The low pass filter will not affect low frequency components in the image data

and will attenuate the high frequency components as illustrated in figure 2.1. Random

speckles in an image can be considered as noise and are high frequency components

since the pixel values of adjacent pixels change very rapidly. The effect of the speckles

can be reduced by using a simple averaging filter. The coefficient matrix for an

Page 26: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

12

averaging filter for a 3x3 local area convolution would contain nine elements as shown

below.

Figure 2.1 Filter

Result of low pass (b) and high pass (c) digital filter on a composite signal (a)

containing both low and high frequency as well as a DC bias.

The value for the pixel in the output matrix is calculated by convoluting the

image data, p1,j with the coefficient matrix f1,j and placing the resultant value at the

center pixel of the area in the new image matrix. The clearly for low pass filter, the

coefficient values of a low pass filter can declared with matrix form as show below

figure 2.2;

High Pass Filter

(b)

Low Pass Filter

(a)

(c)

Page 27: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

13

푓 , 푓 , 푓 ,푓 , 푓 , 푓 ,푓 , 푓 , 푓 ,

=

⎣⎢⎢⎡1

91

91

91

91

91

91

91

91

9⎦⎥⎥⎤

Figure 2.2 coefficient values of low pass filter

The new value of q2,2 is given by

q2,2 = 푓 , x 푝 , + 푓 , x 푝 , + … + 푓 , x 푝 ,

The rules for a low pass filter are;

1. All the coefficient must be positive, and

2. The sum of all the coefficients must be equal 1.

If the sum of the coefficient must be equal 1, amplification will result. If the sum

is less than 1, attenuation will result, and the magnitude of the pixel value over the entire

image will be reduced. Hence, the image would appear darker.

The application of the 3x3 coefficient matrix to a data field where all the pixel

have the same value will have no effect except where there is a gradient between

adjacent pixels. The effect of the low pass digital filter in reducing noise can be

illustrated by considering the case where there is one pixel in the matrix which is zero

due to bad element in the sensor array used to acquire the data; all the adjacent pixels

have a high value show is figure 2.3.

Page 28: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

14

7 7 77 0 77 7 7

7 7 77 7 77 7 7

(a) (b)

Figure 2.3 effect of low pass filter (a) matrix with bad element (b) matrix after low pass

filter

If the bad pixel value had been high instead of low as the result of a white speck,

the application of the low filter would have had the effect of reducing the magnitude of

the value of bad pixel.

The effect of increasing the size of the neighborhood region 5 x 5 or 9 x9 can be

illustrated by comparing the result of applying a low pass filter to the case one of one

bad pixel value, (0 in a region contain all ones) as is done in Table 2.1.

Table 2.1 effect of increasing the size of the neighborhood region

Size of Matrix Convoluted Value Raw Value of Bad

Element

Relative

Computation Time

3 x 3 1/9 8/9 1

5 x5 1/25 24.25 25/9 = 2-7/9

9 x 9 1/81 80/81 81/9 = 9

2.9 High Pass Filter

The high pass digital filter has the inverse characteristic of low pass filter. The

filter will not change the high frequency component of a signal and will attenuate the

low frequency component as well as eliminate any bias in the signal. The effect of

background light would result in a DC bias in the vision system data since the minimum

value of all pixel would be above some given some given value. The effect of applying a

Page 29: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

15

high pass filter to the data for a 6 x 6 image is shown in the histogram of figure 2.4

below. The high pixel values may or may not change depending on the degree of

saturation of the image.

The high pass filter coefficient set for set for a 3 x 3 matrix convolution mask is

−1 −1 −1−1 −8 −1−1 −1 −1

Figure 2.4 high pass filter coefficient set for 3x3 matrix convolution mask

1. The coefficient can be positive or negative.

2. The sum of the coefficient is 0.

Since the sum of all the coefficients is equal to zero, the dc component will be

completely suppressed. If the sum were equal to +1, the DC value would have been

retained at the same value as the original signal. The filter is applied by overlaying the

3x3 coefficient matrix filter mask on the image data, multiplying the coefficient and data

in each of the nine elements, and adding the nine resultant products to obtain the value

of the new element located at the center of 3 x 3 matrixes. The mask is then shifted by

one unit and the process repeated to obtain the value of the next new element.

Page 30: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

16

+1 +1 +1+1 −8 +1+1 +1 +1

4 8 84 8 84 8 8

− − −− [] −− − −

mask data element

Figure 2.5 mask, data and element

(2,2) = +(1x4)+(1x8)+(1x8)+(1x4)-(8x8)-(8x8)+(1x8)+(1x4)+(1x8)+(1x8)

= +4+8+8+4-64+8+4+8+8

=` +52-62

= -12

Page 31: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

CHAPTER III

METHODOLOGY

3.1 Introduction

Basically, MATLAB software has many functions/commands to apply in image

processing. How to manipulate the program depending to us but must be practically

know what item is MATLAB program will be used. Creativity in MATLAB can make

the interesting result. Even, the complex data can be solved in MATLAB. Especially

when the data involved is very complex. Here, we can create some image from

converting data by using the some program in MATLAB, which just applied all

procedure in the MATLAB program. MATLAB toolbox is a tool for making

mathematical calculations. Image processing toolbox is user friendly programming

language with feature more advanced. In the program also used the GUI (Graphical User

Interface) to create develop the program.

Every digital image processing system can be represented by a block diagram

containing three main elements, as shown in figure 3.1. The 4 major elements of every

image processing system include the following,

Page 32: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

18

Figure 3.1 Processing block

Image and MATLAB involves the conversion of scene into a digital representation that

can be processed by a digital computer. This can be performed by a sensor system

specially designed to view a scene and provide a digital representation of the scene.

When the images are installed in MATLAB, flowers picture for example, the

color of that image is first analyzed. In the process include several functions of image

processing technique. Processed Image is the image display after the process.

Image

MATLAB

Process Block

Processed Image

Page 33: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

19

3.2 Blur/Deblurring Image Using Blind Deconvolution Algorithm

In this process, by referring to the M-file

a) LEN = 21, linear motion across 31 pixels

b) THETA = 11, angle of 11 degrees

c) PSF = fspecial('motion', LEN, THETA), point-spread function, PSF,

corresponding to the linear motion across 31 pixels (LEN=31), at an angle of 11

degrees (THETA=11).

d) blurred = imfilter(IMG, PSF, 'conv', 'circular'), simulate the blur, convolve the

filter with the image using imfilter.

e) noise_mean = 0; noise_var = 0.001;

blurred_noisy = imnoise(blurred, 'gaussian', ...noise_mean, noise_var), adding

the noise to the picture.

f) deconvwnr(blurred_noisy, PSF, 0.01) restore the blurred picture.

Page 34: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

20

3.3 Enhancing Multispectral Color Composite Images Threshold / Edge

Detection

In this process, by referring to the M-file

a) truecolor = IMG, set the truecolor equal to the IMG

b) decorrstretched_truecolor = decorrstretch(truecolor, 'Tol', 0.01), Use

decorrstretch to perform the decorrelation stretch (followed by a linear contrast

stretch, as specified by the optional parameter-value pair 'Tol' and 0.1).

c) IMG=decorrstretched_truecolor, set the IMG equal to decorrstretched_truecolor

d) imshow(IMG), display the image IMG.

3.4 Threshold / Edge Detection

a) level = graythresh(IMG), bw = im2bw(IMG,level), level = graythresh(I)

computes a global threshold (level) that can be used to convert an intensity image

to a binary image with im2bw. level is a normalized intensity value that lies in

the range [0, 1]. The graythresh function uses Otsu's method, which chooses the

threshold to minimize the intraclass variance of the black and white pixels.

Multidimensional arrays are converted automatically to 2-D arrays using reshape.

The graythresh function ignores any nonzero imaginary part of I.

b) bw = bwareaopen(bw, 50), Morphologically open binary image (remove small

objects)

Page 35: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

21

c) IMG=bw, set the IMG equal to bw

d) imshow(IMG), display the IMG to screen

3.5 Identify the Round Object

a) I = rgb2gray(RGB);threshold = graythresh(I);bw = im2bw(I,threshold),

computes a global threshold (level) that can be used to convert an intensity image

to a binary image with im2bw. level is a normalized intensity value that lies in

the range [0, 1]. The graythresh function uses Otsu's method, which chooses the

threshold to minimize the intraclass variance of the black and white pixels.

Multidimensional arrays are converted automatically to 2-D arrays using reshape.

The graythresh function ignores any nonzero imaginary part of I.

b) bw = bwareaopen(bw,30), Using morphology functions, remove pixels which do

not belong to the objects of interest. remove all object containing fewer than 30

pixels

c) se = strel('disk',2);bw = imclose(bw,se), fill a gap in the pen's cap

d) bw=imfill(bw,'holes');imshow(bw);[B,L]=bwboundaries(bw,'noholes'), fill any

holes, so that regionprops can be used to estimate the area enclosed by each of

the boundaries

e) IMG=label2rgb(L, @jet, [.5 .5 .5]);imshow(IMG)hold on, Display the label

matrix and draw each boundary

Page 36: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

22

f) For k=1:length(B);boundary = B{k};plot(boundary(:,2),boundary(:,1), 'w',

'LineWidth', 2)

end

stats = regionprops(L,'Area','Centroid');threshold = 0.94, loop over the

boundaries

g) for k = 1:length(B);boundary = B{k}, obtain (X,Y) boundary coordinates

corresponding to label 'k'

h) delta_sq=diff(boundary).^2;perimeter=sum(sqrt(sum(delta_sq,2))), compute a

simple estimate of the object's perimeter

i) area = stats(k).Area, obtain the area calculation corresponding to label 'k'

j) metric = 4*pi*area/perimeter^2, display the results

k) if

metric>threshold; centroid = stats(k); Centroid; plot(centroid(1),centroid(2),'ko');

end

mark objects above the threshold with a black circle

3.6 Rotate

In this process, by referring to M-file

a) image=double(IMG);s=size(image);result=zeros(s(2),s(1),s(3)),

Allocating memory for fast execution

b) i = 1:s(1)

Page 37: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

23

j=1:s(2);

k=s(2)-j+1;

result(k,i,:)=image(i,j,:),Computing the new matrix

c) res=uint8(result);

IMG=res;

imshow(IMG), Displaying the rotated image

3.7 Open Image

In this process, by referring to M-file

Loading the Image

[filename, pathname, filterindex]=uigetfile( ...

{'*.jpg','JPEG File (*.jpg)'; ...

'*.*','Any Image file (*.*)'}, ...

'Pick an image file');

var=strcat(pathname,filename);

ORI_IMG=imread(var);

IMG=ORI_IMG;

% Showing the origional image

imshow(IMG);title('original image')

3.8 Reset

In this process, by referring to M-file

Page 38: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

24

a) global IMG ORI_IMG;IMG=ORI_IMG;, reset the image after process

b) imshow(IMG);title('original image'), show the image

3.9 Save image

In this process, by referring to M-file

a) image=uint8(IMG), define a 8-bit unsigned integer.

b) [filename,pathname] = uiputfile( ...

{'*.jpg', 'JPEG Image File'; ...

'*.*', 'All Files (*.*)'}, ...

'Save current image as');

Open standard dialog box for saving files, displays a dialog box titled 'Save

current image as’ with the filter specifier set to .jpg file, JPEG Image file and all

files.

c) var=strcat(pathname,filename,'.jpg'), horizontally concatenates corresponding

rows of the character arrays pathname, filename and ‘.jpg’.

d) imwrite(image,var), write the image to pc in the format specified by var

3.10 Show original picture

In this process, by referring to M-file

a) (get(handles.checkbox3,'Value') == 0),

Page 39: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

25

subplot(1.2,0.99,1.05); Deleting all subplots present

imshow(IMG);

b) subplot(1.3,1.8,1), imshow(ORI_IMG),title('original image'); Displaying

origional image

c) subplot(1.3,1.8,2), imshow(IMG); Displaying the rotated image

Page 40: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

Image memory

CHAPTER IV

RESULTS AND DISCUSSION

4.1 Introduction

Before processing the image, we must know what process should be planning. The planning as shown in figure 4.1 is step to process the image by applying MATLAB toolbox program.

Figure 4.1 step planning

-Modified Image -Show Image 1. JPG

2. Any image Get image

Operator

1. Enhance 2. Threshold 3. Rotate 4. Blur 5. Deblur 6. Identify Round Object

RESULT

Page 41: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

27

Regarding to figure 4.1 we can know the step to identify which the images

are .JPG and any image file. To develop the program, we should know how to create

GUI (Graphical User Interface) function program.

4.2 GUI (Graphical User Interface)

A graphical user interface (GUI) is a graphical display in one or more windows

containing controls, called components that enable a user to perform interactive tasks.

The user of the GUI does not have to create a script or type commands at the command

line to accomplish the tasks. Unlike coding programs to accomplish tasks, the user of a

GUI need not understand the details of how the tasks are performed.

GUI components can include menus, toolbars, push buttons, radio buttons, list

boxes, and sliders—just to name a few. GUIs created using MATLAB tools can also

perform any type of computation, read and write data files, communicate with other

GUIs, and display data as tables or as plots

Most GUIs wait for their user to manipulate a control, and then respond to each

action in turn. Each control, and the GUI itself, has one or more user-written routines

(executable MATLAB code) known as callbacks, named for the fact that they "call

back" to MATLAB to ask it to do things. The execution of each callback is triggered by

a particular user action such as pressing a screen button, clicking a mouse button,

selecting a menu item, typing a string or a numeric value, or passing the cursor over a

component. The GUI then responds to these events. You, as the creator of the GUI,

provide callbacks which define what the components do to handle events.

This kind of programming is often referred to as event-driven programming. In

the example, a button click is one such event. In event-driven programming, callback

Page 42: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

28

execution is asynchronous, that is, it is triggered by events external to the software. In

the case of MATLAB GUIs, most events are user interactions with the GUI, but the GUI

can respond to other kinds of events as well, for example, the creation of a file or

connecting a device to the computer.

You can code callbacks in two distinct ways:

As MATLAB functions, written in M and stored in M-files

As strings containing MATLAB expressions or commands (such as 'c = sqrt(a*a

+ b*b);'or 'print')

Using functions stored in M-files as callbacks is preferable to using strings, as functions

have access to arguments and are more powerful and flexible. MATLAB scripts

(sequences of statements stored in M-files that do not define functions) cannot be used

as callbacks.

Although you can provide a callback with certain data and make it do anything

you want, you cannot control when callbacks will execute. That is, when your GUI is

being used, you have no control over the sequence of events that trigger particular

callbacks or what other callbacks might still be running at those times. This

distinguishes event-driven programming from other types of control flow, for example,

processing sequential data files.

Page 43: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

29

4.3 Image Processing Result

The image will be modified after the process in the program system. The GUI

program I create will be show below and include all the results (modified images) for

each function.

Figure 4.2 layout of image processing program

Page 44: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

30

Figure 4.3 image opened in program

Figure 4.4 Image after simulated with blur and noise

Page 45: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

31

Figure 4.5 image after deblurred

Figure 4.6 image enhanced after blurred

Page 46: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

32

Figure 4.7 image enhance after deblurred

Figure 4.8 image rotated

Page 47: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

33

Figure 4.9 original image after threshold

Figure 4.10 Enhanced image after threshold

Page 48: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

34

Figure 4.11 original and modified image shows together

Page 49: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

CHAPTER IV

CONCLUSION AND RECOMMENDATION

5.1 Conclusion

Image can be solved with ant software programming such as C language, Matrix

– X (Mainframe or workstation, based on MATLAB), Visual Basic, Java program and

MATLAB program. Image applications frequently need to produce multiple degrees of

manipulation interactively. Image applications frequently need to interactively

manipulate an image by continuously changing a single parameter and multi-parameter.

The best software program is the MATLAB toolbox for image processing. Interpolation

and extrapolation of image can be a unifying approach, providing a simple function that

supports many common images processing operation.

Since a degenerate image is sometimes easier to calculate, extrapolation may

offer a more efficient method to achieve effects such as sharpening or saturation.

Blending is a linear operation, and so it must be performed in linear, not gamma-warped

space. Component range must be also be monitored, since clamping, especially of the

degenerate image, causes inaccuracy.

By using the GUI (Graphical User Interface) program, the application of image

processing can successfully created. The function of the image processing program

Page 50: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

36

include the enhance, threshold, rotate, blur (noise), deblur, identify round object and

show the original and modified image together.

5.3 Problems

Although the image processing program function as we aspect, but there are still

many way to improve this program. In the image processing program, the info for the

function are not state clearly enough and make people understand. In the GUI program,

the info should function as pop-up window after user press any function button.

As the project title is Image Processing using MATLAB – Learning Tool, the

information is not good enough and clear to understand by people. The main problem is

the effectiveness of people to understand it. MATLAB also can be used in industry are

in the areas of bar coding, deck-top publication, copy preparation for printing and

factory automation.

However, due to the information and studies this state of program of image

processing that I only can create. More advance and more functional program can be

creating by using MATLAB. Thereby, to write the program became problem and the this

project not perfectly complete.

Page 51: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

37

5.3 Recommendations

The result of the program is slightly sluggish. For future works, some

recommendations have been listed based on the problems in order to improve the

performance.

a) Create a 3-D for the image processing and animation. Then the image can be

more sophisticated if the 3-D program instead. Can spin and move the image

with applying that command, so that we can create a great animation for the

image.

b) Add more functional button of more function to the program. It is less filter to

filter image, such as Robert Gradient, Sobel Edge Detector Operator, Gaussion

filter and other filters.

c) More information and detail about the function should be add in the program to

educate people well.

Page 52: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

38

REFERENCES

1. FIONN MURTAGH. Image processing data analysis. The Multi-scale approach.

University of Ulster

2. LOUIS J.GALBIATI, JR. Machine Vision and Digital Image Processing

Fundamentals. Prentice-Hall International Editions.

3. ABDUL HALIM BIN BABA. Image processing Learning Tool-Edge detection.

Bachelor Degree. University of Technology Malaysia 1996.

4. CHIN CHIOON KHENG. Window based image processing-learning tool.

Bachelor Degree. University of Technology Malaysia 1997.

5. Fundamentals of Image Processing, [email protected] (http://www.cs.dartmouth.edu/~farid)

6. JEAN-LUC STARCK, Centre d’Etudes de Saclay, Fionn Murtagh. Image processing and data analysis the multiscale approach. University of Ulster.

7. C. ANDERSON. "An alternative to the Burt pyramid algorithm", memo in preparation.

8. S LEVIALDI, “Digital Image Analysis”, University of Rome

Page 53: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

39

APPENDIX A

The contents of Image Processing Toolbox

Image input/output bmpread -Read a BMP (Microsoft Windows Bitmap) file from disk. bmpwrite -Write a BMP (Microsoft Windows Bitmap) file from disk. gifread -Read a GIF (Graphical Interchange Format) file from disk. gifread -Write a GIF (Graphical Interchange Format) file from disk. hdfpeek -Read data from HDF file. hdfwrite -Write data from HDF file. pcxread -Read a PCX (ZSoft Paint Format) file form disk. pcxwrite -Write a PCX (ZSoft Paint Format) file form disk. tiffread -Read a TIFF (Tagged Image File Format) file from disk. tiffwrite -Write a TIFF (Tagged Image File Format) file from disk. xwdread -Read a XWD (X window dump) file from disk. xwdwrite -Write a XWD (X window dump) file from disk.

Utility routines getimage -Get image data form axes isbw -True for black and white images. isgray -True for intensity images. isind -True for indexed images. Color operations brighten -Brighten or darken a colormap. cmunique -Find unique colormap colors and corresponding image. cmpermute -Permute colormap positions. cmgamma -Gamma correct colormap. cmgamdef -Default gamma correction table. dither -Floyd-Steinberg image dithering. hsv2rgb -Convert HSV values to RGB colorspace. imadjust -adjust and stretch image by an image with fewer colors. imapprox -Approximate indexed image by an image with fewer colors. ntsc2rgb -Convert NTSC values to RGB colorspace. rgb2gray -Convert RGB values to gray. rgb2hsv -Convert RGB values to HSV colorspace. rgb2ntsc -Convert RGB values to NTSC colorspace. rgbplot -Plot RGB colormap components.

Page 54: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

40

Geometric operations imcrop -Crop image imresize -Resize image imrotate -Rotate image truesize -Resize figure so that image is actual size imzoom -Zoom in and out an image or 2-D plot

Image enhancement/analysis brighten -Brigthen or darken a colormap. grayslice -Density (intensity) slicing. histeq -Histogram equalization. imadjust -Adjust and stretch image intensity imapprox -Approximate indexed image by an image with fewer colors. imhist -Image histogram impixel -color of a pixel improfile -intensity profile. interp2 -2-D data interpolation.

Image Statistics. mean2 -Mean of a matrix corr2 -2-D correlation coefficient. std2 -2-D standard deviation.

Morphological operations. bwarea -Area of object in binary image. dilate -Dilate (thicken) a binary image. erode -Erode (thin) a binary image. edge -Euler number. bwmorph -Morphological operators. bwperim -Perimeter of objects in a binary image.

FIR Filter design. fsamp2 -2-D FIR filter design via frequency sampling. fspecial -Special 2-D filter. ftrans2 -2-D FIR filter design via frequency transformation. fwind1 -2-D FIR filter design using 1-D windows. fwind2 -2-D FIR filter design using 2-D windows. imnoise -Image noise

Frequency response. freqspace -Frequency spacing for 2-D frequency responses. freqz2 -Two dimensional frequency response.

Page 55: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

41

Filtering. colfilt -Local non-linear filtering as columns. conv2 -Two-dimensional convolution. filter2 -Two-dimensional filtering. medfilt2 -Two-dimensional median filtering. mfilter2 -Masked filter. nlfilter -Local non-linear filtering. wiener2 -Adaptive 2-D Wiener filtering

Block processing bestblk -Best block size for block processing. blkproc -Process an image in blocks. col2im -Rearrange distinct or sliding column blocks to form image, colfilt -Local non-linear filtering as columns. im2col -Rearrange distinct or sliding blocks into columns.

Region of interest (ROI) mfilter2 -Masked filter roipoly -Define polygonal region of interest (ROI). roicolor -Define region of interest (ROI) by color.

Transforms. dct2 -2-D discrete cosine transform. fft2 -2-D Fast Fourier Transform. fftshift -Move zeroth lag (DC component) to center. idct2 -2-D inverse discrete cosine transform. ifft2 -2-D inverse FFt radon -Radon transform.

Conversions. dither -Floyed-Steinberg image dithering. gray2ind -Convert gray scale intensity image to indexed image. hsv2rgb -Covert HSV values to RGB colorspace. im2bw -convert image to black and white by thresholding. imslice -Get image slices into an image deck ind2rgb -Convert indexed image to an RGB image. mat2gray - Convert matrix to (gray) intensity image. ntsc2rgb - Convert NTSC values to an RGB image. rgb2gray - Convert an RGB image r values to gray. rgb2hsv - Convert RGB values to HSV colorspace.. rgb2ind - Convert RGB image to indexed image. rgb2ntsc - Convert RGB values to NTSC colorspace.\

Page 56: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

42

Image diplay colorbar -Display color bar (color scale) colormap -Set or get the color look-up table. gray -Linear gray-scale color map hsv,hot,jet -Colormaps. Types HELP COLOR for others image -Display indexed image. imagesc -Scale data and display as image imcoutour -Image coutour. immovie -Make a movie of an image deck. imshow -Display all type of image data. montage -Display an image deck as a rectangular montage. warp -Warp an image on

Page 57: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

43

APPENDIX B

function varargout = LearningTool(varargin)

% LEARNINGTOOL M-file for LearningTool.fig

% LEARNINGTOOL, by itself, creates a new LEARNINGTOOL

% or raises the existing singleton*.

%

% H = LEARNINGTOOL returns the handle to a new LEARNINGTOOL

% or the handle to the existing singleton*.

%

% LEARNINGTOOL('CALLBACK',hObject,eventData,handles,...) calls the local

% function named CALLBACK in LEARNINGTOOL.M

% with the given input arguments.

%

% LEARNINGTOOL('Property','Value',...) creates a new

% LEARNINGTOOL or raises the existing singleton*. \

% Starting from the left, property value pairs are

% applied to the GUI before LearningTool_OpeningFcn gets called. An

% unrecognized property name or invalid value makes property application

% stop. All inputs are passed to LearningTool_OpeningFcn via varargin.

%

% *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one

% instance to run (singleton)".

%

% See also: GUIDE, GUIDATA, GUIHANDLES

% Edit the above text to modify the response to help LearningTool

% Last Modified by GUIDE v2.5 12-Mar-2010 02:38:49

Page 58: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

44

% Begin initialization code - DO NOT EDIT

gui_Singleton = 1;

gui_State = struct('gui_Name', mfilename, ...

'gui_Singleton', gui_Singleton, ...

'gui_OpeningFcn', @LearningTool_OpeningFcn, ...

'gui_OutputFcn', @LearningTool_OutputFcn, ...

'gui_LayoutFcn', [] , ...

'gui_Callback', []);

if nargin && ischar(varargin{1})

gui_State.gui_Callback = str2func(varargin{1});

end

if nargout

[varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});

else

gui_mainfcn(gui_State, varargin{:});

end

% End initialization code - DO NOT EDIT

% --- Executes just before LearningTool is made visible.

function LearningTool_OpeningFcn(hObject, eventdata, handles, varargin)

% This function has no output args, see OutputFcn.

% hObject handle to figure

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% varargin command line arguments to LearningTool (see VARARGIN)

% Choose default command line output for LearningTool

handles.output = hObject;

% Update handles structure

Page 59: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

45

guidata(hObject, handles);

% UIWAIT makes LearningTool wait for user response (see UIRESUME)

% uiwait(handles.figure1);

% --- Outputs from this function are returned to the command line.

function varargout = LearningTool_OutputFcn(hObject, eventdata, handles)

% varargout cell array for returning output args (see VARARGOUT);

% hObject handle to figure

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% Get default command line output from handles structure

varargout{1} = handles.output;

% --- Executes on button press in OpenFile.

function OpenFile_Callback(hObject, eventdata, handles)

% hObject handle to OpenFile (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG ORI_IMG

% Loading the Image

[filename, pathname, filterindex]=uigetfile( ...

{'*.jpg','JPEG File (*.jpg)'; ...

'*.*','Any Image file (*.*)'}, ...

'Pick an image file');

var=strcat(pathname,filename);

ORI_IMG=imread(var);

IMG=ORI_IMG;

% Showing the origional image

imshow(IMG);title('original image');

Page 60: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

46

% --- Executes on button press in Reset.

function Reset_Callback(hObject, eventdata, handles)

% hObject handle to Reset (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% reset the image after process

global IMG ORI_IMG;

IMG=ORI_IMG;

%show the image

imshow(IMG);title('original image');

% --- Executes on button press in Blur.

function Blur_Callback(hObject, eventdata, handles)

% hObject handle to Blur (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG;

LEN = 21;

THETA = 11;

PSF = fspecial('motion', LEN, THETA);

blurred = imfilter(IMG, PSF, 'conv', 'circular');

noise_mean = 0;

noise_var = 0.001;

blurred_noisy = imnoise(blurred, 'gaussian', ...

noise_mean, noise_var);

IMG=blurred_noisy;

imshow(IMG)

title('Simulate Blur and Noise')

% --- Executes on button press in Deblured.

Page 61: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

47

function Deblured_Callback(hObject, eventdata, handles)

% hObject handle to Deblured (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG;

LEN = 21;

THETA = 11;

PSF = fspecial('motion', LEN, THETA);

blurred = imfilter(IMG, PSF, 'conv', 'circular');

noise_mean = 0;

noise_var = 0.001;

blurred_noisy = imnoise(blurred, 'gaussian', ...

noise_mean, noise_var);

A = deconvwnr(blurred_noisy, PSF, 0.001);

IMG=A;

imshow(IMG)

title('Restoration of Blurred, Noisy Image Using NSR = 0.001')

% --- Executes on button press in Enhance.

function Enhance_Callback(hObject, eventdata, handles)

% hObject handle to Enhance (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG;

truecolor = IMG;

decorrstretched_truecolor = decorrstretch(truecolor, 'Tol', 0.01);

IMG=decorrstretched_truecolor;

imshow(IMG);

title('Image Composite after Decorrelation Stretch');

% --- Executes on button press in Rotate.

Page 62: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

48

function Rotate_Callback(hObject, eventdata, handles)

% hObject handle to Rotate (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG;

image=double(IMG);

s=size(image);

result=zeros(s(2),s(1),s(3)); % Allocating memory for fast execution

for i = 1:s(1)

j=1:s(2);

k=s(2)-j+1;

result(k,i,:)=image(i,j,:); % Computing the new matrix

end

res=uint8(result);

IMG=res;

imshow(IMG); % Displaying the rotated image

title('Rotate Image');

% --- Executes on button press in Threshold.

function Threshold_Callback(hObject, eventdata, handles)

% hObject handle to Threshold (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG;

level = graythresh(IMG);

bw = im2bw(IMG,level);

IMG = bwareaopen(bw, 50);

imshow(IMG);

title('Gray Image');

Page 63: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

49

% --- Executes on button press in IdentifyingRoundObjects.

function IdentifyingRoundObjects_Callback(hObject, eventdata, handles)

% hObject handle to IdentifyingRoundObjects (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

global IMG;

RGB = IMG;

I = rgb2gray(RGB);

threshold = graythresh(I);

bw = im2bw(I,threshold);

% Using morphology functions, remove pixels which do not belong to the

% objects of interest.

% remove all object containing fewer than 30 pixels

bw = bwareaopen(bw,30);

% fill a gap in the pen's cap

se = strel('disk',2);

bw = imclose(bw,se);

% fill any holes, so that regionprops can be used to estimate

% the area enclosed by each of the boundaries

bw = imfill(bw,'holes');

imshow(bw)

[B,L] = bwboundaries(bw,'noholes');

% Display the label matrix and draw each boundary

IMG=label2rgb(L, @jet, [.5 .5 .5]);

imshow(IMG)

hold on

for k = 1:length(B)

boundary = B{k};

plot(boundary(:,2), boundary(:,1), 'w', 'LineWidth', 2)

end

stats = regionprops(L,'Area','Centroid');

Page 64: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

50

threshold = 0.94;

% loop over the boundaries

for k = 1:length(B)

% obtain (X,Y) boundary coordinates corresponding to label 'k'

boundary = B{k};

% compute a simple estimate of the object's perimeter

delta_sq = diff(boundary).^2;

perimeter = sum(sqrt(sum(delta_sq,2)));

% obtain the area calculation corresponding to label 'k'

area = stats(k).Area;

% compute the roundness metric

metric = 4*pi*area/perimeter^2;

% display the results

metric_string = sprintf('%2.2f',metric);

% mark objects above the threshold with a black circle

if metric > threshold

centroid = stats(k).Centroid;

plot(centroid(1),centroid(2),'ko');

end

text(boundary(1,2)-35,boundary(1,1)+13,metric_string,'Color','y',...

'FontSize',14,'FontWeight','bold');

end

Page 65: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

51

% --- If Enable == 'on', executes on mouse press in 5 pixel border.

% --- Otherwise, executes on mouse press in 5 pixel border or over OpenFile.

function OpenFile_ButtonDownFcn(hObject, eventdata, handles)

% hObject handle to OpenFile (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.

function OpenFile_CreateFcn(hObject, eventdata, handles)

% hObject handle to OpenFile (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% --- If Enable == 'on', executes on mouse press in 5 pixel border.

% --- Otherwise, executes on mouse press in 5 pixel border or over Reset.

function Reset_ButtonDownFcn(hObject, eventdata, handles)

% hObject handle to Reset (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.

function Reset_CreateFcn(hObject, eventdata, handles)

% hObject handle to Reset (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% --- Executes on mouse press over axes background.

Page 66: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

52

function axes1_ButtonDownFcn(hObject, eventdata, handles)

% hObject handle to axes1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.

function axes1_CreateFcn(hObject, eventdata, handles)

% hObject handle to axes1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% Hint: place code in OpeningFcn to populate axes1

% --- If Enable == 'on', executes on mouse press in 5 pixel border.

% --- Otherwise, executes on mouse press in 5 pixel border or over Rotate.

function Rotate_ButtonDownFcn(hObject, eventdata, handles)

% hObject handle to Rotate (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.

function Rotate_CreateFcn(hObject, eventdata, handles)

% hObject handle to Rotate (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% --- If Enable == 'on', executes on mouse press in 5 pixel border.

Page 67: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

53

% --- Otherwise, executes on mouse press in 5 pixel border or over Blur.

function Blur_ButtonDownFcn(hObject, eventdata, handles)

% hObject handle to Blur (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.

function Blur_CreateFcn(hObject, eventdata, handles)

% hObject handle to Blur (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% --- Executes during object creation, after setting all properties.

function pushbutton2_CreateFcn(hObject, eventdata, handles)

% hObject handle to pushbutton2 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% --- Executes on button press in Close.

function Close_Callback(hObject, eventdata, handles)

% hObject handle to Close (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

clear all;

close;clear

% --- Executes on button press in Save.

function Save_Callback(hObject, eventdata, handles)

% hObject handle to Save (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

Page 68: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

54

% handles structure with handles and user data (see GUIDATA)

global IMG

image=uint8(IMG);

[filename,pathname] = uiputfile( ...

{'*.jpg', 'JPEG Image File'; ...

'*.*', 'All Files (*.*)'}, ...

'Save current image as');

var=strcat(pathname,filename,'.jpg');

imwrite(image,var);

% --- Executes on selection change in listbox1.

function listbox1_Callback(hObject, eventdata, handles)

% hObject handle to listbox1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% Hints: contents = get(hObject,'String') returns listbox1 contents as cell array

% contents{get(hObject,'Value')} returns selected item from listbox1

% --- Executes during object creation, after setting all properties.

function listbox1_CreateFcn(hObject, eventdata, handles)

% hObject handle to listbox1 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% Hint: listbox controls usually have a white background on Windows.

% See ISPC and COMPUTER.

if ispc && isequal(get(hObject,'BackgroundColor'),

get(0,'defaultUicontrolBackgroundColor'))

Page 69: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

55

set(hObject,'BackgroundColor','white');

end

% --- If Enable == 'on', executes on mouse press in 5 pixel border.

% --- Otherwise, executes on mouse press in 5 pixel border or over text2.

function text2_ButtonDownFcn(hObject, eventdata, handles)

% hObject handle to text2 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% --- Executes during object creation, after setting all properties.

function text2_CreateFcn(hObject, eventdata, handles)

% hObject handle to text2 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles empty - handles not created until after all CreateFcns called

% --- Executes on button press in checkbox3.

function checkbox3_Callback(hObject, eventdata, handles)

% hObject handle to checkbox3 (see GCBO)

% eventdata reserved - to be defined in a future version of MATLAB

% handles structure with handles and user data (see GUIDATA)

% Hint: get(hObject,'Value') returns toggle state of checkbox3

global ORI_IMG IMG

if (get(handles.checkbox3,'Value') == 0),

subplot(1.2,0.99,1.05); % Deleting all subplots present

imshow(IMG);

else

Page 70: IMAGE PROCESSING USING MATLAB – LEARNING TOOL

56

subplot(1.3,1.8,1), imshow(ORI_IMG),title('original image'); % Displaying origional

image

subplot(1.3,1.8,2), imshow(IMG); % Displaying the rotated image

end