Image Processing With MATLAB: Quick Reference
Image Processing With MATLAB: Quick Reference
1. Course Overview
For a complete list of file formats accepted by imread , see the documentation page for Supported File Formats.
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
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
colors
imwrite(I,"newName.jpg")
Inputs
I A grayscale, RGB, or binary image.
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.
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.
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.
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
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.
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.
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
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.
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.
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.
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
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);
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)
imgLab = rgb2lab(imgRGB);
[L,a,b] = imsplit(imgLab);
Convert the image to the desired color space and extract imshow(a,[])
the color planes.
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)
Color Spaces
Color spaces represent color in an image in different ways.
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
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).
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;
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);
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
nearColor = imoverlay(img,~mask,"k");
imshow(nearColor)
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
zebras = imread("zebras.jpg");
zebras = im2gray(zebras);
imshow(zebras)
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.
zebraBW = imbinarize(zebrasRNG);
imshow(zebraBW)
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
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)
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)
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
Cleaning Functions
There are several functions to remove stray noise from a mask.
BW2 = bwareaopen(BW,n);
BW2 = imclearborder(BW);
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.
SE = strel("disk",n);
Create a disk shaped structuring element with
radius r .
BW2 = imerode(BW,SE);
BW2 = imdilate(BW,SE);
BW2 = imopen(BW,SE);
BW2 = imclose(BW,SE);
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
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);
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
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),[])
wts = graydiffweight(gs,mask);
imshow(log(wts),[])
wts = gradientweight(gs,"RolloffFactor",3.8);
imshowpair(gs,wts,"montage");
>> 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
Find it in the Apps tab under "Image Processing and Computer Vision" or type imageSegmenter at the command prompt.
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.
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",6,"largest");
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,[])
coinsRGB = label2rgb(coinsLab,"jet","k","shuffle");
imshow(coinsRGB)
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,[])
d = imcomplement(d);
imshow(d,[])
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,[])
bisonOverlay = labeloverlay(bison,bisonSep);
imshow(bisonOverlay)
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
Outputs Inputs
stats A table or structure with the requested "table" The format of the output. You can
statistics also specify "struct" .
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.
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
I = imread("oranges.jpg")
BW = createMask(I);
BWadj = imopen(BW,strel("disk",5));
BWadj = imclose(BWadj,strel("disk",5));
imshow(BWadj)
B = bwboundaries(BWadj,"noholes")
imshow(I);
hold on
visboundaries(B)
hold off
Detecting circles
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
BW = imread("smiley.png");
[H,theta,rho] = hough(BW);
hough
peaks = houghpeaks(H);
houghpeaks
lines = houghlines(BW,theta,rho,peaks);
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).
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
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
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.
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);
"translation" Translation
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.
"affine" Shearing 3
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
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.
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.
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