0% found this document useful (0 votes)
117 views

Image Processing With MATLAB: Quick Reference

The document provides an overview of image processing with MATLAB. It discusses loading, displaying, and saving different image types including grayscale, RGB, and indexed images. It also describes preprocessing techniques like adjusting contrast through histogram equalization and adaptive histogram equalization. Block processing is introduced as a way to process images by blocks to make algorithms adaptive, parallelize processing, and work with large images out of memory.

Uploaded by

Edrian Pentado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views

Image Processing With MATLAB: Quick Reference

The document provides an overview of image processing with MATLAB. It discusses loading, displaying, and saving different image types including grayscale, RGB, and indexed images. It also describes preprocessing techniques like adjusting contrast through histogram equalization and adaptive histogram equalization. Block processing is introduced as a way to process images by blocks to make algorithms adaptive, parallelize processing, and work with large images out of memory.

Uploaded by

Edrian Pentado
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

6/3/2021 Image Processing with MATLAB - Quick Reference

Image Processing with MATLAB

1. Course Overview

2. Working with Image Data


Summary: Working with Image Data

Supported File Types


MATLAB supports many file formats that you load with imread . Some file types, like DICOM files used in medical image
equipment, have their own read function and set of processing functions.

For a complete list of file formats accepted by imread , see the documentation page for Supported File Formats.

Extracting Metadata from Image Files


You can extract metadata from image files using by using the imfinfo function.

>> info = imfinfo(filename)

Outputs Inputs
info A structure containing the metadata of filename The filename as a string or
an image file. character vector

The metadata depends on the image type, but may include file size, color type, file format, comments, creation time, and
GPS coordinates. You can extract information from the output structure with dot notation.

info.FieldName

Loading, Displaying, and Saving Different Image Types


There are several kinds of image types in MATLAB.

Grayscale Images RGB Images Indexed Images

Color Intensities from black to white The amount of red, green, and The image represented by n colors
information blue in each pixel in the image

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 1/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Grayscale Images RGB Images Indexed Images

Size 2-dimensional array 3-dimensional array 2-dimensional array of indices from 0


to n − 1 along with a colormap of size
n × 3 where n is the number of

colors

Reading, I = imread("imFile.tif"); I = imread("imFile.tif"); [I,map] = imread("imFile.tif");


displaying, and
saving the imshow(I) imshow(I) imshow(I,map)
image
% use full intensity range imwrite(I,"newName.jpg") imwrite(I,map,"newName.jpg")
imshow(I,[])

imwrite(I,"newName.jpg")

You visually compare two images using the imshowpair function.


>> imshowpair(I,method)

Inputs
I A grayscale, RGB, or binary image.

method An optional string that indicates the


display method.

Using the "montage" method displays the images side by side. If no method is specified, the images are superimposed and
highlighted green where the first image is brighter and magenta where the second image is brighter.

The "montage" method is displayed left. The default is on the right.


Landsat satellite images of Bear Glacier courtesy of the U.S. Geological Survey.

See the documentation for a list of functions to convert between grayscale, RGB, and indexed images. You can use the
imapprox function to reduce the number of colors in an indexed image.

Image Data Types


By default, images are imported into MATLAB as uint8 , an integer data type with values from 0 to 255. To avoid rounding
and saturation in computation, you may need to convert your image to type double using the im2double function.

Images of type double have values in the range from 0 to 1. However, your computations are not required to stay within that
range. After completing your computations, you can rescale your image back to the range 0 to 1.

rescale Scale all pixels to between 0 and 1.

imadjust Scale all pixels to between 0 and 1 while saturating the bottom and top 1%.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 2/30
6/3/2021 Image Processing with MATLAB - Quick Reference

See the documentation for a complete list of image data types.

Binary Images
Binary images are 2-dimensional logical arrays. They can be created by thresholding with relational operators ( < , > , <=<
code>, >= ) and manipulated with logical operators like ~ .

You can burn a binary mask onto an image using imoverlay . Once you have created the burned image, you
can use imshow to display it.

>> B = imoverlay(A,mask,color)

Outputs Inputs
B An RGB image. A A grayscale or RGB image.

mask The binary image you want to burn


onto A .

color Optional. A MATLAB color


specification or RGB triplet with
intensities between 0 and 1.

3. Preprocessing
Summary: Preprocessing

Adjusting Contrast
You may need to adjust contrast to improve appearance of an image or the performance of an image processing algorithm.
Below are some techniques and their effects on this dimly illuminated medical slide and its intensity histogram.

Medical slide images from the "C.elegans infection live/dead image set Version 1" provided by Fred Ausubel and available
from the Broad Bioimage Benchmark Collection.

Method Command Effect on an Image Intensity Histogram

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 3/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Method Command Effect on an Image Intensity Histogram

Histogram Stretching I2 = imadjust(I);


Stretch the intensity histogram to span
the entire range. The bottom and top
See the documentation
1% of the intensities are saturated to
for finer control of input
emphasize the difference between
and output intensity limits.
very bright and very dark regions.

Histogram Equalization I2 = histeq(I);


Stretch the intensity histogram to
approximate a uniform distribution.
See the documentation to
fit the intensity histogram
to other distributions.

Adaptive Histogram Equalization I2 = adapthisteq(I);


Enhance contrast locally. The
transformed histogram does not
See the documentation to
necessarily take up the entire intensity
fit the intensity histogram
range.
to other distributions.

Block Processing
You can process your image by blocks by wrapping your algorithm in a block processing function and passing it to
blockproc . This is helpful to
make your own algorithm adaptive,
parallelize your algorithm, and
work with large data files out of memory by reading, processing, and writing output one block at a time.

function newBlock = functionName(blockStruct )

% blockStruct is a structure containing data


sz = blockStruct.blockSize;
blckData = blockStruct.data;

% algorithm using extracted block information


newBlock = rescale(blc kData)

end

imBP = blockproc(im,blockSize,@functionName);

The block processing function can be an anonymous or local function within the file or be contained in a separate file on the
path. The input is a block struct with fields containing information about the block being processed.

blockIm = blockStruct.data % image data for the current block


blockSz = blockStruct.blockSize % size of the block of data
imSz = blockStruct.imageSize % size of the original image

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 4/30
6/3/2021 Image Processing with MATLAB - Quick Reference

See the documentation for blockproc for other parameters, fields of the block struct, and instructions for processing images
out of memory.

Spatial Filtering
Spatial filtering can be used to smooth images and reduce noise. This can improve the appearance of an image or the output
of an image processing algorithm. When filtering an image, you often balance removing noise with blurring detail.

Method Syntax Effect on Image of 5-by-5 Filter

Linear Filter avg = fspecial("average",[m n]);


You can create your own linear filter. imAvg = imfilter(I,avg,"symmetric");
The code for an averaging filter with
symmetric padding is here.

See the documentation for other


types of filters and border padding.

Median Filter imMed = medfilt2(I,[m n],"symmetric");


Take the median value within a
neighborhood. This is good at
removing salt and pepper noise
while preserving edges.

See the documentation for other


types of border padding.

Wiener Filter imMed = wiener2(I,[m n]);


The Wiener filter is an adaptive filter
that smooths less in areas of high
variation (therefore preserving
edges) and more in areas of low
variation, like the background.

Image Quality Metrics


There are two types of quality metrics depending on the type of image and your application—full-reference and no-reference
metrics. The type of image quality metric you use depends on whether or not you have a reference image with no distortion.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 5/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Full-reference metrics No-reference metrics


psnr brisque
mse nique
ssim piqe
multissim

For example:
scoreFullRef = psnr(I,ref)
scoreNoRef = niqe(I)

Background Subtraction
When the background is dark, you can use imtophat to perform background subtraction. The neighborhood needs to be
large enough to include a bit of background when covering a foreground object.
I2 = imtophat(I,nhood);

Use imbothat when the background is bright. This inverts the intensities. You can use imcomplement to make the
foreground (the text below) dark again.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 6/30
6/3/2021 Image Processing with MATLAB - Quick Reference

I2 = imbothat(I,nhood);

4. Segmenting Based on Color


Summary: Segmenting Based on Color

Thresholding by Color
You can threshold one or more color planes to identify pixels with desired color profiles. You can threshold programmatically
(as shown below), or by using the Color Thresholder app.

imgRGB = imread("strawberryPlant.jpg");
imshow(imgRGB)

Import and display the image.

imgLab = rgb2lab(imgRGB);
[L,a,b] = imsplit(imgLab);
Convert the image to the desired color space and extract imshow(a,[])
the color planes.

The a* plane contains values outside the range 0 to 1. Use


imshow with the second input [] to display the scaled
image.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 7/30
6/3/2021 Image Processing with MATLAB - Quick Reference

histogram(a)

Examine a histogram of the color plane's values.

redMask = a > 21;


imshow(redMask)

Segment the image by thresholding the color plane.

Color Spaces
Color spaces represent color in an image in different ways.

Color Space Channels Description

RGB R - red intensities Elements represent the intensities of the red, green, and blue color
G - green intensities channels. The range depends on the data type: for example, 0 to 255 for
B - blue intensities uint8 arrays, and 0 to 1 for double arrays.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 8/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Color Space Channels Description

HSV H - hue
Hue corresponds to the color’s
S - saturation
position on a color wheel.
V - value
Saturation is the amount of hue,
or departure from neutral (shades
of gray). Value quantifies
brightness. Hue, saturation, and
value all have the range 0 to 1.

L*a*b* L* - luminance Luminance represents brightness from black (0) to white (100). The a*
a* - hue from green to red channel and b* channel represent the balance between two hues, and
b* - hue from blue to yellow although there is no single range for a* and b*, values commonly fall in the
range [-100, 100] or [-128, 127).

Segmenting Based on a Region's Average Color

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 9/30
6/3/2021 Image Processing with MATLAB - Quick Reference

imshow(img)
roi = drawpolygon;

Identify the ROI by displaying the image then


calling drawpolygon .

Here, the blue polygon indicates the region of


interest.

Create a mask to isolate the pixels in the


BW = createMask(roi);
selected region.

imgLab = rgb2lab(img);
[L,a,b] = imsplit(imgLab);
Convert to the Lab color space, and calculate aROI = a(BW);
the average pixel color in the region. bROI = b(BW);

meanROI = [mean(aROI) mean(bROI)];

aMean = meanROI(1);
bMean = meanROI(2);
distLab = sqrt((a - aMean).^2 + (b - bMean).^2);
Create a distance matrix by calculating the imshow(distLab,[])
distance between the average color and every
pixel in the image.
G
(a ∗
− amean ) 2
+ (b ∗
− bmean ) 2

Colors similar to the sample color appear dark,


and dissimilar colors appear bright.

mask = distLab < 25;

nearColor = imoverlay(img,~mask,"k");
imshow(nearColor)

Threshold the distance matrix to identify pixels


similar to the sample color.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 10/30
6/3/2021 Image Processing with MATLAB - Quick Reference

5. Detecting and Analyzing Texture


Summary: Detecting and Analyzing Texture

Segmenting Based on Texture


Texture quantifies the variation of intensity values in an image. Segmentation by texture uses spatial filtering to identify
regions with high or low variation.

zebras = imread("zebras.jpg");
zebras = im2gray(zebras);
imshow(zebras)

Import an image and convert it to grayscale.

nHood = true(7);
zebraRNG = rangefilt(zebras,nHood);
imshow(zebraRNG)
Apply a texture filter to the image. By default, the filter uses a 3-
by-3 neighborhood; defining nHood is optional.

Use rescale to rescale the image when using a standard


deviation or entropy filter.

zebraBW = imbinarize(zebrasRNG);
imshow(zebraBW)

Binarize the filtered image.

Texture Filters
There are three types of filters: range filter, standard deviation filter, and entropy filter. Each filter looks at a neighborhood
around each pixel and replaces that pixel with a measure of the texture around it.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 11/30
6/3/2021 Image Processing with MATLAB - Quick Reference

rangefilt Perform range filtering.

stdfilt Perform standard deviation filtering.

entropyfilt Perform entropy filtering.

Measuring Texture Properties


There are four statistics that can be used to measure texture and patterns in images: contrast, correlation, homogeneity, and
energy. The statistics are calculated based on a specified spatial relationship, called an offset. If you change the offset, you
change the statistics.

Defining the Offset


The offset is defined in terms of how many rows and columns it is away from the pixel of interest.

Calculating Texture Statistics


There are three steps to calculate the texture statistics of a grayscale or binary image: define an offset, calculate the gray-
level co-occurrence matrix, and then calculate the statistics from that matrix.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 12/30
6/3/2021 Image Processing with MATLAB - Quick Reference

z = imread("zebras.jpg");
z = im2gray(z);
imshow(z)

Import an image and convert it to grayscale.

offsets = [-1 0;-3 0;-7 0;-14 0]

Define the offset. You can analyze several offsets =


offsets at once using an n-by-2 matrix where -1 0
each row is an offset. -3 0
-7 0
-14 0

glcm = graycomatrix(z,"Offset",offsets);
Calculate the gray-level co-occurrence matrix. stats = graycoprops(glcm)
When there are multiple offsets, the result is a
three-dimensional array with a plane for each stats =
offset. struct with fields:

Calculate the statistics using the graycoprops Contrast: [0.2680 1.1227 3.5026 7.8766]
function. The statistics are calculated for each Correlation: [0.9834 0.9305 0.7830 0.5112]
offset. Energy: [0.1766 0.1515 0.1226 0.0867]
Homogeneity: [0.9029 0.8388 0.7645 0.6554]

glcmSum = sum(glcm,3);
stats = graycoprops(glcmSum)

One way to combine all offsets is to combine the stats =


planes by summing across the third dimension. struct with fields:
Then calculate the statistics of the resulting
matrix. Contrast: 3.0821
Correlation: 0.8091
Energy: 0.1318
Homogeneity: 0.7938

graycomatrix Create a gray-level co-occurrence matrix (GLCM) from an image.

graycoprops Calculate statistics of gray-level co-occurrence matrix.

6. Improving Segmentations

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 13/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Summary: Improving Segmentations

Cleaning Binary Masks

A flatfish camouflaged in the sand and an initial segmentation based on texture.

Cleaning Functions
There are several functions to remove stray noise from a mask.
BW2 = bwareaopen(BW,n);

Remove pieces of foreground that are smaller than n pixels.

BW2 = imclearborder(BW);

Remove foreground along the boundary.

BW2 = imfill(BW,"holes");

Fill holes.

Morphological Operations
Morphological operations are shape-based filtering operations that replace pixels with the minimum or maximum of a
neighborhood or some combination of these.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 14/30
6/3/2021 Image Processing with MATLAB - Quick Reference

The four main operations are erosion, dilation, opening, and closing. Let's see the effect on this mask.

A binary image with a disk-shaped structuring element marked in blue.

SE = strel("disk",n);
Create a disk shaped structuring element with
radius r .

BW2 = imerode(BW,SE);

Erode a binary mask.

BW2 = imdilate(BW,SE);

Dilate a binary mask.

BW2 = imopen(BW,SE);

An opening operation first erodes then dilates an image. This has


the effect of removing small areas of foreground surrounded by
background while keeping the remaining objects approximately
the same size.

BW2 = imclose(BW,SE);

A closing operation first dilates then erodes an image. This has


the effect of closing small areas of background that protrude into
foreground while keeping the objects approximately the same
size.

Growing a Mask from a Seed


Active contours and fast marching method (FMM) are two methods you can use to grow a mask from a seed.

Active Contours
Active contours expands or shrinks edges of a seed to grow to the boundary of a region. This often works well when you
have a decent initial guess at the shape.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 15/30
6/3/2021 Image Processing with MATLAB - Quick Reference

An initial segmentation of a river (left) expanded to identify the flood water with active contours (right).
Flood waters in Montezuma Wash courtesy of the National Park Service.

You can use the activecontour function to grow a seed mask to fill a region based on the original image.

>> BW = activecontour(I,mask,n,"method")

Outputs Inputs
BW The output mask I The original image

mask The seed mask

n The number of iterations

"method" The method to use ( "Chan-Vese" or "edge" )

Use the "ContractionBias" property to control whether the segmentation tends to contract (positive
values) or grow (negative values). The values are between -1 and 1, and the defaults are 0 and 0.3
for the Chan-Vese and edge methods respectively.

Use the "SmoothFactor" property to control the smoothness or regularity of the edges. Higher
values produce smoother region boundaries but can also smooth out details. Lower values allow finer
details to be captured. The default smoothness value is 0 for the Chan-Vese method and 1 for the
edge method. Typical values for this parameter are between -1 and 1. The values are between -1 and
1, and the defaults are 0 and 0.3 for the Chan-Vese and edge methods respectively.

BW = activecontour(I,mask,n,"Chan-Vese",...
"ContractionBias",-0.4,...
"SmoothFactor",0.3);

Fast Marching Method (FMM)


When you have an initial mask that marks the approximate locations of areas of foreground, FMM can be a good method to
try.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 16/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Bison at Yellowstone National Park courtesy of the National Park Service.

For FMM, you need the seed mask and a grayscale image that approximately marks the shapes of the objects you want to
identify. There are several ways to do this.

wts = graydiffweight(gs,0);
imshow(log(wts),[])

Create a grayscale intensity difference array


where each element is the pixel's distance
from a specified threshold, here 0.

wts = graydiffweight(gs,mask);
imshow(log(wts),[])

Create a weight array that represents each pixel's


distance from the average intensity in the region of
the initial segmentation.

wts = gradientweight(gs,"RolloffFactor",3.8);
imshowpair(gs,wts,"montage");

Create a weight array where each weight is


inversely proportional to the gradient values at that
pixel location.

>> BW = imsegfmm(wts,mask,threshold)

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 17/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Outputs Inputs
BW The output mask wts A grayscale weight array where
images in the foreground are
bright

mask An initial seed that marks the


locations of foreground objects

threshold Threshold level used to obtain the


binary image between [0, 1].
Lower values typically result in
larger foreground regions.

Image Segmenter App


You can use the Image Segmenter App for creating masks and improving them with morphological operations, iterative
growing methods, and other interactive options. You can experiment with different techniques and toggle between
segmentation results.

Find it in the Apps tab under "Image Processing and Computer Vision" or type imageSegmenter at the command prompt.

Depressions and Channels on the Floor of Lyot Crater


Image credit: NASA/JPL-Caltech/University of Arizona.

7. Finding and Analyzing Objects


Summary: Finding and Analyzing Objects

What Are Connected Components?


Connected components are separate regions of foreground, a collection of pixels that are all touching. There are two types of
connectivity.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 18/30
6/3/2021 Image Processing with MATLAB - Quick Reference

This image has 3 connected components using 4-connectivity and 2 if you are using 8-connectivity.

Working with Connected Components


There are several functions you can use to identify and filter connected components. Consider this binarization of coins on a
table.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 19/30
6/3/2021 Image Processing with MATLAB - Quick Reference

nickel = bwpropfilt(coinsMask,"Area",[2000 3000]);

Filter all components of a certain area (e.g.


number of pixels)

nickel = bwpropfilt(coinsMask,"Area",6,"largest");

You can also filter the n largest (or smallest)


connected components based on a given
property

coinsCC = bwconncomp(coinsBW)
nickelCC = struct with fields
Find connected components in a binary Connectivity: 8
mask ImageSize: [246 300]
NumObjects: 10
PixelIdList: {[2651x1 double] ...}

numCoins = coinsCC.NumObjects
You can access information about the
connected components using dot notation 10

coinsLab = labelmatrix(coinsCC);
imshow(coinsLab,[])

Create a label matrix that assigns a different


number to pixels in each connected
component.

coinsRGB = label2rgb(coinsLab,"jet","k","shuffle");
imshow(coinsRGB)

Convert a label matrix to an RGB image.

Separating Overlapping Objects with Watershed


You can apply the watershed algorithm to separate overlapping connected components.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 20/30
6/3/2021 Image Processing with MATLAB - Quick Reference

d = bwdist(~BW);
imshow(d,[])

Create a grayscale image that marks the separate


objects. Here the distance transform roughly
identifies the bison.

d = imcomplement(d);
imshow(d,[])

If needed, take the complement of the grayscale


image so that the background is bright.

dHmin = imhmin(d,5);
bisonSep = watershed(dHmin);
imshow(bisonSep,[])
Even out the gray values to remove small minima.
This will prevent oversegmentation by the watershed
algorithm. Then apply watershed to the grayscale
image.

bisonSep(~bisonBW) = 0;
imshow(bisonSep,[])

Set the background to black to visualize the bison.

bisonOverlay = labeloverlay(bison,bisonSep);
imshow(bisonOverlay)

Overlay the connected components on the original


image.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 21/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Measuring Shape Properties


You can use the regionprops function to calculate measurements about connected components from a label matrix or a
binary mask. See the documentation for a list of measurements.

>> stats = regionprops("table",L,props)

Outputs Inputs
stats A table or structure with the requested "table" The format of the output. You can
statistics also specify "struct" .

L A label image or binary mask

props A string array specifying the


properties you want to extract

8. Detecting Edges and Shapes


Summary: Detecting Edges and Shapes

Detecting edges in grayscale images

You can detect object edges in grayscale images using edge .

edge Finds edges in a grayscale image

The edge function uses the "Sobel" method by default. This method detects edges by thresholding the gradient magnitude.

If the default edge detection is not sensitive enough, try using the "Canny" method, which applies two thresholds. A lower
threshold is applied to pixels connected to strong edges in order to keep more of the edge.

Detecting edges in binary images

For binary images, use bwboundaries to detect edges.

bwboundaries Finds edges in a binary image

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 22/30
6/3/2021 Image Processing with MATLAB - Quick Reference

The function bwboundaries is typically used as part of a larger workflow.

I = imread("oranges.jpg")
BW = createMask(I);
BWadj = imopen(BW,strel("disk",5));
BWadj = imclose(BWadj,strel("disk",5));
imshow(BWadj)

Create and filter a binary mask.


Note: createMask was generated by the Color
Thresholder app.

B = bwboundaries(BWadj,"noholes")
imshow(I);
hold on
visboundaries(B)
hold off

Find edges in the binary image and visualize them.

Detecting circles

You can detect circles using imfindcircles .

imfindcircles Finds circles in an image using the circular Hough transform

Detecting straight lines

You can detect straight lines using the Hough transform workflow.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 23/30
6/3/2021 Image Processing with MATLAB - Quick Reference

The Hough workflow requires the use of three hough- functions.

BW = imread("smiley.png");

Load or create a binary mask.

[H,theta,rho] = hough(BW);

Compute the Hough transform matrix

hough

peaks = houghpeaks(H);

Find the peaks in the Hough


transform

houghpeaks

lines = houghlines(BW,theta,rho,peaks);

Find straight lines in the binary image.

houghlines

9. Batch Processing
Summary: Batch Processing
Batch processing workflows
MATLAB has two primary ways to batch process images: the Image Batch Processor app (interactive) and image datastores
(programmatic).

Image Batch Processor app Programmatic workflow using datastores

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 24/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Image Batch Processor app Programmatic workflow using datastores

Select folder and load images Create an image datastore


ds = imageDatastore("imageFolder")
and read images
Load
Images I = read(ds);

Create and select a compatible processing function Create a function that processes an image
Function name med = medianWormLength(I)
medianWormLength

Process some or all of the images Loop through the datastore and process images
while hasdata(ds)

Process
all
end

The Image Batch Processor App


Processing function
The processing function must be a MATLAB function with one input and one output, where:
1. the input is a single image represented as a MATLAB variable (not a filename), and
2. the output is a structure whose fields contain the results of the processing.

function result = processFcn(img)


result.minValue = min(img,[],"all");
result.maxValue = max(img,[],"all");
end

Example of a correctly formatted processing function

Export options
1. Export results: Save selected results in a workspace variable. By default, the app returns the results in a table.
2. Generate function: Create a MATLAB function file that can be called later to batch process images in a folder.

Image datastores
A datastore stores the location and other basic metadata for image files, without actually loading them into memory. When
you need an image from a datastore, you can load it with a call to read .
ds = imageDatastore("dataFolder")

ds

I read(ds)

If you wish to include subdirectories when creating the datastore and create labels based on the folders in which the data
resides, use the "IncludeSubfolders" and "LabelSource" options.
ds = imageDatastore("data","IncludeSubfolders",true,"LabelSource","foldernames")

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 25/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Additional functions used in the image datastore workflow are summarized in the table below.

Function or keyword Example usage What it does

read I = read(ds) Reads the next image in ds

readimage I = readimage(ds,k) Reads the k th image in ds

hasdata hasdata(ds) Determines if any images remain to


be read

countEachLabel T = countEachLabel(ds) Counts how many images have


each label in ds

while while <condition> Executes body code until


… <condition> returns false
end

10. Aligning Images with Image Registration


Summary: Aligning Images with Image Registration

Defining a Known Geometric Transformation

This flower has been rotated approximately ∘


45 , scaled by 0.5 and translated to the upper right part of the frame.

I2 = imrotate(I,angle); % rotate an image (angle in degrees counterclockwise)


I2 = imresize(I,scale); % scale an image
I2 = imtranslate(I,[x y]); % translate an image

Estimating a Geometric Transformation


When you don't know the exact rotation, scale, or translation, you can perform phase correlation with imregcorr to estimate
the transformation matrix.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 26/30
6/3/2021 Image Processing with MATLAB - Quick Reference

tForm = imregcorr(moving,fixed,type)
spRef = imref2d(szFixed);
transformed = imwarp(moving,tForm,"OutputView",spRef);

Transformation Description Example


Type

"translation" Translation

"rigid" Translation and rotation

"similarity" Translation, rotation, and scaling


(default)
imregcorr does not detect scale differences less than 1/4 or
greater than 4.

Mapping Control Points

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 27/30
6/3/2021 Image Processing with MATLAB - Quick Reference

cpselect(movIm,fixedIm)
Open the Control Point Selection Tool and
select the required number of control points.

movPtsCor = cpcorr(movPts,fixPts,movIm,fixIm);
Use cross-correlation to fine-tune control
points.

tForm = fitgeotrans(movingPts,fixedPts,type)
Fit a geometric transformation of a specified
type.

spRef = imref2d(size(fixIm))
Create a spatial referencing object.

movTransf = imwarp(movIm,tForm,"OutputView",spRef);
Warp the image.

Depending on the complexity of the transformation, some transformation types require more control points for estimation.

Transformation Description Minimum Example


Type Number
of Control
Points

"nonreflective Translation, rotation, scaling 2


similarity"
Use this transformation when shapes in the
moving image keep their form. Straight lines
remain straight, parallel lines remain parallel,
and angles between lines are preserved.

"similarity" The same as "nonreflective similarity" , 3


but also includes reflection.

"affine" Shearing 3

Unlike the previous transformations, shapes


are distorted. Straight lines remain straight,
parallel lines remain parallel, but angles are not
preserved (rectangles become parallelograms).

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 28/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Transformation Description Minimum Example


Type Number
of Control
Points

"projective" Projective Transformation 4

Use this transformation when the scene


appears tilted. Straight lines remain straight,
but parallel lines converge toward a vanishing
point.

There are other nonlinear geometric transformations you can estimate using control points. You can find a list of the
supported transformation types in the documentation, along with descriptions and the number of control points to required to
fit a transformation.

Matching Image Features


Three types of features are corners, regions, and blobs.

Feature Example

Corners
In Computer Vision Toolbox, you can detect
corner features using FAST, Harris, and
Brisk techniques.

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 29/30
6/3/2021 Image Processing with MATLAB - Quick Reference

Feature Example

Regions
Regions are calculated using the MSER
algorithm.

Blobs
Blobs are circular or elliptical regions
identified with the SURF algorithm.

Image Courtesy: National Eye Institute, National Institutes of Health NEI/NIH)

Run the registrationEstimator command to test different techniques and parameters using the Registration Estimator
App.

11. Conclusion

https://matlabacademy.mathworks.com/artifacts/quick-reference.html?course=mlip&release=R2021a&language=en 30/30

You might also like