You are on page 1of 13

MATLAB: Image Processing Operations

Read and Display an Image

First, clear the MATLAB workspace of any variables and close open figure windows.
close all
To read an image, use the imread command. The example reads one of the sample images included with
the toolbox, pout.tif, and stores it in an array named I.
I = imread('pout.tif');
imread infers from the file that the graphics file format is Tagged Image File Format (TIFF). For the list of
supported graphics file formats, see the imreadfunction reference documentation.
Now display the image. The toolbox includes two image display functions: imshow and imtool. imshow is
the toolbox's fundamental image display function.imtool starts the Image Tool which presents an
integrated environment for displaying images and performing some common image processing tasks. The
Image Tool provides all the image display capabilities of imshow but also provides access to several other
tools for navigating and exploring images, such as scroll bars, the Pixel Region tool, Image Information tool,
and the Contrast Adjustment tool. For more information, see Displaying and Exploring Images. You can use
either function to display an image. This example uses imshow.
imshow(I)
Grayscale Image pout.tif

Improve Image Contrast


pout.tif is a somewhat low contrast image. To see the distribution of intensities in pout.tif, you can
create a histogram by calling the imhist function. (Precede the call to imhist with the figure command
so that the histogram does not overwrite the display of the image I in the current figure window.)
figure, imhist(I)
Notice how the intensity range is rather narrow. It does not cover the potential range of [0, 255], and is
missing the high and low values that would result in good contrast.

The toolbox provides several ways to improve the contrast in an image. One way is to call
the histeq function to spread the intensity values over the full range of the image, a process
called histogram equalization.
I2 = histeq(I);
Display the new equalized image, I2, in a new figure window.
figure, imshow(I2)
Equalized Version of pout.tif

Call imhist again to create a histogram of the equalized image I2. If you compare the two histograms, the
histogram of I2 is more spread out than the histogram of I1.
figure, imhist(I2)
The toolbox includes several other functions that perform contrast adjustment, including
the imadjust and adapthisteq functions. See Adjusting Pixel Intensity Values for more information. In
addition, the toolbox includes an interactive tool, called the Adjust Contrast tool, that you can use to adjust
the contrast and brightness of an image displayed in the Image Tool. To use this tool, call
the imcontrast function or access the tool from the Image Tool. For more information, see Adjusting
Image Contrast Using the Adjust Contrast Tool.

Displaying a Contour Plot of Image Data


You can use the toolbox function imcontour to display a contour plot of the data in a grayscale image. A
contour is a path in an image along which the image intensity values are equal to a constant. This function is
similar to the contour function in MATLAB, but it automatically sets up the axes so their orientation and
aspect ratio match the image.

This example displays a grayscale image of grains of rice and a contour plot of the image data:

1. Read a grayscale image and display it.


2. I = imread('rice.png');
imshow(I)

3. Display a contour plot of the grayscale image.


figure, imcontour(I,3)
Removing Noise By Median Filtering
Median filtering is similar to using an averaging filter, in that each output pixel is set to an average of the
pixel values in the neighborhood of the corresponding input pixel. However, with median filtering, the value
of an output pixel is determined by the median of the neighborhood pixels, rather than the mean. The
median is much less sensitive than the mean to extreme values (called outliers). Median filtering is therefore
better able to remove these outliers without reducing the sharpness of the image. The medfilt2 function
implements median filtering.
Note Median filtering is a specific case of order-statistic filtering, also known as rank filtering. For
information about order-statistic filtering, see the reference page for the ordfilt2 function.

The following example compares using an averaging filter and medfilt2 to remove salt and pepper noise.
This type of noise consists of random pixels' being set to black or white (the extremes of the data range). In
both cases the size of the neighborhood used for filtering is 3-by-3.
1. Read in the image and display it.
2. I = imread('eight.tif');
imshow(I)
3. Add noise to it.
4. J = imnoise(I,'salt & pepper',0.02);
figure, imshow(J)

5. Filter the noisy image with an averaging filter and display the results.
6. K = filter2(fspecial('average',3),J)/255;
figure, imshow(K)
7. Now use a median filter to filter the noisy image and display the results. Notice that medfilt2 does
a better job of removing noise, with less blurring of edges.
8. L = medfilt2(J,[3 3]);
figure, imshow(L)

ropping an Image
Note You can also crop an image interactively using the Image Tool — see Cropping an Image Using the
Crop Image Tool.

To extract a rectangular portion of an image, use the imcrop function. Using imcrop, you can specify the
crop region interactively using the mouse or programmatically by specifying the size and position of the crop
region.
This example illustrates an interactive syntax. The example reads an image into the MATLAB workspace and
calls imcrop specifying the image as an argument.imcrop displays the image in a figure window and waits
for you to draw the crop rectangle on the image. When you move the pointer over the image, the shape of

the pointer changes to cross hairs . Click and drag the pointer to specify the size and position of the crop
rectangle. You can move and adjust the size of the crop rectangle using the mouse. When you are satisfied
with the crop rectangle, double-click to perform the crop operation, or right-click inside the crop rectangle
and select Crop Image from the context menu. imcrop returns the cropped image in J.
I = imread('circuit.tif')
J = imcrop(I);
You can also specify the size and position of the crop rectangle as parameters when you call imcrop. Specify
the crop rectangle as a four-element position vector, [xmin ymin width height].
In this example, you call imcrop specifying the image to crop, I, and the crop rectangle. imcrop returns
the cropped image in J.
I = imread('circuit.tif');
J = imcrop(I,[60 40 100 90]);

Detecting Edges Using the edge Function

In an image, an edge is a curve that follows a path of rapid change in image intensity. Edges are often
associated with the boundaries of objects in a scene. Edge detection is used to identify the edges in an
image.

To find edges, you can use the edge function. This function looks for places in the image where the intensity
changes rapidly, using one of these two criteria:

 Places where the first derivative of the intensity is larger in magnitude than some threshold

 Places where the second derivative of the intensity has a zero crossing

edge provides a number of derivative estimators, each of which implements one of the definitions above.
For some of these estimators, you can specify whether the operation should be sensitive to horizontal edges,
vertical edges, or both. edge returns a binary image containing 1's where edges are found and 0's
elsewhere.
The most powerful edge-detection method that edge provides is the Canny method. The Canny method
differs from the other edge-detection methods in that it uses two different thresholds (to detect strong and
weak edges), and includes the weak edges in the output only if they are connected to strong edges. This
method is therefore less likely than the others to be fooled by noise, and more likely to detect true weak
edges.

The following example illustrates the power of the Canny edge detector by showing the results of applying
the Sobel and Canny edge detectors to the same image:

1. Read image and display it.


2. I = imread('coins.png');
imshow(I)

3. Apply the Sobel and Canny edge detectors to the image and display them.
4. BW1 = edge(I,'sobel');
5. BW2 = edge(I,'canny');
6. imshow(BW1)
figure, imshow(BW2)

Dilating an Image
To dilate an image, use the imdilate function. The imdilate function accepts two primary arguments:

 The input image to be processed (grayscale, binary, or packed binary image)

 A structuring element object, returned by the strel function, or a binary matrix defining the
neighborhood of a structuring element
imdilate also accepts two optional arguments: SHAPE and PACKOPT. The SHAPE argument affects the size
of the output image. The PACKOPT argument identifies the input image as packed binary. (Packing is a
method of compressing binary images that can speed up the processing of the image. See
the bwpackreference page for information.)

This example dilates a simple binary image containing one rectangular object.
BW = zeros(9,10);
BW(4:6,4:7) = 1
BW =
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 1 1 1 1 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
To expand all sides of the foreground component, the example uses a 3-by-3 square structuring element
object. (For more information about using the strelfunction, see Understanding Structuring Elements.)
SE = strel('square',3)
SE =

Flat STREL object containing 3 neighbors.

Neighborhood:
1 1 1
1 1 1
1 1 1
To dilate the image, pass the image BW and the structuring element SE to the imdilate function. Note how
dilation adds a rank of 1's to all sides of the foreground object.
BW2 = imdilate(BW,SE)

Back to Top

Eroding an Image
To erode an image, use the imerode function. The imerode function accepts two primary arguments:

 The input image to be processed (grayscale, binary, or packed binary image)


 A structuring element object, returned by the strel function, or a binary matrix defining the
neighborhood of a structuring element
imerode also accepts three optional arguments: SHAPE, PACKOPT, and M.
The SHAPE argument affects the size of the output image. The PACKOPT argument identifies the input image
as packed binary. If the image is packed binary, Midentifies the number of rows in the original image.
(Packing is a method of compressing binary images that can speed up the processing of the image. See
thebwpack reference page for more information.)
The following example erodes the binary image circbw.tif:
1. Read the image into the MATLAB workspace.
BW1 = imread('circbw.tif');
2. Create a structuring element. The following code creates a diagonal structuring element object. (For
more information about using the strel function, seeUnderstanding Structuring Elements.)

3. SE = strel('arbitrary',eye(5));

4. SE=

5.
6. Flat STREL object containing 5 neighbors.

7.
8. Neighborhood:

9. 1 0 0 0 0
10. 0 1 0 0 0
11. 0 0 1 0 0
12. 0 0 0 1 0
0 0 0 0 1
13. Call the imerode function, passing the image BW and the structuring element SE as arguments.
BW2 = imerode(BW1,SE);

Notice the diagonal streaks on the right side of the output image. These are due to the shape of the
structuring element.
imshow(BW1)
figure, imshow(BW2)
Morphological Opening
You can use morphological opening to remove small objects from an image while preserving the shape and
size of larger objects in the image. For example, you can use the imopen function to remove all the circuit
lines from the original circuit image, circbw.tif, creating an output image that contains only the
rectangular shapes of the microchips.

To morphologically open the image, perform these steps:

1. Read the image into the MATLAB workspace.


BW1 = imread('circbw.tif');
2. Create a structuring element.
SE = strel('rectangle',[40 30]);

The structuring element should be large enough to remove the lines when you erode the image, but not
large enough to remove the rectangles. It should consist of all 1's, so it removes everything but large
contiguous patches of foreground pixels.

3. Erode the image with the structuring element.


4. BW2 = imerode(BW1,SE);
imshow(BW2)

This removes all the lines, but also shrinks the rectangles.
5. To restore the rectangles to their original sizes, dilate the eroded image using the same structuring
element, SE.

6. BW3 = imdilate(BW2,SE);
imshow(BW3)

Function Morphological Definition

bwhitmiss Logical AND of an image, eroded with one structuring element, and the image's complement,
eroded with a second structuring element.

imbothat
Subtracts the original image from a morphologically closed version of the image. Can be used to
find intensity troughs in an image.

imclose
Dilates an image and then erodes the dilated image using the same structuring element for
both operations.

imopen
Erodes an image and then dilates the eroded image using the same structuring element for
both operations.
Function Morphological Definition

imtophat
Subtracts a morphologically opened image from the original image. Can be used to enhance
contrast in an image.

You might also like