Computer Vision System Toolbox Getting Started Guide
Computer Vision System Toolbox Getting Started Guide
R2016a
www.mathworks.com
www.mathworks.com/sales_and_services
User community:
www.mathworks.com/matlabcentral
Technical support:
www.mathworks.com/support/contact_us
Phone:
508-647-7000
Trademarks
MATLAB and Simulink are registered trademarks of The MathWorks, Inc. See
www.mathworks.com/trademarks for a list of additional trademarks. Other product or brand
names may be trademarks or registered trademarks of their respective holders.
Patents
MathWorks products are protected by one or more U.S. patents. Please see
www.mathworks.com/patents for more information.
Revision History
April 2011
September 2011
March 2012
September 2012
March 2013
September 2013
March 2014
October 2014
March 2015
September 2015
March 2016
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Online only
Contents
Product Overview
Computer Vision System Toolbox Product Description . . . .
Key Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1-2
1-2
2-2
2-3
2-4
2-4
Coordinate Systems
Coordinate Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Pixel Indices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Spatial Coordinates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-D Coordinate Systems . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3-2
3-2
3-2
3-3
vi
Contents
System Objects
What Is a System Toolbox? . . . . . . . . . . . . . . . . . . . . . . . . . . . .
4-2
4-3
4-5
4-5
4-5
4-6
4-8
4-9
4-10
4-10
4-14
4-15
4-15
4-15
4-16
4-16
4-16
4-18
4-18
4-18
4-19
4-19
4-19
4-20
4-22
4-22
4-22
4-23
4-23
4-24
4-25
4-25
4-27
4-28
4-28
4-31
4-31
4-36
4-37
5-2
5-4
6-2
6-3
6-3
6-4
vii
1
Product Overview
Product Overview
Key Features
Object detection and tracking, including the Viola-Jones, Kanade-Lucas-Tomasi
(KLT), and Kalman filtering methods
Training of object detection, object recognition, and image retrieval systems, including
cascade object detection and bag-of-features methods
Camera calibration for single and stereo cameras, including automatic checkerboard
detection and an app for workflow automation
Stereo vision, including rectification, disparity calculation, and 3-D reconstruction
3-D point cloud processing, including I/O, visualization, registration, denoising, and
geometric shape fitting
Feature detection, extraction, and matching
Support for C-code generation and fixed-point arithmetic with code generation
products
1-2
2
Computer Vision Algorithms and
Video Processing
Computer Vision Capabilities on page 2-2
Video Processing in MATLAB on page 2-3
Computer Vision System Toolbox Preferences on page 2-4
2-2
2-3
2-5
3
Coordinate Systems
Coordinate Systems
Coordinate Systems
You can specify locations in images using various coordinate systems. Coordinate
systems are used to place elements in relation to each other. Coordinates in pixel and
spatial coordinate systems relate to locations in an image. Coordinates in 3-D coordinate
systems describe the 3-D positioning and origin of the system.
Pixel Indices
Pixel coordinates enable you to specify locations in images. In the pixel coordinate
system, the image is treated as a grid of discrete elements, ordered from top to bottom
and left to right.
For pixel coordinates, the number of rows, r, downward, while the number of columns, c,
increase to the right. Pixel coordinates are integer values and range from 1 to the length
of the row or column. The pixel coordinates used in Computer Vision System Toolbox
software are one-based, consistent with the pixel coordinates used by Image Processing
Toolbox and MATLAB. For more information on the pixel coordinate system, see Pixel
Indices in the Image Processing Toolbox documentation.
Spatial Coordinates
Spatial coordinates enable you to specify a location in an image with greater granularity
than pixel coordinates. Such as, in the pixel coordinate system, a pixel is treated as a
discrete unit, uniquely identified by an integer row and column pair, such as (3,4). In
the spatial coordinate system, locations in an image are represented in terms of partial
pixels, such as (3.3, 4.7).
3-2
Coordinate Systems
For more information on the spatial coordinate system, see Spatial Coordinates in the
Image Processing Toolbox documentation.
Z
X
3-3
Coordinate Systems
X
camera 1
camera 2
Y
When you reconstruct a 3-D scene using a calibrated stereo camera, the
reconstructScene and triangulate functions return 3-D points with the origin at
the optical center of Camera 1. When you use Kinect images, the depthToPointCloud
function returns 3-D points with the origin at the center of the RGB camera.
Calibration Pattern-Based Coordinate System
Points represented in a calibration pattern-based coordinate system are described with
the origin located at the (0,0) location of the calibration pattern.
X
Y
When you reconstruct a 3-D scene from multiple views containing a calibration pattern,
the resulting 3-D points are defined in the pattern-based coordinate system. The
Structure From Motion From Two Views example shows how to reconstruct a 3-D scene
from a pair of 2-D images containing a checkerboard pattern.
Related Examples
3-4
Coordinate Systems
3-5
4
System Objects
What Is a System Toolbox? on page 4-2
What Are System Objects? on page 4-3
System Objects vs. MATLAB Functions on page 4-5
System Design and Simulation in MATLAB on page 4-8
System Design and Simulation in Simulink on page 4-9
System Objects in MATLAB Code Generation on page 4-10
System Objects Methods That Support Code Generation on page 4-16
System Objects in Simulink on page 4-18
System Object Methods on page 4-19
System Design in MATLAB Using System Objects on page 4-22
System Design in Simulink Using System Objects on page 4-31
System Objects
4-2
System Objects
In addition to the System objects provided with System Toolboxes, you can also create
your own System objects. See Define System Objects.
4-4
Obtain the total number of samples and the sampling rate from the source file.
audioInfo = audioinfo(fname);
maxSamples = audioInfo.TotalSamples;
fs = audioInfo.SampleRate;
4-5
System Objects
Define the amount of audio data to process at one time, and initialize the while loop
index.
frameSize = 1024;
nIdx = 1;
The loop uses explicit indexing and state management, which can be a tedious and errorprone approach. You must have detailed knowledge of the states, such as, sizes and
data types. Another issue with this MATLAB-only code is that the sound function is not
designed to run in real time. The resulting audio is very choppy and barely audible.
4-6
This System objects code avoids the issues present in the MATLAB-only code. Without
requiring explicit indexing, the file reader object manages the data frame sizes while the
filter manages the states. The audio device writer object plays each audio frame as it is
processed.
4-7
System Objects
4-8
Create individual components Create the System objects to use in your system.
See Create Components for Your System on page 4-22. In addition to the
System objects provided with System Toolboxes, you can also create your own
System objects. See Define System Objects.
Assemble components into system Write a MATLAB program that includes those
System objects, connecting them using MATLAB variables as inputs and outputs to
simulate your system. See Connecting System Objects on page 4-25.
Run the system Run your program, which uses the step method to run your
systems System objects. You can change tunable properties while your system is
running. See Run Your System on page 4-27 and Reconfiguring Objects on
page 4-28.
Create a System object to be used in your model. See Define New Kinds of System
Objects for Use in Simulink on page 4-31 for information.
Test your new System object in MATLAB. See Test New System Objects in
MATLAB on page 4-36
Add the System object to your model using the MATLAB System block. See Add
System Objects to Your Simulink Model on page 4-37 for information.
Add other Simulink blocks as needed and connect the blocks to construct your
system.
4-9
System Objects
4-10
For another detailed code generation example, see Generate Code for MATLAB Handle
Classes and System Objects in the MATLAB Coder product documentation.
Usage Rules and Limitations for System Objects for Generating Code
The following usage rules and limitations apply to using System objects in code
generated from MATLAB.
Object Construction and Initialization
If objects are stored in persistent variables, initialize System objects once by
embedding the object handles in an if statement with a call to isempty( ).
4-11
System Objects
System Objects
isInputDirectFeedThroughImpl
outputImpl
processTunedPropertiesImpl
releaseImpl Code is not generated automatically for the this method. To
release an object, you must explicitly call the release method in your code.
resetImpl
setupImpl
stepImpl
updateImpl
validateInputsImpl
validatePropertiesImpl
Code generation support for using dot notation depends on whether the System object
is predefined in the software or is one that you defined.
For System objects that are predefined in the software, you cannot use dot
notation to call methods.
For System objects that you define, you can use dot notation or function call
notation, with the System object as first argument, to call methods.
4-14
4-15
System Objects
getInputNamesImpl
getIconImpl
getOutputDataTypeImpl
getOutputNamesImpl
getOutputSizeImpl
getPropertyGroupsImpl
isInactivePropertyImpl
isOutputComplexImpl
loadObjectImpl
propagatedInputComplexity
propagatedInputDataType
propagatedInputFixedSize
propagatedInputSize
saveObjectImpl
supportsMultipleInstanceImpl
4-17
System Objects
4-18
System Objects
Common Methods
All System objects support the following methods, each of which is described in a method
reference page associated with the particular object. In cases where a method is not
applicable to a particular object, calling that method has no effect on the object.
Method
Description
step
4-20
release
reset
getNumInputs
getNumOutputs
getDiscreteState
clone
Creates another object of the same type with the same property
values
isLocked
Method
Description
isDone
info
For a complete list of methods for writing new System objects, see System Objects
Methods for Defining New Objects.
4-21
System Objects
Predefined Components
The example in the next section shows how to use System objects that are predefined in
the software. If you use a function to create and use a System object, specify the object
creation using conditional code. This will prevent errors if that function is called within a
loop.
You can also create your own System objects (see Define System Objects).
hVideoSrc = vision.VideoFileReader;
hAB = vision.AlphaBlender;
hVideoOrig = vision.VideoPlayer;
hVideoEdges = vision.VideoPlayer;
hVideoOverlay = vision.VideoPlayer;
Component Properties
When to Configure Components
If you did not set an object's properties when you created it and do not want to use
default values, you must explicitly set those properties. Some properties allow you to
change their values while your system is running. See Reconfiguring Objects on page
4-28 for information.
Most properties are independent of each other. However, some System object properties
enable or disable another property or limit the values of another property. To avoid
errors or warnings, you should set the controlling property before setting the dependent
property.
Display Component Property Values
To display the current property values for an object, type that objects handle name at
the command line (such as audioIn). To display the value of a specific property, type
objecthandle.propertyname (such as audioIn.FileName).
System Objects
hVideoSrc.Filename = 'vipmen.avi';
hVideoSrc.ImageColorSpace = 'Intensity';
hAB.Operation = 'Highlight selected pixels';
WindowSize = [190 150];
hVideoOrig.Name = 'Original';
hVideoOrig.Position = [10 hVideoOrig.Position(2) WindowSize];
hVideoEdges.Name = 'Edges';
hVideoEdges.Position = [210 hVideoOrig.Position(2) WindowSize];
hVideoOverlay.Name = 'Overlay';
hVideoOverlay.Position = [410 hVideoOrig.Position(2) WindowSize];
4-24
end
release(hVideoSrc);
4-25
System Objects
4-26
System Objects
Reconfiguring Objects
When Can You Change Component Properties?
When a System object has started processing data, it is locked to prevent changes that
would disrupt its processing. You can use isLocked on any System object to verify
whether it is locked or not. When processing is complete, you can use the release
method to unlock a System object.
Some object properties are tunable, which enables you to change them even if the object
is locked. Unless otherwise specified, System objects properties are nontunable. Refer
to the objects reference page to determine whether an individual property is tunable.
Typically, tunable properties are not critical to how the System object processes data.
Change Input Complexity or Dimensions
During simulation, some System objects do not allow complex data if the object was
initialized with real data. You cannot change any input complexity during code
generation.
You can change the value of a tunable property without a warning or error being
produced. For all other changes at run time, an error occurs.
4-28
hAB.Location(1) = hAB.Location(1)+1;
if (hAB.Location(1)==120)
hAB.Location = [1 1];
end
% Offset edges
step(hVideoOrig,frame);
% Display original
% wrap
step(hVideoEdges,edges);
step(hVideoOverlay,composite);
% Display edges
% Display edges overlaid
end
4-29
System Objects
4-30
System Objects
Add the appropriate basic System object methods to set up, reset, set the number of
inputs and outputs, and run your algorithm. See the reference pages for each method and
the full class definition file below for the implementation of each of these methods.
Use the setupImpl method to perform one-time calculations and initialize variables.
Use the stepImpl method to implement the blocks algorithm.
Use the resetImpl method to reset the state properties or DiscreteState
properties.
4-32
properties (DiscreteState)
X;
H;
end
methods (Access = protected)
function setupImpl(obj)
obj.X = zeros(obj.N,1);
obj.H = zeros(obj.N,1);
end
function [y, e_norm] = stepImpl(obj,d,u)
tmp = obj.X(1:obj.N-1);
obj.X(2:obj.N,1) = tmp;
obj.X(1,1) = u;
y = obj.X'*obj.H;
e = d-y;
obj.H = obj.H + obj.Mu*e*obj.X;
e_norm = norm(obj.Weights'-obj.H);
end
function resetImpl(obj)
obj.X = zeros(obj.N,1);
obj.H = zeros(obj.N,1);
end
end
% Block icon and dialog customizations
methods (Static, Access = protected)
function header = getHeaderImpl
header = matlab.system.display.Header(...
'lmsSysObj', ...
'Title', 'LMS Adaptive Filter');
end
function groups = getPropertyGroupsImpl
upperGroup = matlab.system.display.SectionGroup(...
'Title','General',...
'PropertyList',{'Mu'});
lowerGroup = matlab.system.display.SectionGroup(...
'Title','Coefficients', ...
'PropertyList',{'Weights','N'});
4-33
System Objects
groups = [upperGroup,lowerGroup];
end
end
methods (Access = protected)
function icon = getIconImpl(~)
icon = sprintf('LMS Adaptive\nFilter');
end
function [in1name, in2name] = getInputNamesImpl(~)
in1name = 'Desired';
in2name = 'Actual';
end
function [out1name, out2name] = getOutputNamesImpl(~)
out1name = 'Output';
out2name = 'EstError';
end
end
end
methods instead. See the reference pages for each method and the full class definition file
below for the implementation of each of these methods.
Use the setupImpl method to initialize some of the objects properties.
Use the resetImpl method to reset the property states.
Use the validatePropertiesImpl method to check that the property values are
valid.
Add the following Nondirect mixin class methods instead of the stepImpl method to
specify how the block updates its state and its output. See the reference pages and the
full class definition file below for the implementation of each of these methods.
Use the outputImpl method to implement code to calculate the block output.
Use the updateImpl method to implement code to update the blocks internal states.
Use the isInputDirectFeedthroughImpl method to specify that the block is not
direct feedthrough. Its inputs do not directly affect its outputs.
Add the getIconImpl method to define the block icon when it is used in Simulink via
the MATLAB System block. See the reference page and the full class definition file below
for the implementation of this method.
The full class definition file for the delay is:
classdef intDelaySysObj < matlab.System &...
matlab.system.mixin.Nondirect &...
matlab.system.mixin.CustomIcon
% intDelaySysObj Delay input by specified number of samples.
% #codegen
properties
% InitialOutput Initial output
InitialOutput = 0;
end
properties (Nontunable)
% NumDelays Number of delays
NumDelays = 1;
end
properties (DiscreteState)
PreviousInput;
end
4-35
System Objects
Create an instance of your new System object. For example, create an instance of the
lmsSysObj.
s = lmsSysObj;
4-36
Run the step method on the object multiple times with different inputs. This tests for
syntax errors and other possible issues before you add it to Simulink. For example,
desired = 0;
actual = 0.2;
step(s,desired,actual);
Add your System objects to your Simulink model by using the MATLAB System block
as described in Mapping System Objects to Block Dialog Box.
Add other Simulink blocks, connect them, and configure any needed parameters to
complete your model as described in the Simulink documentation. See the System
Identification for an FIR System Using MATLAB System Blocks Simulink example.
Run your model in the same way you run any Simulink model.
4-37
5
Strategies for Real-Time Video
Processing in Simulink
Optimizing Your Implementation on page 5-2
Developing Your Models on page 5-4
data types. This code affects simulation performance. After you run your model
in accelerator mode or generate code for your target using the Simulink Coder,
the fixed-point data types are specific to the choices you made for the fixed-point
parameters. Therefore, the fixed-point model and generated code run faster.
5-3
Create the initial model and optimize the implementation algorithm. Use floatingpoint data types so that the model runs faster in simulation mode. If you are working
with a floating-point processor, go to step 3.
If you are working with a fixed-point processor, gradually change the model data
types to fixed point, and run the model after every modification.
During this process, you can use data type conversion blocks to isolate the
floating point sections of the model from the fixed-point sections. You should see a
performance improvement if you run the model in accelerator mode.
5-4
Remove unnecessary sink blocks, including scopes, and blocks that log data to files.
6
Data Type Support
6-2
vision.Pyramid
vision.ShapeInserter
vision.Variance
6-4