National Instruments IMAQ Vision for Measurement Studio User Manual

IMAQ
IMAQ Vision for Measurement Studio User Manual
LabWindows/CVI
IMAQ Vision for LabWindows/CVI User Manual
Part Number 323022A-01

Support

Worldwide Technical Support and Product Information

ni.com

National Instruments Corporate Headquarters

11500 North Mopac Expressway Austin, Texas 78759-3504 USA Tel: 512 794 0100

Worldwide Offices

Australia 03 9879 5166, Austria 0662 45 79 90 0, Belgium 02 757 00 20, Brazil 011 284 5011, Canada (Calgary) 403 274 9391, Canada (Ontario) 905 785 0085, Canada (Québec) 514 694 8521, China 0755 3904939, Denmark 45 76 26 00, Finland 09 725 725 11, France 01 48 14 24 24, Germany 089 741 31 30, Greece 30 1 42 96 427, Hong Kong 2645 3186, India 91805275406, Israel 03 6120092, Italy 02 413091, Japan 03 5472 2970, Korea 02 596 7456, Mexico (D.F.) 5 280 7625, Mexico (Monterrey) 8 357 7695, Netherlands 0348 433466, New Zealand 09 914 0488, Norway 32 27 73 00, Poland 0 22 528 94 06, Portugal 351 1 726 9011, Singapore 2265886, Spain 91 640 0085, Sweden 08 587 895 00, Switzerland 056 200 51 51, Taiwan 02 2528 7227, United Kingdom 01635 523545
For further support information, see the Technical Support Resources appendix. To comment on the documentation, send e-mail to techpubs@ni.com
Copyright © 2001 National Instruments Corporation. All rights reserved.

Important Information

Warranty

The media on which you receive National Instruments software are warranted not to fail to execute programming instructions, due to defects in materials and workmanship, for a period of 90 days from date of shipment, as evidenced by receipts or other documentation. National Instruments will, at its option, repair or replace software media that do not execute programming instructions if National Instruments receives notice of such defects during the warranty period. National Instruments does not warrant that the operation of the software shall be uninterrupted or error free.
A Return Material Authorization (RMA) number must be obtained from the factory and clearly marked on the outside of the package before any equipment will be accepted for warranty work. National Instruments will pay the shipping costs of returning to the owner parts which are covered by warranty.
National Instruments believes that the information in this document is accurate. The document has been carefully reviewed for technical accuracy. In the event that technical or typographical errors exist, National Instruments reserves the right to make changes to subsequent editions of this document without prior notice to holders of this edition. The reader should consult National Instruments if errors are suspected. In no event shall National Instruments be liable for any damages arising out of or related to this document or the information contained in it.
E
XCEPT AS SPECIFIED HEREIN,NATIONAL INSTRUMENTS MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AND SPECIFICALLY DISCLAIMS ANY
WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE
NEGLIGENCE ON THE PART OF
INSTRUMENTS WILL NOT BE LIABLE FOR DAMAGES RESULTING FROM LOS S OF DATA, PROFI TS, USE OF PRO DUCTS, OR INCIDENTAL OR
CONSEQUENTIAL DAMAGES
apply regardless of the form of action, whether in contract or tort, including negligence. Any action against National Instruments must be brought within one year after the cause of action accrues. National Instruments shall not be liable for any delay in performance due to causes beyond its reasonable control. The warranty provided herein does not cover damages, defects, malfunctions, or service failures caused by owners failure to follow the National Instruments installation, operation, or maintenance instructions; owners modification of the product; owners abuse, misuse, or negligent acts; and power failure or surges, fire, flood, accident, actions of third parties, or other events outside reasonable control.
NATIONAL INSTRUMENTS SHALL BE LIMITED TO THE AMOUNT THERETOFORE PAID BY THE CUSTOMER.NATIONAL
, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. This limitation of the liability of National Instruments will
.CUSTOMERS RIGHT TO RECOVER DAMAGES CAUSED BY FAULT OR

Copyright

Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent of National Instruments Corporation.

Trademarks

CVI™,IMAQ™,LabVIEW™, Measurement Studio™, National Instruments™,ni.com™, and NI-IMAQ™are trademarks of National Instruments Corporation.
Product and company names mentioned herein are trademarks or trade names of their respective companies.

WARNING REGARDING USE OF NATIONAL INSTRUMENTS PRODUCTS

(1) NATIONAL INSTRUMENTS PRODUCTS ARE NOT DESIGNED WITH COMPONENTS AND TESTING FOR A LEVEL OF RELIABILITY SUITABLE FOR USE IN OR IN CONNECTION WITH SURGICAL IMPLANTS OR AS CRITICAL COMPONENTS IN ANY LIFE SUPPORT SYSTEMS WHOSE FAILURE TO PERFORM CAN REASONABLY BE EXPECTED TO CAUSE SIGNIFICANT INJURY TO A HUMAN.
(2) IN ANY APPLICATION, INCLUDING THE ABOVE, RELIABILITY OF OPERATION OF THE SOFTWARE PRODUCTS CAN BE IMPAIRED BY ADVERSE FACTORS, INCLUDING BUT NOT LIMITED TO FLUCTUATIONS IN ELECTRICAL POWER SUPPLY, COMPUTER HARDWARE MALFUNCTIONS, COMPUTER OPERATING SYSTEM SOFTWARE FITNESS, FITNESS OF COMPILERS AND DEVELOPMENT SOFTWARE USED TO DEVELOP AN APPLICATION, INSTALLATION ERRORS, SOFTWARE AND HARDWARE COMPATIBILITY PROBLEMS, MALFUNCTIONS OR FAILURES OF ELECTRONIC MONITORING OR CONTROL DEVICES, TRANSIENT FAILURES OF ELECTRONIC SYSTEMS (HARDWARE AND/OR SOFTWARE), UNANTICIPATED USES OR MISUSES, OR ERRORS ON THE PART OF THE USER OR APPLICATIONS DESIGNER (ADVERSE FACTORS SUCH AS THESE ARE HEREAFTER COLLECTIVELY TERMED SYSTEM FAILURES). ANY APPLICATION WHERE A SYSTEM FAILURE WOULD CREATE A RISK OF HARM TO PROPERTY OR PERSONS (INCLUDING THE RISK OF BODILY INJURY AND DEATH) SHOULD NOT BE RELIANT SOLELY UPON ONE FORM OF ELECTRONIC SYSTEM DUE TO THE RISK OF SYSTEM FAILURE. TO AVOID DAMAGE, INJURY, OR DEATH, THE USER OR APPLICATION DESIGNER MUST TAKE REASONABLY PRUDENT STEPS TO PROTECT AGAINST SYSTEM FAILURES, INCLUDING BUT NOT LIMITED TO BACK-UP OR SHUT DOWN MECHANISMS. BECAUSE EACH END-USER SYSTEM IS CUSTOMIZED AND DIFFERS FROM NATIONAL INSTRUMENTS' TESTING PLATFORMS AND BECAUSE A USER OR APPLICATION DESIGNER MAY USE NATIONAL INSTRUMENTS PRODUCTS IN COMBINATION WITH OTHER PRODUCTS IN A MANNER NOT EVALUATED OR CONTEMPLATED BY NATIONAL INSTRUMENTS, THE USER OR APPLICATION DESIGNER IS ULTIMATELY RESPONSIBLE FOR VERIFYING AND VALIDATING THE SUITABILITY OF NATIONAL INSTRUMENTS PRODUCTS WHENEVER NATIONAL INSTRUMENTS PRODUCTS ARE INCORPORATED IN A SYSTEM OR APPLICATION, INCLUDING, WITHOUT LIMITATION, THE APPROPRIATE DESIGN, PROCESS AND SAFETY LEVEL OF SUCH SYSTEM OR APPLICATION.

Conventions

The following conventions are used in this manual:
» The » symbol leads you through nested menu items and dialog box options
to a final action. The sequence File»Page Setup»Options directs you to pull down the File menu, select the Page Setup item, and select Options from the last dialog box.
This icon denotes a note, which alerts you to important information.
bold Bold text denotes items that you must select or click on in the software,
such as menu items and dialog box options. Bold text also denotes parameter names.
italic Italic text denotes variables, emphasis, a cross reference, or an introduction
to a key concept. This font also denotes text that is a placeholder for a word or value that you must supply.
monospace
Text in this font denotes text or characters that you should enter from the keyboard, sections of code, programming examples, and syntax examples. This font is also used for the proper names of disk drives, paths, directories, programs, subprograms, subroutines, device names, functions, operations, variables, filenames and extensions, and code excerpts.

Contents

Chapter 1 Introduction to IMAQ Vision
About IMAQ Vision ......................................................................................................1-1
Documentation and Examples .......................................................................................1-1
Application Development Environments.......................................................................1-2
IMAQ Vision Function Tree..........................................................................................1-2
IMAQ Machine Vision Function Tree...........................................................................1-4
Creating IMAQ Vision Applications.............................................................................1-5
Chapter 2 Getting Measurement-Ready Images
Set Up Your Imaging System ........................................................................................2-1
Calibrate Your Imaging System ....................................................................................2-2
Create an Image .............................................................................................................2-2
Source and Destination Images .......................................................................2-4
Acquire or Read an Image .............................................................................................2-5
Acquiring an Image .........................................................................................2-6
Reading a File..................................................................................................2-6
Converting an Array to an Image ....................................................................2-7
Display an Image ...........................................................................................................2-7
Attach Calibration Information......................................................................................2-8
Analyze an Image ..........................................................................................................2-8
Improve an Image ..........................................................................................................2-9
Lookup Tables .................................................................................................2-9
Filters...............................................................................................................2-10
Convolution Filter .............................................................................2-10
Nth Order Filter.................................................................................2-11
Grayscale Morphology ....................................................................................2-11
FFT ..................................................................................................................2-11
Complex Image Operations ..............................................................2-13
Chapter 3 Grayscale and Color Measurements
Define Regions of Interest .............................................................................................3-1
Interactively Defining Regions........................................................................3-1
Programmatically Defining Regions ...............................................................3-6
Defining Regions with Masks .........................................................................3-6
Measure Grayscale Statistics .........................................................................................3-7
© National Instruments Corporation v IMAQ Vision for LabWindows/CVI User Manual
Contents
Measure Color Statistics................................................................................................ 3-7
Chapter 4 Blob Analysis
Correct Image Distortion............................................................................................... 4-2
Create a Binary Image................................................................................................... 4-2
Improve the Binary Image............................................................................................. 4-3
Make Particle Measurements ........................................................................................ 4-4
Convert Pixel Coordinates to Real-World Coordinates ................................................ 4-7
Chapter 5
Comparing Colors ........................................................................................... 3-8
Learning Color Information ............................................................................ 3-9
Choosing the Right Color Information............................................. 3-9
Specifying the Color Information to Learn ...................................... 3-10
Choosing a Color Representation Sensitivity ................................... 3-12
Ignoring Learned Colors................................................................... 3-13
Removing Unwanted Blobs ............................................................................ 4-3
Separating Touching Blobs............................................................................. 4-4
Improving Blob Shapes................................................................................... 4-4
Machine Vision
Locate Objects to Inspect .............................................................................................. 5-2
Using Edge Detection to Build a Coordinate Transform................................ 5-3
Using Pattern Matching to Build a Coordinate Transform ............................. 5-5
Choosing a Method to Build the Coordinate Transform................................. 5-7
Set Search Areas............................................................................................................ 5-8
Interactively Defining Regions ....................................................................... 5-8
Programmatically Defining Regions............................................................... 5-9
Find Measurement Points ..............................................................................................5-9
Finding Features Using Edge Detection ......................................................... 5-9
Finding Points Using Pattern Matching.......................................................... 5-13
Finding Points Using Color Pattern Matching................................................ 5-18
Finding Lines or Circles ................................................................... 5-9
Finding Edge Points Along One Search Contour.............................5-11
Finding Edge Points Along Multiple Search Contours .................... 5-12
Defining and Create Good Template Images ................................... 5-13
Training the Pattern Matching Algorithm ........................................ 5-15
Defining a Search Area..................................................................... 5-15
Setting Matching Parameters and Tolerances................................... 5-16
Testing the Search Algorithm on Test Images ................................. 5-18
Using a Ranking Method to Verify Results...................................... 5-18
Defining and Creating Good Color Template Images......................5-19
IMAQ Vision for LabWindows/CVI User Manual vi ni.com
Convert Pixel Coordinates to Real-World Coordinates.................................................5-26
Make Measurements ......................................................................................................5-26
Display Results ..............................................................................................................5-28
Chapter 6 Calibration
Perspective and Nonlinear Distortion Calibration .........................................................6-1
Simple Calibration .........................................................................................................6-9
Save Calibration Information.........................................................................................6-10
Attach Calibration Information......................................................................................6-10
Contents
Training the Color Pattern Matching Algorithm...............................5-20
Defining a Search Area .....................................................................5-21
Setting Matching Parameters and Tolerances...................................5-22
Testing the Search Algorithm on Test Images..................................5-24
Finding Points Using Color Location.............................................................. 5-25
Distance Measurements...................................................................................5-26
Analytic Geometry Measurements..................................................................5-27
Instrument Reader Measurements ...................................................................5-27
Defining a Calibration Template.....................................................................6-2
Defining a Reference Coordinate System .......................................................6-2
Learning Calibration Information....................................................................6-5
Specifying Scaling Factors................................................................6-6
Choosing a Region of Interest...........................................................6-6
Choosing a Learning Algorithm .......................................................6-6
Using the Learning Score..................................................................6-7
Learning the Error Map.....................................................................6-8
Learning the Correction Table .......................................................... 6-8
Setting the Scaling Method ...............................................................6-8
Calibration Invalidation ....................................................................6-8
Appendix A Technical Support Resources
Glossary
Index
© National Instruments Corporation vii IMAQ Vision for LabWindows/CVI User Manual
Introduction to IMAQ Vision
This chapter describes the IMAQ Vision for LabWindows/CVI software
and associated software products, discusses the documentation and
examples available, outlines the IMAQ Vision function organization, and
lists the steps for making a machine vision application.
Note
For information about the system requirements and installation procedure for IMAQ Vision for LabWindows/CVI, see the IMAQ Vision for Measurement Studio Release Notes that came with your software.

About IMAQ Vision

IMAQ Vision for Measurement Studio is a National Instruments product comprised of IMAQ Vision for LabWindows/CVI and IMAQ Vision for Visual Basic. IMAQ Vision for LabWindows/CVI is a library of C functions that you can use to develop machine vision and scientific imaging applications. IMAQ Vision for Visual Basic is a collection of ActiveX controls that offer the same imaging functionality as IMAQ Vision for LabWindows/CVI. National Instruments also offers IMAQ Vision for LabVIEW, which is a library of LabVIEW VIs for developing machine vision and scientific imaging applications. IMAQ Vision Builder, another software product from National Instruments, allows you to prototype your application strategy quickly without having to do any programming.
1

Documentation and Examples

In addition to this manual, several documentation resources are available to help you create your vision application:
IMAQ Vision Concepts ManualIf you are new to machine vision and imaging, read this manual to understand the concepts behind IMAQ Vision.
IMAQ Vision for LabWindows/CVI function referenceIf you need information about IMAQ Vision functions while creating your application, refer to this help file. Access this file from the Start menu by selecting Programs»National Instruments»Vision»
© National Instruments Corporation 1-1 IMAQ Vision for LabWindows/CVI User Manual
Chapter 1 Introduction to IMAQ Vision
Documentation»IMAQ Vision for LabWindows/CVI Function Reference.
Example programsIf you want examples of how to create specific applications, go to
Application NotesIf you want to know more about advanced IMAQ Vision concepts and applications, refer to the Application Notes located on the National Instruments Web site at
ni.com/appnotes.nsf/
NI Developer Zone (NIDZ)If you want even more information about developing your vision application, visit the NI Developer Zone at
ni.com/zone.
tutorials, technical presentations, the Instrument Driver Network, a measurement glossary, an online magazine, a product advisor, and a community area where you can share ideas, questions, and source code with vision developers around the world.
cvi\samples\vision
The NI Developer Zone contains example programs,

Application Development Environments

This release of IMAQ Vision for LabWindows/CVI supports the following Application Development Environments (ADEs) for Windows 2000/NT/Me/9x.
LabWindows/CVI version 5.0.1 and higher
Borland C++ Builder 3.0 and higher
Microsoft Visual C/C++ version 6.0 and higher
.
Note
Although IMAQ Vision has been tested and found to work with these ADEs, other
ADEs may also work.

IMAQ Vision Function Tree

The IMAQ Vision function tree ( classes corresponding to groups or types of functions. Table 1-1 lists the IMAQ Vision function types and gives a description of each type.
IMAQ Vision for LabWindows/CVI User Manual 1-2 ni.com
NIVision.lfp
) contains separate
Chapter 1 Introduction to IMAQ Vision
Table 1-1.
IMAQ Vision Function Types
Function Type Description
Image Management
Memory
Functions that create space in memory for images and perform basic image manipulation.
A function that returns memory you no longer need to the operating system.
Management
Error Management
Functions that set the current error, return the name of the function in which the last error occurred, return the error code of the last error, and clear any pending errors.
Acquisition Functions that acquire images through an IMAQ hardware device.
Display Functions that cover all aspects of image visualization and image window
management.
Overlay Functions that create and manipulate overlays.
Regions of
Functions that create and manipulate regions of interest.
Interest
File I/O Functions that read and write images to and from files.
Calibration Functions that learn calibration information and correct distorted images.
Image Analysis
Functions that compute the centroid of an image, profile of a line of pixels, and the mean line profile. This type also includes functions that calculate the pixel distribution and statistical parameters of an image.
Grayscale
Functions for grayscale image processing and analysis.
Processing
Binary
Functions for binary image processing and analysis.
Processing
Color
Functions for color image processing and analysis.
Processing
Pattern
Functions that learn patterns and search for patterns in images.
Matching
Caliper Functions designed for gauging, measurement, and inspection applications.
Operators Functions that perform arithmetic, logic, and comparison operations with
two images or with an image and a constant value.
Analytic
Functions that perform basic geometric calculations on an image.
Geometry
© National Instruments Corporation 1-3 IMAQ Vision for LabWindows/CVI User Manual
Chapter 1 Introduction to IMAQ Vision
Table 1-1. IMAQ Vision Function Types (Continued)
Function Type Description
Frequency Domain Analysis
Barcode A function that reads a barcode.
LCD Functions that find and read seven-segment LCD characters.
Meter Functions that return the arc information of a meter and read the meter.
Utilities Functions that return structures, and a function that returns a pointer to
Obsolete Functions that are no longer necessary but may exist in older applications.
Functions for the extraction and manipulation of complex planes. Functions of this type perform FFTs, inverse FFTs, truncation, attenuation, addition, subtraction, multiplication, and division of complex images.
predefined convolution matrices.

IMAQ Machine Vision Function Tree

The IMAQ Machine Vision function tree ( contains separate classes corresponding to groups or types of functions. Table 1-2 lists the IMAQ Machine Vision function types and gives a description of each type.

Table 1-2. IMAQ Machine Vision Function Types

Function Type Description
Coordinate Transform Functions that find coordinate transforms based on image contents.
NIMachineVision.fp
)
Count and Measure Objects A function that counts and measures objects in an image.
Find Patterns A function that finds patterns in an image.
Locate Edges Functions that locate different types of edges in an image.
Measure Distances Functions that measure distances between objects in an image.
Measure Intensities Functions that measure light intensities in various shaped regions
within an image.
Select Region of Interest Functions that allow a user to select a specific region of interest in
an image.
IMAQ Vision for LabWindows/CVI User Manual 1-4 ni.com

Creating IMAQ Vision Applications

Figures 1-1 and 1-2 illustrate the steps for creating an application with IMAQ Vision. Figure 1-1 describes the general steps to designing a Vision application. The last step in Figure 1-1 is expanded upon in Figure 1-2. You can use a combination of the items in the last step to create your IMAQ Vision application. For more information about items in either diagram, see the corresponding chapter listed to the right of the item.
Note
Diagram items enclosed with dashed lines are optional steps.
Set Up Your Imaging System
Chapter 1 Introduction to IMAQ Vision
Chapter 2:
Measurement-Ready
Getting
Images
Calibrate Your Imaging System
Create an Image
Acquire or Read an Image
Display an Image
Attach Calibration Information
Analyze an Image
Improve an Image
Improve an Image
Make Measurements in an Image Using
1
Grayscale or Color Measurements, and/or
2
Blob Analysis, and/or
3
Machine Vision
Chapter 6: Calibration

Figure 1-1. General Steps to Designing a Vision Application

© National Instruments Corporation 1-5 IMAQ Vision for LabWindows/CVI User Manual
Chapter 1 Introduction to IMAQ Vision
1
Chapter 4:
Blob Analysis
Chapter 3:
Grayscale and Color
Measurements
Make Particle Measurements
Convert Pixel Coordinates to
Measure
Grayscale Statistics
2
Correct Image Distortion
Create a Binary Image
Improve a Binary Image
Real-World Coordinates
Define Regions of Interest
Measure
Color Statistics
Locate Objects to Inspect
Find Measurement Points
Convert Pixel Coordinates to
Real-World Coordinates
3
Set Search Areas
Make Measurements
Display Results
Chapter 5: Machine Vision

Figure 1-2. Inspection Steps for Building a Vision Application

IMAQ Vision for LabWindows/CVI User Manual 1-6 ni.com
Getting Measurement-Ready Images
This chapter describes how to set up your imaging system, acquire and display an image, analyze the image, and prepare the image for additional processing.

Set Up Your Imaging System

Before you acquire, analyze, and process images, you must set up your imaging system. The manner in which you set up your system depends on your imaging environment and the type of analysis and processing you need to do. Your imaging system should produce images with high enough quality so that you can extract the information you need from the images.
Follow the guidelines below to setup your imaging system.
1. Determine the type of equipment you need given your space constraints and the size of the object you need to inspect. For more information, see Chapter 3, System Setup and Calibration,ofthe IMAQ Vision Concepts Manual.
a. Make sure your camera sensor is large enough to satisfy your
minimum resolution requirement.
b. Make sure your lens has a depth of field high enough to keep all
of your objects in focus regardless of their distance from the lens. Also, make sure your lens has a focal length that meets your needs.
c. Make sure your lighting provides enough contrast between the
object under inspection and the background for you to extract the information you need from the image.
2. Position your camera so that it is parallel to the object under inspection. If your camera acquires images of the object from an angle, perspective errors occur. You can compensate for these errors with software, but using a parallel inspection angle obtains the fastest and most accurate results.
2
© National Instruments Corporation 2-1 IMAQ Vision for LabWindows/CVI User Manual
Chapter 2 Getting Measurement-Ready Images
3. Select an image acquisition device that meets your needs. National Instruments offers several image acquisition (IMAQ) devices, such as analog color and monochrome IMAQ devices as well as digital devices. Visit devices.
4. Configure the driver software for your image acquisition device. If you have a National Instruments image acquisition device, configure your NI-IMAQ driver software through Measurement & Automation Explorer (MAX). Open MAX by double-clicking the Measurement & Automation Explorer icon on your desktop. For more information, see the NI-IMAQ User Manual and the MAX online help.
ni.com/imaq

Calibrate Your Imaging System

After you set up your imaging system, you may want to calibrate your system. Calibrate your imaging system to assign real-world coordinates to pixel coordinates and compensate for perspective and nonlinear errors inherent in your imaging system.
Perspective errors occur when your camera axis is not perpendicular to the object under inspection. Nonlinear distortion may occur from aberrations in the camera lens. Perspective errors and lens aberrations cause images to appear distorted. This distortion misplaces information in an image, but it does not necessarily destroy the information in the image.
for more information about IMAQ
Use simple calibration if you only want to assign real-world coordinates to pixel coordinates. Use perspective and nonlinear distortion calibration if you need to compensate for perspective errors and nonlinear lens distortion. For detailed information about calibration, see Chapter 6, Calibration.

Create an Image

To create an image in IMAQ Vision for LabWindows/CVI, call
imaqCreateImage()
use when calling other IMAQ Vision functions. The only limitation to the size and number of images you can acquire and process is the amount of memory on your computer. When you create an image, specify the type of the image. Table 2-1 lists the valid image types.
IMAQ Vision for LabWindows/CVI User Manual 2-2 ni.com
. This function returns an image reference you can
Chapter 2 Getting Measurement-Ready Images
Va lu e Description
IMAQ_IMAGE_U8
IMAQ_IMAGE_I16
IMAQ_IMAGE_SGL
IMAQ_IMAGE_COMPLEX
IMAQ_IMAGE_RGB
IMAQ_IMAGE_HSL
Table 2-1.
IMAQ Vision for LabWindows/CVI Image Types
8 bits per pixelunsigned, standard monochrome
16 bits per pixelsigned, monochrome
32 bits per pixelfloating point, monochrome
2 × 32 bits per pixelfloating point, native format after a Fast Fourier Transform (FFT)
32 bits per pixelstandard color
32 bits per pixelcolor
If you plan to use filtering or blob analysis functions on the image, set the appropriate border size for the image. The default border size is 3.
When you create an image, IMAQ Vision creates an internal image structure to hold properties of the image, such as its name and border size. However, no memory is allocated to store the image pixels at this time. IMAQ Vision functions automatically allocate the appropriate amount of memory when the image size is modified. For example, functions that acquire or resample an image alter the image size, so they allocate the appropriate memory space for the image pixels. The return value of
imaqCreateImage()
is a pointer to the image structure. Supply this
pointer as an input to all subsequent IMAQ Vision functions.
Most functions belonging to the IMAQ Vision library require one or more image pointers. The number of image pointers a function takes depends on the image processing function and the type of image you want to use. Some IMAQ Vision functions act directly on the image and require only one image pointer. Other functions that process the contents of images require pointers to the source image(s) and to a destination image.
You can create multiple images by executing
imaqCreateImage()
as many times as you want. Determine the number of required images through an analysis of your intended application. The decision is based on different processing phases and your need to keep the original image (after each processing step).
At the end of your application, dispose of each image that you created using
imaqDispose()
© National Instruments Corporation 2-3 IMAQ Vision for LabWindows/CVI User Manual
.
Chapter 2 Getting Measurement-Ready Images

Source and Destination Images

Some IMAQ Vision functions that modify the contents of an image have source image and destination image input parameters. The source image receives the image to process. The destination image receives the processing results. The destination image can receive either another image or the original, depending on your goals. If you do not want the contents of the original image to change, use separate source and destination images. If you want to replace the original image with the processed image, pass the same image as both the source and destination.
Depending on the function, the image type of the destination image can be the same or different than the image type of the source image. The function descriptions in the IMAQ Vision for LabWindows/CVI function reference help include the type of images you can use as image inputs and outputs. IMAQ Vision resizes the destination image to hold the result if the destination is not the appropriate size.
The following examples illustrate source and destination images with
imaqTranspose()
imaqTranspose(myImage, myImage);
This function creates a transposed image using the same image for the source and destination. The contents of
imaqTranspose(myTransposedImage, myImage);
This function creates a transposed image and stores it in a destination different from the source. The and
myTransposedImage
:
change.
myImage
myImage
image remains unchanged,
contains the result.
Functions that perform arithmetic or logical operations between two images have two source images and a destination image. You can perform an operation between two images and then either store the result in a separate destination image or in one of the two source images. In the latter case, make sure you no longer need the original data in the source image before storing the result over the data.
The following examples show the possible combinations using
imaqAdd()
imaqAdd(myResultImage, myImageA, myImageB);
This function adds two source images ( stores the result in a third image (
:
myImageA
myResultImage
and
myImageB
). Both source
)and
images remain intact after processing.
IMAQ Vision for LabWindows/CVI User Manual 2-4 ni.com
Chapter 2 Getting Measurement-Ready Images
imaqAdd(myImageA, myImageA, myImageB);
This function adds two source images and stores the result in the first source image.
imaqAdd(myImageB, myImageA, myImageB);
This function adds two source images and stores the result in the second source image.
Most operations between two images require that the images have the same type and size. However, some arithmetic operations can work between two different types of images (for example, 8-bit and 16-bit).
Some functions perform operations that populate an image. Examples of this type of operation include reading a file, acquiring an image from an IMAQ device, or transforming a 2D array into an image. This type of function can modify the size of an image.
Some functions take an additional mask parameter. The presence of a mask parameter indicates that the processing or analysis is dependent on the contents of another image (the image mask). The only pixels in the source image that are processed are those whose corresponding pixels in the image mask are non-zero. If an image mask pixel is 0, the corresponding source image pixel is not processed or analyzed. The image mask must be an 8-bit image.
If you want to apply a processing or analysis function to the entire image, pass NULL for the image mask. Passing the same image to both the source image and image mask also gives the same effect as passing NULL for the image mask, except in this case the source image must be an 8-bit image.

AcquireorReadanImage

After you create an image reference, you can acquire an image into your imaging system in three ways. You can acquire an image with a camera through your image acquisition device, load an image from a file stored on your computer, or convert the data stored in a 2D array to an image. Functions that acquire images, load images from file, or convert data from a 2D array automatically allocate the memory space required to accommodate the image data.
© National Instruments Corporation 2-5 IMAQ Vision for LabWindows/CVI User Manual
Chapter 2 Getting Measurement-Ready Images

Acquiring an Image

Use one of the following methods to acquire images with a National Instruments image acquisition (IMAQ) device:
Acquire a single image using this function, it initializes the IMAQ device and acquires the next incoming video frame. Use this function for low-speed single capture applications where ease of programming is essential.
Acquire a single image using function, it acquires the next incoming video frame on an IMAQ device you have already initialized using i
mgSessionOpen()
applications.
Acquire images continually through a grab acquisition. Grab functions perform high-speed acquisitions that loop continually on one buffer. Use
imaqSetupGrab()
return a copy of the current image. Use stop the acquisition.
Acquire a fixed number of images using a sequence acquisition. Set up the acquisition using
imaqStartAcquisition()
requested during setup. If you want to acquire only certain images, supply frames to skip after each acquired frame.
Acquire images continually through a ringed buffer acquisition. Set up the acquisition using
imaqStartAcquisition()
acquired ring buffer. To get an image from the ring, call
imaqExtractFromRing()orimaqCopyRing() imaqStopAcquisition()
imaqEasyAcquire()
imaqSnap()
. Use this function for high-speed single capture
to start the acquisition. Use
imaqSetupSequence()
to acquire the number of images you
imaqSetupSequence()
imaqSetupRing()
to start acquiring images into the
to stop the acquisition.
. When you call
. When you call this
imgInterfaceOpen()
imaqGrab()
imaqStopAcquisition()
and
to to
.Use
with a table describing the number of
.Use
.Use
Note
You must use the
imgClose()
to release resources associated with the image
acquisition device.

Reading a File

Use
imaqReadFile()
computer into the image reference. You can read from image files stored in severalstandardformats:BMP,TIFF,JPEG,PNG,andAIPD.The software automatically converts the pixels it reads into the type of image you pass in.
IMAQ Vision for LabWindows/CVI User Manual 2-6 ni.com
to open and read data from a file stored on your
Chapter 2 Getting Measurement-Ready Images
Use
imaqReadVisionFile()
information, such as calibration information, template information for pattern matching, or overlay information. For more information about pattern matching templates and overlays, see Chapter 5, Machine Vision.
You can also use propertiesimage size, recommended image type, and calibration unitswithout actually reading all the image data.

Converting an Array to an Image

Use
imaqArrayToImage()
also use
imaqImageToArray()

Display an Image

Display an image in an external window using You can display images in 16 different external windows. Use the other display functions to configure the appearance of each external window. Properties you can set include whether the window has scroll bars, is resizable, or has a title bar. You can also use position the external image window at a particular location on you monitor. See the IMAQ Vision for LabWindows/CVI function reference for a complete list of display functions.
to open an image file containing additional
imaqGetFileInfo()
to convert a 2D array to an image. You can
to convert an image to a 2D array.
to retrieve image
imaqDisplayImage()
imaqMoveWindow()
.
to
Note
Image windows are not LabWindows/CVI panels. They are managed directly by
IM AQ Vis ion.
You can use a color palette to display grayscale images by applying a color palette to the window. Use
imaqSetWindowPalette()
to set predefined color palettes. For example, if you need to display a binary imagean image containing particle regions with pixel values of 1 and a background region with pixel values of 0apply the predefined binary palette. For more information about color palettes, see the Chapter 2, Display,ofthe IMAQ Vision Concepts Manual.
Note
At the end of your application, you should close all open external windows using
imaqCloseWindow()
© National Instruments Corporation 2-7 IMAQ Vision for LabWindows/CVI User Manual
.
Chapter 2 Getting Measurement-Ready Images

Attach Calibration Information

If you want to attach the calibration information of the current setup to each image you acquire, use function takes in a source image containing the calibration information and a destination image that you want to calibrate. The output image is your inspection image with the calibration information attached to it. For detailed information about calibration, see Chapter 6, Calibration.
Note
Because calibration information is part of the image, it is propagated throughout the processing and analysis of the image. Functions that modify the image size (such as geometrical transforms) void the calibration information. Use to save the image and all of the attached calibration information to a file.

Analyze an Image

Once you acquire and display an image, you may want to analyze the contents of the image for the following reasons:
To determine whether the image quality is high enough for your inspection task.
To obtain the values of parameters that you want to use in processing functions during the inspection process.
imaqCopyCalibrationInfo()
imaqWriteVisionFile()
.This
The histogram and line profile tools can help you analyze the quality of your images.
Use
imaqHistogram()
image. Use the histogram of the image to analyze two important criteria that define the quality of an imagesaturation and contrast. If your image is underexposed (does not have enough light) the majority of your pixels will have low intensity values, which appear as a concentration of peaks on the left side of your histogram. If your image is overexposed (has too much light) the majority of your pixels will have a high intensity values, which appear as a concentration of peaks on the right side of your histogram. If your image has an appropriate amount of contrast, your histogram will have distinct regions of pixel concentrations. Use the histogram information to decide if the image quality is high enough to separate objects of interest from the background.
If the image quality meets your needs, use the histogram to determine the range of pixel values that correspond to objects in the image. You can use
IMAQ Vision for LabWindows/CVI User Manual 2-8 ni.com
to analyze the overall grayscale distribution in the
Chapter 2 Getting Measurement-Ready Images
this range in processing functions, such as determining a threshold range during blob analysis.
If the image quality does not meet your needs, try to improve the imaging conditions to get the desired image quality. You may need to re-evaluate and modify each component of your imaging setup: lighting equipment and setup, lens tuning, camera operation mode, and acquisition board parameters. If you reach the best possible conditions with your setup but the image quality still does not meet your needs, try to improve the image quality using the image processing techniques described in the Improve an
Image section.
Use image, or use one-dimensional path in the image. By looking at the pixel distribution, you can determine if the image quality is high enough to provide you with sharp edges at object boundaries. Also, you can determine if the image is noisy, and identify the characteristics of the noise.
If the image quality meets your needs, use the pixel distribution information to determine some parameters of the inspection functions you want to use. For example, use the information from the line profile to determine the strength of the edge at the boundary of an object. You can input this information into line.

Improve an Image

Using the information you gathered from analyzing your image, you may want to improve the quality of your image for inspection. You can improve your image with lookup tables, filters, grayscale morphology, and Fast Fourier transforms.

Lookup Tables

Apply lookup table (LUT) transformations to highlight image details in areas containing significant information at the expense of other areas. A LUT transformation converts input grayscale values in the source image into other grayscale values in the transformed image. IMAQ Vision provides four functions that directly or indirectly apply lookup tables to images:
imaqLineProfile()
imaqROIProfile()
imaqEdgeTool()
imaqMathTransform()
replacing them with values from a predefined lookup table. IMAQ Vision has seven predefined lookup tables based on mathematical
to get the pixel distribution along a line in the
to get the pixel distribution along a
to find the edges of objects along the
Converts the pixel values of an image by
© National Instruments Corporation 2-9 IMAQ Vision for LabWindows/CVI User Manual
Chapter 2 Getting Measurement-Ready Images
transformations. For more information about these lookup tables, see Chapter 5, Image Processing,intheIMAQ Vision Concepts Manual.
imaqLookup()
them with values from a user-defined lookup table.
imaqEqualize()
given grayscale range. Use IMAQ Equalize to increase the contrast in images containing few grayscale values.
imaqInverse()
compute the negative of the image. For example, use before applying an automatic threshold to your image if the background pixels are brighter than the object pixels.

Filters

Filter your image when you need to improve the sharpness of transitions in the image or increase the overall signal-to-noise ratio of the image. You can choose either a lowpass or highpass filter depending on your needs.
Lowpass filters remove insignificant details by smoothing the image, removing sharp details, and smoothing the edges between the objects and the background. You can use lowpass filter with
Converts the pixel values of an image by replacing
Distributes the grayscale values evenly within a
Inverts the pixel intensities of an image to
imaqInverse()
imaqLowpass()
imaqConvolve()orimaqNthOrderFilter()
or define your own
.
Highpass filters emphasize details, such as edges, object boundaries, or cracks. These details represent sharp transitions in intensity value. You can define your own highpass filter with
imaqNthOrderFilter() imaqEdgeFilter()orimaqCannyEdgeFilter() imaqEdgeFilter()
, or you can use a predefined highpass filter with
function allows you to find edges in an image using
imaqConvolve()
or
.The
predefined edge detection kernels, such as the Sobel, Prewitt, and Roberts kernels.
Convolution Filter
The
imaqConvolve()
lowpass and highpass filters. Each filter is defined by a kernel of coefficients. Use predefined kernels do not meet your needs, define your own custom filter using a 2D array of floating point numbers.
IMAQ Vision for LabWindows/CVI User Manual 2-10 ni.com
function allows you to use a predefined set of
imaqGetKernel()
to retrieve predefined kernels. If the
Nth Order Filter
The highpass filter depending on the value of N that you choose. One specific Nth order filter, the median filter, removes speckle noise, which appears as small black and white dots. Use filter. For more information about Nth order filters, see Chapter 5, Image Processing,oftheIMAQ Vision Concepts Manual.

Grayscale Morphology

Perform grayscale morphology when you want to filter grayscale features of an image. Grayscale morphology helps you remove or enhance isolated features, such as bright pixels on a dark background. Use these transformations on a grayscale image to enhance non-distinct features before thresholding the image in preparation for blob analysis.
imaqNthOrderFilter()
Chapter 2 Getting Measurement-Ready Images
function allows you to define a lowpass or
imaqMedianFilter()
to apply a median
FFT
Use
imaqGrayMorphology()
transformations:
ErosionReduces the brightness of pixels that are surrounded by neighbors with a lower intensity.
DilationIncreases the brightness of pixels surrounded by neighbors with a higher intensity. A dilation has the opposite effect as an erosion.
OpeningRemoves bright pixels isolated in dark regions and smooths boundaries.
ClosingRemoves dark pixels isolated in bright regions and smooths boundaries.
Proper-openingRemoves bright pixels isolated in dark regions and smooths the inner contours of particles.
Proper-closingRemoves dark pixels isolated in bright regions and smooths the inner contours of particles.
Auto-medianGenerates simpler particles that have fewer details.
For more information about grayscale morphology transformations, see Chapter 5, Image Processing,oftheIMAQ Vision Concepts Manual.
Use the Fast Fourier Transform (FFT) to convert an image into its frequency domain. In an image, details and sharp edges are associated with mid to high spatial frequencies because they introduce significant gray-level variations over short distances. Gradually varying patterns are associated with low spatial frequencies.
to perform one of the following seven
© National Instruments Corporation 2-11 IMAQ Vision for LabWindows/CVI User Manual
Chapter 2 Getting Measurement-Ready Images
An image can have extraneous noise, such as periodic stripes, introduced during the digitization process. In the frequency domain, the periodic pattern is reduced to a limited set of high spatial frequencies. Also, the imaging setup may produce non-uniform lighting of the field of view, which produces an image with a light drift superimposed on the information you want to analyze. In the frequency domain, the light drift appears as a limited set of low frequencies around the average intensity of the image (DC component).
Youcanusealgorithmsworkinginthefrequencydomaintoisolateand remove these unwanted frequencies from your image. Follow these steps to obtain an image in which the unwanted pattern has disappeared but the overall features remain:
1. Use
imaqFFT()
frequency domain. This function computes the Fast Fourier Transform (FFT) of the image and results in a complex image representing the frequency information of your image.
2. Improve your image in the frequency domain with a lowpass or highpass frequency filter. Specify which type of filter to use with
imaqAttenuate()orimaqTruncate()
noise, details, textures, and sharp edges in an image. Highpass filters emphasize details, textures, and sharp edges in images, but they also emphasize noise.
Lowpass attenuationThe amount of attenuation is directly
proportional to the frequency information. At low frequencies, there is little attenuation. As the frequencies increase, the attenuation increases. This operation preserves all of the zero frequency information. Zero frequency information corresponds to the DC component of the image or the average intensity of the image in the spatial domain.
Highpass attenuationThe amount of attenuation is inversely
proportional to the frequency information. At high frequencies, there is little attenuation. As the frequencies decrease, the attenuation increases. The zero frequency component is removed entirely.
Lowpass truncationSpecify a frequency. The frequency
components above the ideal cutoff frequency are removed, and the frequencies below it remain unaltered.
Highpass truncationSpecify a frequency. The frequency
components above the ideal cutoff frequency remain unaltered, and the frequencies below it are removed.
to convert an image from the spatial domain to the
. Lowpass filters smooth
IMAQ Vision for LabWindows/CVI User Manual 2-12 ni.com
Chapter 2 Getting Measurement-Ready Images
3. To transform your image back to the spatial domain, use
imaqInverseFFT()
.
Complex Image Operations
The
imaqExtractComplexPlane()
imaqReplaceComplexPlane()
and update independently the real and imaginary planes of a complex image. You can also convert planes of a complex image to an array and back with
imaqArrayToComplexPlane()
imaqComplexPlaneToArray()
and
functions allow you to access, process,
and
.
© National Instruments Corporation 2-13 IMAQ Vision for LabWindows/CVI User Manual
Grayscale and Color Measurements
This chapter describes how to take measurements from grayscale and color images. You can make inspection decisions based on image statistics, such as the mean intensity level in a region. Based on the image statistics, you can perform many machine vision inspection tasks on grayscale or color images, such as detecting the presence or absence of components, detecting flaws in parts, and comparing a color component with a reference. Figure 3-1 illustrates the basic steps involved in making grayscale and color measurements.
3

Define Regions of Interest

Figure 3-1. Steps to Taking Grayscale and Color Measurements

Define Regions of Interest
A region of interest (ROI) is an area of an image in which you want to focus your image analysis. You can define an ROI interactively, programmatically, or with an image mask.

Interactively Defining Regions

You can interactively define an ROI in a window that displays an image. Use the tools from the IMAQ Vision tools palette to interactively define and manipulate an ROI. Table 3-1 describes each of the tools and the manner in which you use them.
Measure
Grayscale Statistics
Measure
Color Statistics
© National Instruments Corporation 3-1 IMAQ Vision for LabWindows/CVI User Manual
Chapter 3 Grayscale and Color Measurements
Table 3-1. Tools Palette Functions
Icon Too l N a me Function
Selection Tool Select an ROI in the image and adjust the position of its control
points and contours.
Action: Click on the desired ROI or control points.
Point Select a pixel in the image.
Action: Click on the desired position.
Line Drawalineintheimage.
Action: Click on the initial position and click again on the final position.
Rectangle Draw a rectangle or square in the image.
Action: Click on one corner and drag to the opposite corner.
Rotated Rectangle Draw a rotated rectangle in the image.
Action: Click on one corner and drag to the opposite corner to create the rectangle. Then, click on the lines inside the rectangle anddragtoadjusttherotationangle.
Oval Draw an oval or circle in the image.
Action: Click on the center position and drag to the desired size.
Annulus Draw an annulus in the image.
Action: Click on the center position and drag to the desired size. Adjust the inner and outer radii, and adjust the start and end angle.
Broken Line Drawabrokenlineintheimage.
Action: Click to place a new vertex and double-click to complete the ROI element.
Polygon Drawapolygonintheimage.
Action: Click to place a new vertex and double-click to complete the ROI element.
Freehand Line Draw a freehand line in the image.
Action: Click on the initial position, drag to the desired shape and release the mouse button to complete the shape.
IMAQ Vision for LabWindows/CVI User Manual 3-2 ni.com
Chapter 3 Grayscale and Color Measurements
Table 3-1. Tools Palette Functions (Continued)
Icon Too l N a me Function
Freehand Draw a freehand region in the image.
Action: Click on the initial position, drag to the desired shape and release the mouse button to complete the shape.
Zoom Zoom-in or zoom-out in an image.
Action: Click on the image to zoom in. Hold down <Shift> and clicktozoomout.
Pan Panaroundanimage.
Action: Click on an initial position, drag to the desired position and release the mouse button to complete the pan.
Hold down <Shift> while drawing an ROI if you want to constrain the ROI to the horizontal, vertical, or diagonalaxes when possible. Use the selection tool to position an ROI by its control points or vertices. ROIs are context sensitive, meaning that the cursor actions differ depending on the ROI with which you interact. For example, if you move your cursor over the side of a rectangle, the cursor changes to indicate that you can click and drag the side to resize the rectangle. If you want to draw more than one ROI in a window, hold down <Ctrl> while drawing additional ROIs.
You can display the IMAQ Vision tools palette as part of an ROI constructor window or in a separate, floating window. Follow these steps to invoke an ROI constructor and define an ROI from within the ROI constructor window:
1. Use
imaqConstructROI()
todisplayanimageandthetoolspalette
in an ROI constructor window, as shown in Figure 3-2.
© National Instruments Corporation 3-3 IMAQ Vision for LabWindows/CVI User Manual
Chapter 3 Grayscale and Color Measurements
2. Select an ROI tool from the tools palette.
3. Draw an ROI on your image. Resize and reposition the ROI until it designates the area you want to inspect.
4. Click the OK button to output a descriptor of the region you selected. You can input the ROI descriptor into many analysis and processing functions. You can also convert the ROI descriptor into an image mask, which you can use to process selected regions in the image. Use
imaqROIToMask()
Figure 3-2. ROI Constructor
to convert the ROI descriptor into an image mask.
The tools palette, shown in Figure 3-3, automatically transforms from the palette on the left to the palette on the right when you manipulate an ROI tool in an image window. The palette on the right displays the characteristics of the ROI you are drawing.
IMAQ Vision for LabWindows/CVI User Manual 3-4 ni.com
Loading...
+ 84 hidden pages