programmers_guide
programmers_guide
Programmer’s Guide
This manual describes the programming language interfaces of HALCON and shows how to use HALCON in
programming languages like C++, C#, C, or Visual Basic. It contains the necessary information to understand and
use the provided data structures and classes in your own programs.
We expect the reader of this manual to be familiar with the programming languages themselves and with the
corresponding development tools.
The manual is divided into the following parts:
• General Issues
This part contains information that is relevant for all programming interfaces, e.g., which interface to use for
which programming language or how to use HALCON with parallel programming.
• Programming With HALCON/C++
This part describes the HALCON’s language interface to C++.
• Programming With HALCON/.NET
This part describes HALCON’s language interface to .NET programming languages (C#, Visual Basic.NET,
etc.).
• Programming With HALCON/C
This part describes HALCON’s language interface to C.
• Using HDevEngine
This part describes how to use HDevEngine to execute HDevelop programs and procedures from a program-
ming language.
Symbols
I General Issues 11
1 Which HALCON Interface to Use 13
11 HALCON/.NET Interface 69
11.0.1 Specifying the Namespace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
11.1 Using HALCON/.NET Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
11.1.1 Online Help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
11.1.2 Calling HALCON Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
11.1.3 From Declaration to Finalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
11.1.4 Operator Overloads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
11.2 Working With Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
11.2.1 Calling HALCON Operators with Single or Multiple Values . . . . . . . . . . . . . . . . 74
11.2.2 Iconic Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
11.2.3 Control Tuples and the Class HTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
11.3 Working With Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
11.4 Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
11.5 Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
11.6 Window Controls for Visualization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
11.7 Customizing HSmartWindowControl for the Visualization . . . . . . . . . . . . . . . . . . . . . 82
12 Additional Information 85
12.1 Provided Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
12.1.1 C# . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
12.1.2 Visual Basic.NET . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
12.1.3 C++ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
12.2 HALCON/.NET Applications under Linux Using Mono . . . . . . . . . . . . . . . . . . . . . . . 87
12.2.1 Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
12.2.2 Deploying HALCON/.NET Applications Created under Windows . . . . . . . . . . . . . 87
12.2.3 Compiling HALCON/.NET Applications with Mono . . . . . . . . . . . . . . . . . . . . 87
12.2.4 Using Other GUI Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
12.3 Using HDevelop Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
12.3.1 Using the Template Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
12.3.2 Combining the Exported Code with the HALCON/.NET Classes . . . . . . . . . . . . . . 89
12.4 HALCON/.NET and Remote Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
15 HALCON/Python Interface 97
15.1 Module Import . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
15.2 Using HALCON Operators From HALCON/Python . . . . . . . . . . . . . . . . . . . . . . . . . 97
15.3 Operators Are Standalone Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
15.4 Inputs Are Parameters, Outputs Are Return Values . . . . . . . . . . . . . . . . . . . . . . . . . 98
15.5 HALCON Tuples Are Represented With Native Python Types . . . . . . . . . . . . . . . . . . . 99
15.6 HHandle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
15.7 HObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
15.8 HDict . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
15.9 HALCON/Python with NumPy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
15.10Output Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
15.11Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
15.12Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
15.13Named Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
15.14Operator and Parameter Capitalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
15.15UTF-8 in HALCON/Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
15.16HALCON/Python With HALCON XL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
15.17Global HALCON Functions in HALCON/Python . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Index 207
Part I
General Issues
Which HALCON Interface to Use 13
General Issues
Chapter 1
Since the introduction of HALCON/.NET, for many programming languages you can now use more than one
interface. Table 1.1 on page 13 guides you through these possibilities.
recommendation alternative(s)
C → HALCON/C
C++ (unmanaged) → HALCON/C++
C++ (managed) → HALCON/.NET HALCON/C++
C# → HALCON/.NET
Visual Basic.NET → HALCON/.NET
Python → HALCON/Python
The system requirements and supported platforms are listed in the Installation Guide, section 1.4 on page 8.
14 Which HALCON Interface to Use
Parallel Programming and HALCON 15
General Issues
Chapter 2
This chapter explains how to use HALCON on multi-core or multi-processor hardware, concentrating on the main
features: automatic parallelization (section 2.1 on page 15) and the support of parallel programming (section 2.2
on page 16).
1. Tuple level
If an operator is called with iconic input parameters containing tuples, i.e., arrays of images, regions, or
XLDs, it can be parallelized by distributing the tuple elements, i.e., the individual images, regions, or
XLDs, on parallel threads. This method requires that all input parameters contain the same number of
tuple elements (or contain a single iconic object or value).
2. Channel level
If an operator is called with input images containing multiple channels, it can be parallelized by distributing
the channels on parallel threads. This method requires that all input image objects contain the same number
of channels or a single channel image.
3. Domain level
An operator supporting this level can be parallelized by dividing its domain and distributing its parts on
parallel threads.
4. Internal data level
Only parts of the operator are parallelized. The actual degree of parallelization depends on the implemen-
tation of the operator. As a result, the potential speedup on multi-core systems varies among operators
utilizing this parallelization method.
The description of a HALCON operator in the Reference Manuals contains an entry called ’Execution Informa-
tion’, which specifies its behavior when using HALCON on a multi-core or multi-processor hardware. This entry
indicates whether the operator will be automatically parallelized by HALCON and by which method (tuple, chan-
nel, domain, internal data).
The parallelization method of an arbitrary operator opname can also be determined using get_operator_info:
HALCON supports parallel programming by being thread-safe and reentrant, i.e., different threads can call HAL-
CON operators simultaneously without having to wait. However, not all operators are fully reentrant. This section
takes a closer look at the reentrancy of HALCON. Furthermore, it points out issues that should be kept in mind
when writing parallel programs that use HALCON.
The example program example_multithreaded1.c in the directory example\c shows how to use multithread-
ing to extract different types of components on a board in parallel using HALCON/C.
Furthermore, HALCON provides special operators to synchronize threads (see section 2.2.3 on page 17).
1. Reentrant
An operator is fully reentrant if it can be called by multiple threads simultaneously, independent of the data
it is called with.
Take special care when multiple threads use the same data objects, e.g., the same image variable. In this
case, you must synchronize the access to this variable manually using the corresponding parallel program-
ming mechanisms (mutexes, semaphores). Better still is to avoid such cases as far as possible, i.e., to use
local variables. Note that this is no special problem of HALCON but of parallel programming in general.
2. Local
Operators marked as local should be called only from the thread that instantiates the corresponding objects.
3. Single write, multiple read
A certain group of operators should be called simultaneously only if the different calling threads work on
different data.
2.2 Parallel Programming 17
As this thread behavior is not recommended in general, HALCON does not actively prevent it and thus
saves overhead. This means that if you (accidentally) call such operators simultaneously with the same
General Issues
data, no thread will block but you might get undesirable effects.
4. Mutually exclusive
Some operators cannot be called simultaneously by multiple threads but may be executed in parallel to
other HALCON operators.
5. Exclusive
A group of operators is executed exclusively by HALCON, i.e., while such an operator is executed, all
other threads cannot call another HALCON operator.
6. Independent
A group of operators is executed independently from others, even exclusive operators.
As mentioned already, the description of a HALCON operator in the Reference Manuals contains an entry called
’Execution Information’, which specifies its behavior when using HALCON. This entry specifies the level of
reentrancy as described above.
In the operator section “System . Multithreading”, HALCON provides operators for creating and using synchro-
nization objects like mutexes, events, condition variables, and barriers.
18 Parallel Programming and HALCON
With them, you can synchronize threads in a platform-independent way. Note, however, that up to now no operators
for creating the threads are provided.
2.2.4 Examples
HALCON currently provides the following examples for parallel programming (paths relative to %HALCONEXAM-
PLES%):
HALCON/C
• c\source\example_multithreaded1.c
two threads extract different elements on a board in parallel
HALCON/.NET
• c#\MultiThreading (C#)
performs image acquisition, processing, and display in three threads
• hdevengine\c#\MultiThreading (C#)
executes the same HDevelop procedure in parallel by two threads using HDevEngine
• hdevengine\c#\MultiThreadingTwoWindows (C#)
executes different HDevelop procedures in parallel by two threads using HDevEngine
HALCON/C++
• mfc\FGMultiThreading (using MFC)
performs image acquisition / display and processing in two threads
• hdevengine\mfc\source\exec_programs_mt_mfc.cpp
executes HDevelop procedures for image acquisition, data code reading, and visualization in parallel using
HDevEngine and MFC
• hdevengine\cpp\source\exec_procedures_mt.cpp
executes HDevelop programs in parallel using HDevEngine
Various windowing systems have different restrictions on multithreading that have an impact on HALCON graphic
operators.
On Microsoft Windows, accessing a window’s message queue is only possible from the thread that created the
window. Furthermore, a window that has a parent window must be opened in the thread that created the parent
window.
All HALCON graphic operators are automatically redirected to the correct thread. This is done by sending a
special message to the window. To avoid conflicts with user code, the ID of this message is dynamically generated
using the Win32 RegisterWindowMessage function. For windows not created by HALCON (this is relevant
for new_extern_window and when specifying a parent window to open_window), the non-HALCON window is
automatically subclassed using the Win32 SetWindowSubclass function. The only requirement for user code is
that for this mechanism to work, each window must have an active message loop.
To avoid having to write user code to handle the message loop of a HALCON window, HALCON can be instructed
to create all top level HALCON windows from a special thread via set_system('use_window_thread','true'),
2.4 Using HALCON with OpenMP 19
which will then also take care of the message loop. Note that this may negatively affect performance if many
windows are used simultaneously, as HALCON provides only a single thread for all windows.
General Issues
The various HALCON draw_* operators work by actively polling the message queue. Several draw_* operators
can be active if they target windows belonging to different threads.
2.3.2 X11
When using the X11 windowing system, HALCON will automatically call the Xlib function XInitThreads when
the first window is opened (note that querying the available OpenGL features will open a hidden X11 window in
the background).
This means that if an application using HALCON also uses Xlib functions independently of HALCON, either
directly by explicitly calling Xlib functions or indirectly through some other library that uses Xlib, care must be
taken that XInitLibrary is called first before any other Xlib function. The easiest way to ensure this is to call
XInitThreads very early in the application’s main function, before calling any other library functions.
Using different OpenMP runtimes in a single program leads to an undefined behavior. Thus, if you have an
application using HALCON and OpenMP, meaning your application uses the halcondl library and OpenMP, you
have to link against the Intel OpenMP library libiomp5. The latter one is installed with HALCON. For the linking,
the necessary steps depend on your platform:
Windows
You can do this in Visual Studio:
1. Open Visual Studio.
2. Go to Project Properties → Linker → Input.
3. Add vcomp.lib (vcompd.lib for the debug configuration) to Ignore Specific Default
Libraries
4. Add libiomp5md.lib from %HALCONROOT%\lib %HALCONARCH% to the Additional
Dependencies.
Linux
For gcc and clang, add
• -fopenmp to the compile flags
• -L$HALCONROOT/lib/$HALCONARCH/thirdparty -liomp5 to the linker flags
This section contains additional information that helps you to use HALCON on multi-core or multi-processor
hardware.
With the help of HALCON’s system parameters, which can be set and queried with the operators set_system and
get_system, respectively, you can customize the behavior of the parallelization mechanisms.
You can query the number of processors (or cores) by calling
get_system('processor_num', Information)
20 Parallel Programming and HALCON
You can switch off parts of the features of HALCON with the help of the operator set_system. To switch off
the automatic parallelization mechanism, call (HDevelop notation, see the Reference Manual for more information)
set_system('parallelize_operators','false')
set_system('reentrant','false')
Of course, you can switch on both behaviors again by calling set_system with 'true' as the second parame-
ter. Please note that when switching off reentrancy you also switch off automatic parallelization, as it requires
reentrancy.
A reason for switching off the automatic parallelization mechanism could be if your multithreaded program does
its own scheduling and does not want HALCON to interfere via automatic parallelization. Note that you do not
need to switch off automatic parallelization when using HALCON on a single-processor or single-core computer;
HALCON does so automatically if it detects only one processor or core.
When switching off the automatic parallelization, you might consider switching off the use of thread pools (see the
parameter ’thread_pool’ of set_system).
! Do not switch on reentrancy if this is already the case. Otherwise, this will reset the parallelization system,
which includes switching on the automatic operator parallelization. This will decrease the performance in case of
manual parallelization (multithreading).
With the system parameter ’parallelize_operators’, you can customize the automatic parallelization mech-
anisms in more detail. Please see the description of set_system for more information.
Finally, you can influence the number of threads used for automatic parallelization with the parameters
’thread_num’ and ’tsp_thread_num’ (set_system). Reducing the number of threads is useful if you also
perform a manual parallelization in your program. If you switch off automatic parallelization permanently, you
should also switch off the thread pool to save resources of the operating system.
All image acquisition devices supported by HALCON can be used on multi-core or multi-processor hard-
ware. Please note, that none of the corresponding operators is automatically parallelized. Most of the op-
erators are reentrant, only the operators concerned with the connection to the device (open_framegrabber,
info_framegrabber, and close_framegrabber) are processed exclusively in their group, i.e., they block the
concurrent execution of other image acquisition operators but run in parallel with all non-exclusive operators out-
side of this group (see open_framegrabber). Furthermore, these operators are local, i.e., under Windows they
should be called from the thread that instantiates the corresponding object (see section 2.2.1 on page 16).
By default, HALCON uses spinlocks for synchronization between threads to maximize performance. However,
there are several situations where using spinlocks is not recommended:
1. If there are more threads running than there are CPUs to run them on, performance will be severely reduced.
2. If any threads using HALCON use any form of real-time scheduling (SCHED_FIFO, SCHED_RR, or
SCHED_DEADLINE on Linux systems, REALTIME_PRIORITY_CLASS on Windows systems), HALCON can
deadlock.
To turn spinlocks off, call the function HSetUseSpinLock(0) before calling the first HALCON operator. Please
note that calling HSetUseSpinLock after HALCON has been initialized leads to undefined behavior.
2.5 Additional Information on HALCON 21
General Issues
The HALCON thread pool used for the automatic operator parallelization will always use spinlocks, even if
HSetUseSpinLock has been called to turn them off. Thus, it is important to make sure the thread pool does
not use more threads than CPUs are actually available to run them on. You must be especially careful if your
program uses any form of real-time scheduling, as your program can deadlock otherwise.
HALCON will normally always create the thread pool during initialization. If you do not need the thread pool,
you can prevent it from being created by calling the function HSetStartUpThreadPool(0) before calling the
first HALCON operator.
General Issues
Chapter 3
set_spy('mode','on')
Alternatively, you can activate HALCON Spy for an already linked program by defining the environment variable
HALCONSPY (i.e., by setting it to any value). How to set environment variables is described in the Installation
Guide, section A.4 on page 45.
You specify the monitoring mode by calling the operator set_spy again with a pair of parameters to be informed
about all operator calls and the names and values of input control parameters. For example:
set_spy('operator','on')
set_spy('input_control','on')
The monitoring mode can also be specified via the environment variable HALCONSPY, using a colon to separate
multiple options:
operator=on:input_control=on
For detailed information on all the debugging options, see the entry for set_spy in the HALCON Reference
Manuals.
Please note that HALCON Spy cannot be used to debug multithreaded programs or programs using the automatic
parallelization.
If you want to use HALCON Spy on a multi-core or multi-processor hardware, you must therefore first switch off
the automatic parallelization as described in section 2.5.1 on page 19.
A possible scenario in which the problem may occur is using HALCON/C++ to implement an ATL control, for
example.
To overcome this problem, it is necessary to call the function FinalizeHALCONLibrary() before unloading
the DLL. Please note that the application has to be linked against halcon.lib. Make sure that the call to
FinalizeHALCONLibrary() is not from within any other DLL’s DllMain function. Please note that once
FinalizeHALCONLibrary() has been called, no further HALCON functions may be called. Please also note
that the HALCON library is not capable to free all resources properly during termination. This might result in
memory leaks when loading and unloading the HALCON library repeatedly.
Applications using a HALCON floating license should return the license to the license server on exit so that it
can be reused immediately. As socket communication is not possible during process termination, a process using
HALCON cannot return floating licenses automatically on Windows by itself and requires the help of the license
watchdog process hlwd (see Installation Guide, section 5.7 on page 31 for more details).
If the license watchdog is not available, the process using HALCON must return the floating license before ter-
mination either by calling FinalizeHALCONLibrary() as described in section 3.2 on page 23, or by calling the
HALCON set_system operator with the parameter ’return_license’. This is only necessary on Windows
when using a floating license and when the license watchdog is unavailable.
HALCON includes an extension for the inspection of HALCON variables in Visual Studio (see the Installation
Guide, section 1.4 on page 8, for the system requirements). A development license is required for this extension to
work (see the Installation Guide, chapter 5 on page 25 for the different license types). If the license is valid for the
HALCON Progress-Steady edition, only the corresponding edition of the HALCON Variable Inspect can be used,
i.e., HALCON Progress-Steady Variable Inspect requires HALCON Progress-Steady. To change the HALCON
Variable Inspect edition, you have to reopen Visual Studio and choose the desired HALCON Variable Inspect
edition.
The extension is registered by default for your Visual Studio installation while installing HALCON. In case this
option was deactivated for the installation, you can register the extension manually by double-clicking one of the
following files, depending on your version of Visual Studio:
If multiple versions of Visual Studio are installed on your machine, the installer will let you select the version(s)
you wish to add the extension to. Once installed, the extension should appear in the side pane of Visual Studio.
If it does not, select Tools → HALCON 24.11 Progress-Steady Variable Inspect. Please note that the
environment variable %HALCONROOT% must be set for the extension to work.
The extension is provided only for the inspection of iconic objects and tuples in the following languages:
Interface Language
HALCON/C++ C++
HALCON/.NET C#, Visual Basic.NET
General Issues
• HALCON Variable Inspect cannot inspect objects located in GPU memory. You can only inspect objects if
they are stored in CPU memory.
• At the moment, HALCON Variable Inspect does not work with C++/CLI applications. The only supported
combinations are native C++ with HALCON/C++, C# with HALCON/.NET, and Visual Basic.NET with
HALCON/.NET.
• Note that Visual Studio Express does not support extensions.
• HALCON Variable Inspect cannot be used to inspect images, with fewer channels than the default number
of channels for HImage.
• Mark a variable in the program code. Then drag the selected variable from the program code to the “Watch”
list.
• Right-click the variable in the program code and select Add to HALCON Watch from the context menu.
• Right-click a variable in the “Locals” list and select Add to Watch from the context menu.
Note that the fewer variables are listed in the inspection window the better the performance. Therefore, moving
only the desired variables to the “Watch” list and inspecting the variables in the Watch tab improves the perfor-
mance.
By default, the variables in the inspection window are listed in the same order as in the Locals window of Visual
Studio. The variables can be sorted in descending or ascending order by clicking on the header of the respective
columns in the inspection window. To switch back to the default order, click the header of the column “#”.
The table Table 3.2 on page 25 describes which information is displayed for the variables of the “Locals” and
“Watch” list of the inspection window.
Columns Description
# This column contains no values. It can be used to restore the default order of the
variable list by clicking on the header of this column.
Name Name of the local HALCON variable.
Type Type of the local HALCON variable. Only iconic variables and tuples are sup-
ported in the extension.
Status Current status that indicates if the debug information of the variable could be
retrieved. In case it has been successfully retrieved, a green checkmark is dis-
played. If the information could not be retrieved, a red crossmark is displayed.
Status Message Status message for the variable. If the HALCON data of a variable could not be
retrieved, the status message delivers more detailed information about the cause.
If the HALCON data could be retrieved, additional information about the data
is displayed.
Column Description
Scope Scope of the HALCON variable. For local HALCON variables the scope “Lo-
cal” is returned and for global HALCON variables the scope “Global”. If the
scope could not be determined, i.e., because the variable is not in the current
scope or uninitialized, “Unknown” is returned.
Inside Scope Current status if the HALCON variable is in the current scope of the program.
If the variable is in the current scope, “True” is returned, else “False”.
Table 3.3: Additional columns of the variable list in the Watch tab.
The Watch tab of the inspection window gives some additional information about the scope, see Table 3.3 on page
26.
To select a variable for the inspection, click the corresponding entry in the variable list of the inspection window.
If the debug information and HALCON data of the variable has already been retrieved, i.e., if Status has a green
checkmark, the value of the variable is displayed. Otherwise, the retrieval of the HALCON data is started and the
value of the variable is displayed if the data could be retrieved. To enforce a complete new retrieval of the data,
even for variables whose data have already been obtained, double-click the variable. The inspection window is
automatically updated if the content of the currently displayed variable changes.
To deselect a variable, press Ctrl and click the respective line of the variable. Alternatively, right-click the line of
the variable and select Deselect all from the context menu. In some cases, it is desired to display the data of a
variable again. This can be achieved by deselecting and selecting the variable again or by double-clicking it.
If a member of a variable cannot be resolved, e.g., if the variable is related to a class, it is not sufficient to inspect
only the member of this variable. Instead, mark the complete expression before right-clicking and inspecting the
member variable.
Please note that native 64-bit data types, e.g., int8 images, and image data with a size > 0.5 GB are not supported.
• Name of the iconic variable, type, number of channels (for images), and the dimensions (for images).
• Gray value (v), row (r), and column (c) at the mouse position
Iconic variables may be stacked: For example, image data may be overlayed with region data by first inspecting
the image variable and then the region variable.
3.5 Handling Licensing Errors 27
General Issues
Figure 3.1: Inspecting iconic variables.
Getting Help
You can open the operator reference of a specific operator right from the context menu of Visual Studio. Move the
mouse cursor over a method name, right-click it and select HALCON Help.
Persistent Settings
The following settings are persistent between sessions:
When running HALCON with a runtime license and a dongle, HALCON checks regularly whether the dongle is
still available. This check has no measurable impact on the performance of HALCON.
In order to be notified if the dongle was removed and a license error is imminent, applications can register a
callback function with HALCON that will be called when HALCON detects that the dongle is no longer available.
HALCON operators will fail with licensing errors after about two to four minutes after this callback fires. If the
dongle is reinserted before this time, HALCON will continue to operate normally.
Please note that if you do not register a callback and the dongle becomes unavailable during runtime, HALCON
operators will fail with a license error and will therefore not provide meaningful output parameters. Depending on
your application, this might even lead to crashes. It is highly suggested to handle errors from operators correctly
or register the callback to notify the user and/or shut down the application in a controlled way.
To register your own callback function, use the following code in your application:
HSetLicenseRecheckFailedCallback(MyLicenseRecheckFailedCallback,
&MyLicenseRecheckFailedContext);
MyLicenseRecheckFailedContext is a user-defined structure that you can use to pass extra information to your
callback. If you do not need this, you can pass a NULL pointer instead.
To unregister a callback, simply call HSetLicenseRecheckFailedCallback with a NULL pointer as argument.
Note that callbacks are not chained – registering a callback will overwrite any previously registered callback.
For example, in your application, you might implement a proper licensing error handling like this:
Herror error;
Htuple param, value;
create_tuple_s(¶m, "version");
set_check("~give_error");
error = T_get_system(param, &value);
destroy_tuple(value);
destroy_tuple(param);
try
{
HalconCpp::HTuple value = HalconCpp::HSystem::GetSystem("version");
}
catch (HalconCpp::HException &exception)
{
if ( (exception.ErrorCode() >= H_ERR_LIC_NO_LICENSE)
&& (exception.ErrorCode() <= H_ERR_LAST_LIC_ERROR))
{
// Handle licensing error here.
}
}
To check whether a license is available at all, you can use any operator at the beginning of your application and
check the result.
%HALCONEXAMPLES%/c#/MultiThreading
General Issues
30 Tips and Tricks
Part II
Chapter 4
C++
Introducing HALCON/C++
HALCON/C++ is HALCON’s interface to the programming language C++. Together with the HALCON library,
it allows to use the image processing power of HALCON inside C++ programs.
This part is organized as follows:
• In section 4.1 on page 33, we start with a first example program.
• Chapter 5 on page 35 then takes a closer look at the basics of the HALCON/C++ interface,
• while chapter 6 on page 45 gives an overview of the classes HImage, etc.
• Chapter 7 on page 51 shows how to create applications based on HALCON/C++.
• Chapter 8 on page 57 presents typical image processing problems and shows how to solve them using HAL-
CON/C++.
This section demonstrates how to create a simple HALCON application with C++. For a more comprehensive
description, see chapter 7 on page 51.
The task is to read an image and compute the number of connected regions in it, as illustrated in figure 4.1 on page
33
Figure 4.1: Left: Input image of a printed circuit board. Middle: Regions found by threshold, colored red. Right:
Connected regions, a result of connection.
#include <HalconCpp.h>
using HalconCpp::HImage;
using HalconCpp::HRegion;
int main()
{
HImage img{"pcb"};
./region_example
As a result, you should see the following output ’Number of Regions: 43’.
Basics of the HALCON/C++ Interface 35
Chapter 5
C++
Basics of the HALCON/C++ Interface
The HALCON/C++ interface provides two different approaches to use HALCON’s functionality within your C++
program: a procedural and an object-oriented approach. The procedural approach corresponds to calling HAL-
CON operators directly as in C or HDevelop, e.g.:
In addition to the procedural approach, HALCON/C++ allows to call HALCON operators in an object-oriented
way, i.e., via a set of classes. For example, the code from above can be “translated” into:
HImage original_image("monkey");
HImage smoothed_image = original_image.MeanImage(11, 11);
This simple example already shows that the two approaches result in clearly different code: The operator calls
differ in the number and type of parameters. Furthermore, functionality may be available in different ways; for
example, images can be read from files via a constructor of the class HImage. In general, we recommend using
the object-oriented approach. Note, however, that HDevelop can export programs only as procedural C++ code.
Section 5.5 on page 43 shows how to combine procedural with object-oriented code.
In the following sections, we take a closer look at various issues regarding the use of the HALCON/C++ interface;
chapter 6 on page 45 describes the provided classes in more detail.
All functions and classes of HALCON/C++ use the namespace HalconCpp to prevent potential name conflicts
with other C++ libraries.
You can specify (“use”) the namespace in three ways:
• Specifically, by prefixing each class name or operator call with the namespace:
• Locally, by placing the directive using namespace HalconCpp; at the beginning of a block, e.g., at the
beginning of a function:
36 Basics of the HALCON/C++ Interface
In this case, you can use HALCON’s classes and functions without prefix inside this block.
• Globally, by placing the directive directly after including HalconCpp.h. In this case, you do not need the
prefix in your whole application:
#include "HalconCpp.h"
using namespace HalconCpp;
Which method is most suitable depends on your application, more specifically, what other libraries it contains and
whether there are any name collisions.
Please note that the namespace is not mentioned in the operator descriptions in the reference manual to keep it
readable. Similarly, in the following sections the namespace is left out.
void MeanImage (const HObject& Image, HObject* ImageMean, const HTuple& MaskWidth,
const HTuple& MaskHeight)
HImage HImage::MeanImage (Hlong MaskWidth, Hlong MaskHeight) const
Image (input_object) . . . (multichannel-)image(-array) ; HObject (byte / int2 / uint2 / int4 / int8 / real / vec-
tor_field)
ImageMean (output_object) . . . (multichannel-)image(-array) ; HObject (byte / int2 / uint2 / int4 / int8 / real
/ vector_field)
MaskWidth (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; HTuple (Hlong)
MaskHeight (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; HTuple (Hlong)
Figure 5.1: The head and parts of the parameter section of the reference manual entry for mean_image.
Please note that the reference manual does not list all possible signatures of the operators. A complete list can be
found in the file include\halconcpp\HOperatorSet.h.
Below, we
• take a closer look at the parameters of an operator call (section 5.2.1 on page 37)
• describe how to call operators via classes (section 5.2.2 on page 39) or via special constructors (section 5.2.3
on page 39) or destructors (section 5.2.4 on page 40)
• explain another special HALCON concept, the tuple mode (section 5.2.5 on page 40)
5.2 Calling HALCON Operators 37
void FindBarCode (const HObject& Image, HObject* SymbolRegions, const HTuple& BarCodeHandle,
const HTuple& CodeType, HTuple* DecodedDataStrings)
HRegion HBarCode::FindBarCode (const HImage& Image, const HTuple& CodeType,
HTuple* DecodedDataStrings) const
HRegion HBarCode::FindBarCode (const HImage& Image, const HString& CodeType,
HString* DecodedDataStrings) const
HRegion HBarCode::FindBarCode (const HImage& Image, const char* CodeType,
HString* DecodedDataStrings) const
HRegion HBarCode::FindBarCode (const HImage& Image, const wchar_t* CodeType,
C++
HString* DecodedDataStrings) const
HRegion HImage::FindBarCode (const HBarCode& BarCodeHandle, const HTuple& CodeType,
HTuple* DecodedDataStrings) const
HRegion HImage::FindBarCode (const HBarCode& BarCodeHandle, const HString& CodeType,
HString* DecodedDataStrings) const
HRegion HImage::FindBarCode (const HBarCode& BarCodeHandle, const char* CodeType,
HString* DecodedDataStrings) const
HRegion HImage::FindBarCode (const HBarCode& BarCodeHandle, const wchar_t* CodeType,
HString* DecodedDataStrings) const
Figure 5.2: The head and parts of the parameter section of the reference manual entry for find_bar_code.
HALCON distinguishes two types of parameters: iconic and control parameters. Iconic parameters are related
to the original image (images, regions, XLD objects), whereas control parameters are values such as integers,
floating-point numbers, strings, or handles.
A special form of control parameters are the so-called handles. A well-known representative of this type is the
window handle, which provides access to an opened HALCON window, e.g., to display an image in it. Besides,
handles are used when operators share complex data, e.g., the operators for shape-based matching which cre-
ate and then use the model data, or for accessing input/output devices, e.g., image acquisition devices. Classes
encapsulating handles are described in detail in section 6.2.3 on page 47.
Both iconic and control parameters can appear as input and output parameters of a HALCON operator. For ex-
ample, the operator MeanImage expects one iconic input parameter, one iconic output parameter, and two input
control parameters (see figure 5.1); figure 5.2 shows an operator which has all four parameter types. Note how
some parameters “disappear” from within the parentheses if you call an operator via a class; this mechanism is
described in more detail in section 5.2.2 on page 39.
An important concept of HALCON’s philosophy regarding parameters is that input parameters are not modified
by an operator. As a consequence, they are passed by value (e.g., Hlong MaskWidth in figure 5.1) or via a
constant reference (e.g., const HObject& Image). This philosophy also holds if an operator is called via a class,
with the calling instance acting as an input parameter. Thus, in the following example code the original image is
not modified by the call to MeanImage; the operator’s result, i.e., the smoothed image, is provided via the return
value instead:
HImage original_image("monkey");
HImage smoothed_image = original_image.MeanImage(11, 11);
In contrast to input parameters, output parameters are always modified, thus they must be passed by reference.
38 Basics of the HALCON/C++ Interface
void InfoFramegrabber (const HTuple& Name, const HTuple& Query, HTuple* Information,
HTuple* ValueList)
static HString HInfo::InfoFramegrabber (const HString& Name, const HString& Query, HTuple* ValueList)
static HString HInfo::InfoFramegrabber (const char* Name, const char* Query, HTuple* ValueList)
static HString HInfo::InfoFramegrabber (const wchar_t* Name, const wchar_t* Query, HTuple* ValueList)
Figure 5.3: The head and parts of the parameter section of the reference manual entry for info_framegrabber.
Note that operators expect a pointer to an already existing variable or class instance! For example, when calling
the operator FindBarCode as in the following lines of code, variables of the class HTuple are declared before
passing the corresponding pointers using the operator &.
HImage image("barcode/ean13/ean1301");
HBarCode barcode(HTuple(), HTuple());
HString result;
The above example shows another interesting aspect of output parameters: When calling operators via classes, one
output parameter may become the return value (see section 5.2.2 on page 39 for more details); in the example,
FindBarCode returns the bar code region.
Many HALCON operators accept more than one value for certain parameters. For example, you can call the
operator MeanImage with an array of images (see figure 5.1); then, an array of smoothed images is returned. This
is called the tuple mode; see section 5.2.5 on page 40 for more information.
String Parameters
Regardless of the encoding of the HALCON library (set_system(’filename_encoding’, ...)) the HAL-
CON/C++ interface expects raw char pointer strings that are passed to HALCON operators and to HTuple or
HString instances to be UTF-8 encoded.
Output strings are always of type HString with automatic memory management. These strings are by default
also UTF-8 encoded. The encoding of the HALCON/C++ interface (interface encoding) can be changed to local-
8-bit encoding via a call of HalconCpp::SetHcppInterfaceStringEncodingIsUtf8(false). The current
interface encoding can be requested via HalconCpp::IsHcppInterfaceStringEncodingUtf8(). It is not rec-
ommended to switch the interface encoding back and forth. The setting should be adjusted only once at the very
beginning of the program (before the first HALCON operator or assignment), because HTuple instances can not
store in which encoding the contained strings are present, i.e, for all write and read accesses, the same encoding
must be set. Furthermore, the interface encoding is set globally and is therefore not suitable for multithreading
programs: Changing the setting in one thread has an effect on other threads.
In the following example code, the operator InfoFramegrabber (see also figure 5.3) is called with two output
string parameters to query the currently installed image acquisition board:
Note that it is also not necessary to allocate memory for multiple output string parameters returned as HTuple:
5.2 Calling HALCON Operators 39
HImage image("barcode/ean13/ean1301");
HBarCode barcode(HTuple(), HTuple());
HString result;
HObject image;
C++
HTuple barcode;
HObject code_region;
HTuple result;
ReadImage(&image, "barcode/ean13/ean1301");
CreateBarCodeModel(HTuple(), HTuple(), &barcode);
FindBarCode(image, &code_region, barcode, "EAN-13", &result);
Figure 5.4: Using FindBarCode via HBarCode, via HImage, or in the procedural approach.
HBarCode barcode;
barcode.CreateBarCodeModel(HTuple(), HTuple());
40 Basics of the HALCON/C++ Interface
If the instance was already initialized, the corresponding data structures are automatically destroyed before con-
structing and initializing them anew (see also section 5.2.4). The handle classes are described in more detail in
section 6.2.3.2 on page 48.
Below we take a brief look at the most important classes. A complete and up-to-date list of available constructors
can be found in the HALCON operator reference and the corresponding header files in %HALCONROOT%\include\
cpp.
• Images:
The class HImage provides constructors based on the operators ReadImage, GenImage1, and
GenImageConst.
• Regions:
The class HRegion provides constructors based on operators like GenRectangle2 or GenCircle.
• Windows:
The class HWindow provides a constructor based on the operator OpenWindow.
Of course, you can close a window using CloseWindow and then open it again using OpenWindow. In
contrast to the iconic parameter classes, you can call the “constructor-like” operator OpenWindow via an
instance of HWindow in the intuitive way, i.e., the calling instance is modified; in addition the corresponding
handle is returned. HWindow is described in more detail in section 6.2.3.1 on page 48.
All HALCON/C++ classes provide default destructors which automatically free the corresponding memory.
The default destructors of classes encapsulating handles, e.g., HShapeModel or HFramegrabber, work similar to
members like ClearShapeModel or CloseFramegrabber, respectively.
There is no need to call these operators as you can initialize instances anew as described in section 5.2.3.
Basically, we differentiate between destroying a handle and destroying the underlying data structure. The data
structure can be destroyed in two ways: Automatically as soon as the last reference to the data structure has been
deleted. Explicitly by calling an operator, e.g., CloseWindow. Explicit destruction invalidates references, but
access is secure.
As already mentioned in section 5.2.1 on page 37, many HALCON operators can be called in the so-called tuple
mode. In this mode, you can, e.g., apply an operator to multiple images or regions with a single call. The standard
case, e.g., calling the operator with a single image, is called the simple mode. Whether or not an operator supports
the tuple mode can be checked in the reference manual. For example, take a look at figure 5.5, which shows an
extract of the reference manual entry for the operator CharThreshold: In the parameter section, the parameter
Image is described as an image(-array); this signals that you can apply the operator to multiple images at once.
If you call CharThreshold with multiple images, i.e., with an image tuple, the output parameters automat-
ically become tuples as well. Consequently, the parameters Characters and Threshold are described as
region(-array) and integer(-array), respectively.
Note that the class HTuple can also contain arrays (tuples) of control parameters of mixed type; please refer to
section 6.2.1 on page 46 for more information about this class. In contrast to the control parameters, the iconic
parameters remain instances of the class HObject in both modes, as this class can contain both single objects and
object arrays.
In the object-oriented approach, control parameters can be of a basic type (simple mode only) or instances of
HTuple (simple and tuple mode).
After this rather theoretic introduction, let us take a look at two examples which are both realized in the object-
oriented and in the procedural approach. The examples highlight some interesting points:
5.2 Calling HALCON Operators 41
void CharThreshold (const HObject& Image, const HObject& HistoRegion, HObject* Characters,
const HTuple& Sigma, const HTuple& Percent, HTuple* Threshold)
HRegion HImage::CharThreshold (const HRegion& HistoRegion, double Sigma, const HTuple& Percent,
HTuple* Threshold) const
HRegion HImage::CharThreshold (const HRegion& HistoRegion, double Sigma, double Percent,
Hlong* Threshold) const
C++
HistoRegion (input_object) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HObject
Characters (output_object) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HObject
Sigma (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; HTuple (double)
Percent (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; HTuple (double / Hlong)
Threshold (output_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; HTuple (Hlong)
Figure 5.5: The head and parts of the parameter section of the reference manual entry for CharThreshold.
// object-oriented approach
HImage image("alpha1");
HRegion region;
Hlong threshold;
// procedural approach
HObject image;
HObject region;
HTuple threshold;
ReadImage(&image, "alpha1");
CharThreshold(image, image, ®ion, 2, 95, &threshold);
DispObj(image, window);
DispObj(region, window);
cout << "Threshold for 'alpha1': " << threshold.ToString();
The second example shows how CharThreshold is applied in tuple mode, i.e., to two images at once:
42 Basics of the HALCON/C++ Interface
// object-oriented approach
HImage images;
HRegion regions;
HTuple thresholds;
images.GenEmptyObj();
for (int i = 1; i <= 2; i++)
{
images = images.ConcatObj(HImage(HTuple("alpha") + i));
}
// procedural approach
HObject images, image;
HObject regions, region;
HTuple num;
HTuple thresholds;
GenEmptyObj(&images);
Error handling is fully based on exceptions using try ... catch blocks.
The following code shows how to catch and evaluate errors that might occur when reading an image from file. The
call to ReadImage is encapsulated by a try block; the error code of the exception is evaluated in a corresponding
catch block. For more information on HALCON error codes please refer to the Extension Package Programmer’s
Manual, appendix A on page 105.
5.4 Memory Management 43
try
{
image.ReadImage(filename);
}
catch (HException &except)
{
if (except.ErrorCode() == H_ERR_FNF)
{
// Handle file not found error
}
else
C++
{
// Pass on unexpected error to caller
throw except;
}
}
All of HALCON’s classes, i.e., not only HImage, HRegion, HTuple, HFramegrabber etc., but also the class
HObject used when calling operators in the procedural approach, release their allocated resources automatically
in their destructor (see also section 5.2.4 on page 40). Furthermore, when constructing instances anew, e.g., by
calling CreateBarCodeModel via an already initialized instance as mentioned in section 5.2.3 on page 39, the
already allocated memory is automatically released before reusing the instance. Thus, there is no need to call
the operator ClearObj in HALCON/C++; what is more, if you do use it HALCON will complain about already
released memory. To explicitly release the resources before the instance gets out of scope, you can call the method
Clear() of the instance.
As already noted, we recommend using the object-oriented approach wherever possible. However, there are some
reasons for using the procedural approach, e.g., if you want to quickly integrate code that is exported by HDevelop,
which can only create procedural code.
The least trouble is caused by the basic control parameters as both approaches use the elementary types long etc.
and the class HTuple. Iconic parameters and handles can be converted as follows:
HImage o_image(p_image);
Iconic parameters can be converted from HObject to, e.g., HImage simply by calling the constructor with
the procedural variable as a parameter.
• Converting handles into specific handle classes
HTuple p_barcode;
CreateBarCodeModel(HTuple(), HTuple(), &p_barcode);
HBarCode o_barcode(p_barcode.H());
o_code_region = o_barcode.FindBarCode(o_image, "EAN-13", &result);
Note that instances of HImage can be used in procedural code where HObject is expected.
As already remarked in section 5.2.4 on page 40, you must not use operators like ClearShapeModel,
ClearAllShapeModels, or CloseFramegrabber together with instances of the corresponding handle classes!
44 Basics of the HALCON/C++ Interface
HALCON/C++ provides iostream operators by default. Note that it may be necessary to enable the namespace
std:
If you want to use the older iostream interface (i.e., <iostream.h> instead of <iostream>), the following line
has to be added (otherwise, there may be conflicts with the HALCON include files):
#define HCPP_NO_USE_IOSTREAM
FindText, CreateMutex, CreateEvent, and DeleteFile are also functions of the Windows API. There are
defines on FindTextW, CreateMutexW, CreateEventW, and DeleteFileW if UNICODE is defined, otherwise there
are defines on FindTextA, CreateMutexA, CreateMutexA, and DeleteFileA. These defines are undefined in
HalconCpp.h. If you want to use the corresponding Windows API calls, you must use FindTextA, FindTextW,
CreateMutexA, CreateMutexW, CreateEventA, CreateEventW, DeleteFileA, or DeleteFileW directly.
The HALCON Parameter Classes 45
Chapter 6
C++
The HALCON Parameter Classes
The HALCON operator reference contains a complete list of the generic classes and member functions of HAL-
CON/C++. This chapter contains a summary of additional convenience members.
In addition, HALCON/C++ contains many operator overloads, which are consistent with HALCON/.NET. See
section 11.1.4 on page 73 for a list of the overloaded operators. i
6.1.1 Regions
A region is a set of coordinates in the image plane. Such a region does not need to be connected and it may contain
holes. A region can be larger than the actual image format. Regions are represented by the so-called runlength
coding in HALCON. The class HRegion represents a region in HALCON/C++. Besides those operators that can
be called via HRegion (see also section 5.2.2 on page 39), HRegion provides the following member functions:
• HTuple HRegion::Area()
Area of the region, i.e., number of pixels, see reference manual entry of AreaCenter.
• HTuple HRegion::Row()
Center row of the region.
• HTuple HRegion::Column()
Center column of the region.
6.1.2 Images
There is more to HALCON images than just a matrix of pixels: In HALCON, this matrix is called a channel, and
images may consist of one or more such channels. For example, gray value images consist of a single channel,
color images of three channels. Channels can not only contain the standard 8 bit pixels (pixel type byte) used
46 The HALCON Parameter Classes
to represent gray value images, HALCON allows images to contain various other data, e.g. 16 bit integers (type
int2) or 32 bit floating point numbers (type real) to represent derivatives. Besides the pixel information, each
HALCON image also stores its so-called domain in form of a HALCON region. The domain can be interpreted as
a region of interest, i.e., HALCON operators (with some exceptions) restrict their processing to this region.
• HTuple HImage::Width()
Return the width of the image, see reference manual entry of GetImageSize.
• HTuple HImage::Height()
Return the height of the image, see reference manual entry of GetImageSize.
XLD is the abbreviation for eXtended Line Description. This is a data structure used for describing areas (e.g.,
arbitrarily sized regions or polygons) or any closed or open contour, i.e., also lines. In contrast to regions, which
represent all areas at pixel precision, XLD objects provide subpixel precision. There are two basic XLD structures:
contours and polygons.
HALCON/C++ provides both a base class HXLD and a set of specialized classes derived from HXLD, e.g., HXLDCont
for contours or HXLDPoly for polygons.
In contrast to the classes described in the previous sections, the XLD classes provide only member functions
corresponding to HALCON operators (see also section 5.2.2 on page 39).
HALCON/C++ can handle different types of control parameters for HALCON operators:
• integer numbers (Hlong),
• floating point numbers (double), and
• strings (HString).
• handles (HHandle).
A special form of control parameters are the so-called handles, which provide access to more complex data struc-
tures like windows, image acquisition connections, or models for shape-based matching. Internally, handles are
represented by a distinct control data type. They are “magic” values that must not be changed and can differ from
execution to execution and version to version. Once all instances of the handle are overwritten or cleared, the
handle and its content will be destroyed and will become invalid. For handles there exist corresponding classes,
which are described in section 6.2.3 on page 47.
With the class HTuple, HALCON/C++ provides a container class for control parameters. HTuple may contain
arrays of control parameters of mixed type.
6.2.1 Tuples
The class HTuple implements an array of dynamic length. The default constructor constructs an empty array
(Length() == 0). This array can dynamically be expanded via assignments. The memory management, i.e.,
reallocation, freeing, is also managed by the class. The index for accessing the array is in the range between 0 and
Length() − 1.
In order to use instances of an HTuple in different threads concurrently, the method HTuple::Clone() has to be
used (see below).
The following member functions reflect only a small portion of the total. For further information please refer to
the file HTuple.h in %HALCONROOT%\include\halconcpp.
• void HTuple::Clear()
Clear all data inside the tuple.
• HTuple HTuple::Clone()
Create a detached copy duplication the tuple data.
• Hlong HTuple::Length()
Return the number of elements of the tuple.
• HTupleType HTuple::Type()
Return the data type of the tuple (pure data types or mixed tuple).
• HString HTuple::ToString()
C++
Return a simple string representation of the tuple contents.
• Hlong* HTuple::LArr()
double* HTuple::DArr()
char** HTuple::SArr()
Hcpar* HTuple::PArr()
Hphandle* HTuple::HArr()
Access tuple data.
String Encoding
The class HTuple always stores raw char pointer strings in the interface encoding. This is important especially
when accessing the internal raw pointer via the methods HTuple::SArr() and HTupleElement::C().
Under Windows, it is possible to initialize an HTuple or an HTupleElement with a wide character string
(wchar_t*, UTF-16). This wide character string is converted into the current interface encoding (default: UTF-8).
If the interface encoding is not UTF-8, the conversion can involve transcoding errors, i.e., the stored string may
not contain all characters of the input wide character string. The class HTuple does not allow accessing the string
in a different encoding or as wide character string.
6.2.2 Strings
The class HString can be used when transcoding or access to a wide character raw pointer is needed. Like
HTuple, the class can be initialized with a wchar_t pointer string (Windows only) or with a raw char pointer
string with the current interface encoding. HString allows to create a string with a specific encoding via
HString::FromUtf8(const char*) or HString::FromLocal8bit(const char*).
Furthermore, this class allows storing the same string in UTF-8, local-8-bit encoding, and wide character string at
the same time. Thus it is save to use the required raw pointer, as long as the HString instance is not modified or
destroyed. The string remains the owner of the string memory for all representations.
The following methods for accessing raw pointers are provided:
• HString::TextA() and HString::Text()
Return the string as char pointer in the interface encoding.
When the char pointer string is needed in a different encoding, the methods HString::ToUtf8() and
HString::ToLocal8bit() can be used.
The methods HString::LengthA() and HString::Length() return the length in bytes of the char pointer
string returned by HString::TextA() and HString::Text(), respectively.
• HString::TextW() (Windows only)
Returns the string as wide character pointer.
The method HString::LengthW() returns the length of the string returned by HString::TextW() in
words of the datatype wchar_t.
6.2.3.1 Windows
The class HWindow provides the management of HALCON windows in a very convenient way. The properties of
HALCON windows can be easily changed, images, regions, and polygons can be displayed, etc. Besides those
operators that can be called via HWindow (see also section 5.2.2 on page 39), HWindow provides the following
member functions:
• void HWindow::Click()
Wait for a mouse click in the window.
• void HWindow::CloseWindow()
Close the window.
HALCON/C++ provides the so-called handle classes like HFramegrabber, HBarCode, or HClassMlp. These are
based on the class HHandle.
Besides the default constructor, the classes typically provide additional constructors based on suitable operators
as described in section 5.2.3 on page 39; e.g., the class HBarCode provides a constructor based on the operator
CreateBarCodeModel.
The reference manual provides short overview pages for these classes, listing the operators that can be called via
them.
6.3 Vectors
HALCON/C++ provides the class HVector for the use of HALCON vectors in C++ programs. A HALCON vector
is a container that can hold an arbitrary number of elements of the identical data type (i.e., tuple, iconic object,
or vector) and dimension. The type of a vector, i.e., its dimension and the type of its elements is defined when
initializing the vector instance and cannot be changed during its lifetime. A vector with one dimension may be a
vector of tuples or a vector of iconic objects. A two-dimensional vector may be a vector of vectors of tuples or a
vector of vectors of iconic objects, and so on.
Two classes are derived from the root class HVector:
In the following some basic information on how to use vectors in HALCON/C++ is given, e.g., how to construct
vectors and how to access and set vector elements. For a complete list of the available functionality please refer to
the corresponding header file HVector.h in %HALCONROOT%\include\halconcpp.
Construction of Vectors
As already mentioned above, a distinction is made between vectors of iconic objects (HObjectVector) and vectors
of tuples (HTupleVector). The type of a vector must be defined at its construction as in the following lines:
Note that the type of the vector cannot be changed within a program after its construction. Thus, a tuple cannot be
assigned to a vector of iconic objects and vice versa.
To create a two-dimensional vector, i.e., a vector of vectors of iconic objects or a vector of vector of tuples you
may use the following line:
6.3 Vectors 49
You can also create a multi-dimensional vector with more than two dimensions by specifying the desired dimension
in brackets. However, the dimension of a vector is part of its type and has to remain constant within the program
and cannot be changed.
Note that the vectors created by these calls are still empty. How to set the elements of vectors and how to access
C++
them is described below.
The vector element to be accessed is addressed by the specified index in square brackets. If a subelement of a
multi-dimensional vector is to be accessed, you have to use the indices of the corresponding subvector and its
subelement instead.
The left index vec_index defines the index of the subvector and elem_index defines the desired element of the
specified subvector.
If a vector element is to be set, the expression for accessing a vector element is used as reference to the HObject
or HTuple element to be set. The right side of the assignment specifies the value which is assigned to the vector
element.
In the example code above the Image is copied and set as the first vector element of vectorObj. The tuple is also
copied and set as first vector element of vectorTup.
Setting a subelement of a multi-dimensional vector can be done with the same call. However, instead of a single
index, multiple indices must be specified for the corresponding vector element and its subelement, which is to be
set.
It is also allowed to write to a non-existing vector element. Then, the vector is automatically filled with empty
elements if necessary.
50 The HALCON Parameter Classes
Destruction of a Vector
If a vector is not needed anymore for further processing, its contents can be cleared with the following call,
explicitly:
vectorTup.Clear();
Additional Information
In addition to the described functionalities HObjectVector and HTupleVector provide some more functionality
for the use of HALCON vectors in HALCON/CPP, e.g., inserting or removing vector elements, or concatenation
of vectors. Please refer to the corresponding header file HVector.h in %HALCONROOT%\include\halconcpp for
more information.
Creating Applications With HALCON/C++ 51
Chapter 7
C++
Creating Applications With
HALCON/C++
The HALCON distribution contains examples for creating an application with HALCON/C++. The following
sections show
• the relevant directories and files (section 7.1 on page 51)
• the list of provided example applications (section 7.2 on page 52)
• the relevant environment variables (section 7.3 on page 52)
• how to store source files with non-ASCII characters (section 7.4 on page 53)
• how to create an executable under Windows (section 7.5 on page 53)
• how to create an executable under Linux (section 7.6 on page 55)
• include\HProto.h
External function declarations
• %HALCONEXAMPLES%\cpp\console\CMakeLists.txt
Example CMake file, which can be used to compile the example programs
• %HALCONEXAMPLES%\cpp\console\README.md
Information about building the examples using CMake
• %HALCONEXAMPLES%\cpp\console\source\
Directory containing the source files of the example programs
• %HALCONEXAMPLES%\images\
Images used by the example programs
• help\operators_*
Files necessary for online information
• doc\pdf\
Various manuals (in subdirectories)
error_handling.cpp Demonstrates the C++ exception handling (see section 5.3 on page 42)
ia_callback.cpp Shows the usage of the HALCON image acquisition callback functionality
matching.cpp Locates a chip on a board and measures the pins
serialized_item.cpp Shows how to use the serialization of HALCON objects and tuples in the C++ interface
You can find additional examples for using HALCON/C++ in the subdirectories mfc, motif, and qt of
%HALCONEXAMPLES%.
There are some common traps and pitfalls when programs containing string constants with non-ASCII characters
C++
are executed. The following ways to store the source files have different implications:
Your own C++ programs that use HALCON operators must include the file HalconCpp.h, which contains all
user-relevant definitions of the HALCON system and the declarations necessary for the C++ interface. Do this by
adding the following command near the top of your C++ file:
#include "HalconCpp.h"
Compiler:
Include Directories: $(HALCONROOT)\include,$(HALCONROOT)\include\halconcpp
Linker:
Library Directories: $(HALCONROOT)\lib\$(HALCONARCH)
Additional Dependencies: halconcpp.lib
HALCON XL applications:
Please note that you should use HALCON XL only when you need its features.
If you want to use HALCON XL, link the library halconcppxl.lib instead.
!
54 Creating Applications With HALCON/C++
#include "HalconCpp.h"
#include <iostream>
std::cout << "Image - width: " << width.I() << ", height: " << height.I() << '\n';
return 0;
}
1. If required, download CMake (version 3.7.1 or later) from the CMake website and install it.
2. Create a build directory and then run cmake to configure the build and create the application:
mkdir build
cd build
cmake %HALCONEXAMPLES%\cpp\console
cmake --build .
To configure, CMake needs to know the location of the HALCON installation, the location of the example
files, and which HALCON architecture to use:
• Specify the location of the HALCON installation via the HALCON_DIR CMake option, or via the
%HALCONROOT% environment variable if the option is not set.
• Specify the location of the HALCON example files via the %HALCONEXAMPLES% environment vari-
able.
• Specify the HALCON architecture with the HALCON_ARCHITECTURE CMake option, or via the
%HALCONARCH% environment variable. If neither the option nor the environment variable are set,
CMake will try to guess the architecture based on the host build system.
For general information on how to use CMake, see the CMake documentation.
HALCON XL applications: By default, the examples will be built using the normal version of HALCON.
If you want to build using HALCON XL, set the option HALCON_XL to ON or 1 in CMake during the
configuration step. For this, use the following syntax:
3. Optionally, you can use the -G option to specify the generator for a new build tree.
For more information about CMake generators, see the CMake documentation.
7.6 Linux 55
You can find corresponding CMakeLists.txt files in the other subdirectories as well (mfc\FGMultiThreading,
mfc\Matching, mfc\MatchingExtWin, qt\Matching).
Your own C++ programs that use HALCON operators must include the file HalconCpp.h, which contains all
user-relevant definitions of the HALCON system and the declarations necessary for the C++ interface. Do this by
adding the following command near the top of your C++ file:
C++
#include "HalconCpp.h"
To specify the include path for the compiler on the command line, use the following syntax:
-I$HALCONROOT/include -I$HALCONROOT/include/halconcpp
To create an application, you have to link two libraries to your program: The library libhalconcpp.so contains
the various components of the HALCON/C++ interface. The library libhalcon.so is the HALCON library. To
specify the library path and the libraries for the linker, use the following syntax:
On some systems, you also have to link the libraries libdl.so and librt.so (by using the additional options
-ldl and -lrt, respectively).
HALCON XL applications:
Please note that you should use HALCON XL only when you need its features.
If you want to use HALCON XL, link the libraries libhalconcppxl.so and libhalconxl.so instead.
!
To link and run applications under Linux, ensure that the system variable LD_LIBRARY_PATH contains the HAL-
CON library path $HALCONROOT/lib/$HALCONARCH.
#include "HalconCpp.h"
#include <iostream>
std::cout << "Image - width: " << width.I() << ", height: " << height.I() << '\n';
return 0;
}
1. If required, download CMake (version 3.7.1 or later) from the CMake website and install it.
2. Create a build directory and then run cmake to configure the build and create the application:
mkdir build
cd build
cmake $HALCONEXAMPLES/cpp/console
cmake --build .
To configure, CMake needs to know the location of the HALCON installation, the location of the example
files, and which HALCON architecture to use:
• Specify the location of the HALCON installation via the HALCON_DIR CMake option, or via the
$HALCONROOT environment variable if the option is not set.
• Specify the location of the HALCON example files via the $HALCONEXAMPLES environment variable.
• Specify the HALCON architecture with the HALCON_ARCHITECTURE CMake option, or via the
$HALCONARCH environment variable. If neither the option nor the environment variable are set,
CMake will try to guess the architecture based on the host build system.
For general information on how to use CMake, see the CMake documentation.
HALCON XL applications: By default, the examples will be built using the normal version of HAL-
CON. If you want to build using HALCON XL, set the option HALCON_XL to ON or 1 in CMake during
configuration.
3. Optionally, you can use the -G option to specify the generator for a new build tree.
For more information about CMake generators, see the CMake documentation.
You can find corresponding CMakeLists.txt files in the other subdirectories as well (mfc/FGMultiThreading,
mfc/Matching, mfc/MatchingExtWin, motif/Matching, qt/Matching).
Typical Image Processing Problems 57
Chapter 8
C++
Typical Image Processing Problems
This chapter shows the power the HALCON system offers to find solutions for image processing problems. Some
typical problems are introduced together with sample solutions.
HImage Image("file_xyz");
HRegion Threshold = Image.Threshold(0,120);
HRegion ConnectedRegions = Threshold.Connection();
HRegion ResultingRegions =
ConnectedRegions.SelectShape("area","and",10,100000);
HImage Image("file_xyz");
HImage Sobel = Image.SobelAmp("sum_abs",3);
HRegion Max = Sobel.Threshold(30,255);
HRegion Edges = Max.Skeleton();
Some notes:
• Before applying the sobel operator it might be useful first to apply a low-pass filter to the image in order to
suppress noise.
• Besides the sobel operator you can also use filters like EdgesImage, PrewittAmp, RobinsonAmp,
KirschAmp, Roberts, BandpassImage, or Laplace.
• The threshold (in our case 30) must be selected appropriately depending on data.
• The resulting regions are thinned by a Skeleton operator. This leads to regions with a pixel width of 1.
58 Typical Image Processing Problems
HImage Image("file_xyz");
HImage Mean = Image.MeanImage(11,11);
HRegion Threshold = Image.DynThreshold(Mean,5,"light");
• The size of the filter mask (in our case 11 × 11) is correlated with the size of the objects which have to be
found in the image. In fact, the sizes are proportional.
• The dynamic threshold selects the pixels with a positive gray value difference of more than 5 (brighter) than
the local environment (mask 11 × 11).
Texture transformation is useful in order to obtain specific frequency bands in an image. Thus, a texture filter
detects specific structures in an image. In the following case this structure depends on the chosen filter; 16 are
available for the operator TextureLaws.
HImage Image("file_xyz");
HImage TT = Image.TextureLaws("ee",2,5);
HImage Mean = TT.MeanImage(71,71);
HRegion Reg = Mean.Threshold(30,255);
• The mean filter MeanImage is applied with a large mask size in order to smooth the “frequency” image.
• You can also apply several texture transformations and combine the results by using the operators AddImage
and MultImage.
The morphological operator Opening eliminates small objects and smoothes the contours of regions.
...
segmentation(Image,&Seg);
HRegion Circle(100,100,3.5);
HRegion Res = Seg.Opening(Circle);
• The term segmentation() is an arbitrary segmentation step that results in an array of regions (Seg).
• The size of the mask (in this case the radius is 3.5) determines the size of the resulting objects.
• You can choose an arbitrary mask shape.
Part III
Chapter 9
Introducing HALCON/.NET
This chapter introduces you to HALCON/.NET. Chapter 10 on page 63 shows how to use it to create .NET appli-
.NET
cations, chapter 12 on page 85 contains additional information.
What is HALCON/.NET?
HALCON/.NET is HALCON’s interface to .NET programming languages, e.g., C# or Visual Basic.NET. It pro-
vides you with a set of .NET classes and controls.
Platform Independence
HALCON/.NET is highly platform-independent: It is written in C# but can be used in any .NET language. Like
.NET in general, it can be used under Windows and Linux, on 32-bit and 64-bit systems. In addition, successful
experiments with the .NET Core implementation of HALCON/.NET were performed on Arm-based platforms.
Moreover, not only can you use it on all these platforms, but you can also run an application created on one of
them on the others without having to recompile it. This is possible because applications written in .NET languages
are stored in a platform-independent intermediate language (IL), which is then compiled by the so-called common
language runtime (CLR) into platform-specific code.
All .NET implementations listed above are supported. The interface for all of these implementations is the same
as well as their documented behavior. For users they mostly differ in terms of tooling and platform support. Most
of the relevant differences are documented in chapter 10 on page 63.
NuGet packages are provided for .NET Core, and assemblies for .NET Framework.
HDevEngine/.NET
By using the HDevEngine/.NET language bindings, you can execute HDevelop programs and procedures from a
.NET application. For more information, please refer to part VI on page 139.
This section demonstrates how to create a simple HALCON application with .NET Core. For a more comprehen-
sive description, see section 10.1 on page 63.
The task is to read an image and compute the number of connected regions in it, as illustrated in figure 9.1 on page
62
Figure 9.1: Left: Input image of a printed circuit board. Middle: Regions found by threshold, colored red. Right:
Connected regions, a result of connection.
using HalconDotNet;
namespace region_example
{
class Program
{
static void Main(string[] args)
{
HImage img = new HImage("pcb");
5. To run the application, type the following command in the same shell:
dotnet run
As a result, you should see the following output ’Number of Regions: 43’.
Creating Applications With HALCON/.NET 63
Chapter 10
.NET
10.1 Creating Applications With HALCON/.NET
For .NET Framework, the examples are given in C#, using Visual Studio under Windows as development environ-
ment. If programming constructs or activities differ in Visual Basic.NET or managed C++, this is noted at the first
occurrence.
For .NET Core, the examples are given in C# using the .NET Core SDK, usable on both Windows and Linux.
At the moment we do not officially support using the .NET Core interface with other languages, C# has been our
focus for testing and documentation.
How to create applications under Linux using Mono is described in section 12.2 on page 87. Many of the code ex-
amples stem from the example Matching, which is provided in C# (%HALCONEXAMPLES%\c#), Visual Basic.NET
(%HALCONEXAMPLES%\vb.net), and managed C++(%HALCONEXAMPLES%\cpp.net). An overview of the provided
example applications can be found in section 12.1 on page 85.
But before explaining how to create applications, we must take a brief look under the hood of .NET, particularly
at the dependency of applications on the .NET Framework.
To leverage the cross-platform nature of .NET Core, the interface is offered in two package variants. Both of them
contain the complete HALCON/.NET and HDevEngine/.NET language bindings.
MVTec.HalconDotNet
This package targets .NET Standard 2.0 and can be used on all architectures supported by HALCON.
MVTec.HalconDotNet-Windows
This package targets .NET Core 3.1 and additionally includes Windows Forms and WPF controls for integrating
HALCON windows into GUI applications. This package can only be used on Windows since other .NET Core 3.1
implementations do not offer Windows Forms or WPF support.
While NuGet uses SemVer to version packages, HALCON versions are not SemVer compatible. To avoid unnec-
essary conflicts, .NET Core packages receive a SemVer-compatible version by combining the major, minor, and
revision into a new version, e.g.:
HALCON/.NET is not a self-contained package but an interface to the native HALCON library. Therefore, the
package version used by your project has to match the installed HALCON version exactly.
Even for maintenance releases, which are backwards compatible at application level, mixing of binaries from
different releases is not recommended because the internal communication between HALCON/.NET and the native
HALCON library is not guaranteed to be always compatible. Therefore, the revision of the HALCON release is
also part of the SemVer major version. The SemVer minor and patch version are reserved for fully backwards-
compatible intermediate releases of the package itself. See section 10.5.0.3 on page 67 for updating dependencies.
To use the packages offline, download them from the NuGet website. Consider adding a nuget.config file to
your project. This helps to source it reliably from a file system.
10.3 Adding HALCON/.NET to an Application 65
When developing an application with HALCON XL, select the following XL packages:
• MVTec.HalconDotNetXL
• MVTec.HalconDotNetXL-Windows
For upgrading HALCON/.NET in relation to a HALCON upgrade, see section 10.5.0.3 on page 67.
.NET
the matching package version for your installed HALCON version.
The previous section describes, how to create a console application. To create a WPF Application in Visual Studio,
that uses a HALCON window for visualization, follow these steps:
1. Use the common Visual Studio mechanism for creating a WPF application.
2. Add a package reference as described in the previous section. The needed package is MVTec.HalconDotNet-
Windows.
3. Edit the XAML file.
After this change, the XAML file should look something like this:
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:ha="http://schemas.mvtec.com/halcondotnet"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="513" Width="862">
<Grid Margin="0,0,-433,-146">
<Button Content="Button" HorizontalAlignment="Left" Height="5"
Margin="178,121,0,0" VerticalAlignment="Top" Width="7"/>
<Button Name="MyButton" Content="My Button

"
HorizontalAlignment="Left" Height="84" Margin="156,121,0,0"
VerticalAlignment="Top" Width="151" Click="Button_Click"/>
<ha:HSmartWindowControlWPF Name="MyControl" Margin="399,55,313,55" />
</Grid>
</Window>
66 Creating Applications With HALCON/.NET
The HALCON/.NET assembly provides not only a class library but also one control: HSmartWindowControl (or
HSmartWindowControlWPF), which contains a HALCON graphics window for visualizing images and results.
The older control HWindowControl is still available for backwards compatibility but it is strongly advised against
using this control for new projects (see section 11.6 on page 81 for information about the differences).
You can add these controls to Visual Studio’s toolbox by performing the following steps. Note that the exact menu
names slightly differ in different versions of Visual Studio:
1. Right-click the toolbox and select Choose Items (Customize Toolbox in previous versions of Visual
Studio). This will open a dialog displaying all available .NET Framework components in a tab.
2. Click Browse, navigate to the directory %HALCONROOT%\bin\dotnet20 or %HALCONROOT%\bin\
dotnet35 and select halcondotnet.dll.
3. The icon of HSmartWindowControl and the older HWindowControl appear in the toolbox.
HALCON XL applications:
! Please note that you should use HALCON XL only when you need its features.
When developing an application with HALCON XL, select halcondotnetxl.dll instead of
halcondotnet.dll. In the toolbox, the control appears with the same name but with a different icon.
You can add both HALCON versions to the toolbox but only one of them to an application.
In many applications, you will use at least one instance of HSmartWindowControl to visualize results. By adding
the control to the form (as described in section 11.7 on page 82), you automatically create a reference to the
assembly halcondotnet.dll.
If you do not want to use HSmartWindowControl, add a reference as follows:
1. Right-click References in the Solution Explorer and select Add Reference.
2. Click Browse, navigate to the subdirectory %HALCONROOT%\bin\dotnet20 or %HALCONROOT%\bin\
dotnet35 and select the assembly halcondotnet.dll.
HALCON XL applications:
! Please note that you should use HALCON XL only when you need its features.
When developing an application with HALCON XL, select halcondotnetxl.dll instead of
halcondotnet.dll. If you already added a reference to the HALCON version, simply delete this refer-
ence and add one to halcondotnetxl.dll.
.NET Core projects resolve a specific version the moment you add the package. If you want to update to a newer
HALCON version, for example from 24.05. to 24.11.1, you must change the version specified in your project.
Note that 20.11.2 is a breaking change compared to 20.11.1, which can also be seen in the HALCON SemVer
major version change from 20111 to 20112.
For example from 24.05. to 24.11.1, change your project .csproj from:
to:
.NET
10.5.0.4 .NET Framework
halcondotnet.dll is not a self-contained library but an interface to the native HALCON library. Therefore, the
library version used by your project has to match the installed HALCON version exactly.
Even for maintenance releases, which are backwards compatible at application level, mixing of binaries from
different releases is not recommended because the internal communication between HALCON/.NET and the native
HALCON library is not guaranteed to be always compatible.
Applications that use HALCON/.NET have local copies of the corresponding assemblies. After installing a newer
release of HALCON, these applications would therefore still use their old HALCON assemblies. To use the new
halcondotnet.dll re-build your project, Visual Studio-> Solution -> Rebuild Solution.
If you want to replace the halcondotnet.dll without recompiling the application, you need to both manually
replace the halcondotnet.dll with the newly installed one, and update the application’s app.config, to in-
form the executable of the new halcondotnet.dll. Do this by copying either bin\dotnet20\app.config
or bin\dotnet35\app.config into the directory containing the halcondotnet.dll, and rename it to
<application_name>.exe.config.
68 Creating Applications With HALCON/.NET
HALCON/.NET Interface 69
Chapter 11
HALCON/.NET Interface
.NET
To be able to use the HALCON/.NET classes without prefixing them with their namespace, we recommend that
you specify this namespace at the beginning of each source file (for example, see the example MatchingForm.cs)
by adding the following line:
using HalconDotNet;
Visual Basic.NET applications: The corresponding Visual Basic.NET code is (for example, see
MatchingForm.vb):
Imports HalconDotNet
window = windowControl.HalconWindow;
framegrabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0, "default",
-1, "default", -1, "default",
"board/board.seq", "default", 1, -1);
img = framegrabber.GrabImage();
img.GetImagePointer1(out ImgType, out imgWidth, out imgHeight);
window.SetPart(0, 0, imgHeight - 1, imgWidth - 1);
img.DispObj(window);
The operator GrabImage is called via an instance of HFramegrabber. As an experienced HALCON user you will
perhaps have identified the constructor of HFramegrabber as a call to the operator OpenFramegrabber.
Below, we take a closer look at:
• how to call operators via HALCON/.NET’s classes (section 11.1.2 on page 70)
• construction, initialization, and destruction of class instances (section 11.1.3 on page 71)
• overloads of operator calls (section 11.1.4 on page 73)
But first, we give you an overview of the provided online help.
70 HALCON/.NET Interface
The main source of information about HALCON/.NET operators and classes is the reference manual, which
is available as HTML and PDF version (note that the latter is only provided in HDevelop syntax). Un-
der Windows, you can open both versions via the Start Menu. Under Linux, open index.html in the di-
rectory $HALCONROOT/doc/html/reference/operators, and reference_hdevelop.pdf in the directory
$HALCONROOT/doc/pdf/reference, respectively. You can access them also via HDevelop’s Help Browser.
The Reference Manual describes the functionality of each HALCON operator and its signatures, i.e., via which
classes it can be called with which parameters. Furthermore, it gives an overview of the provided classes (which
does not list all methods, however, only the HALCON operators).
Online help is also available in Visual Studio:
• When you type a dot (.) after the name of a class or class instance, the automatic context help (IntelliSense)
lists all available methods.
• Similarly, when you type the name of a method, its signature(s) is (are) listed.
• For parameters of HALCON operators, a short description and the so-called default value is shown. Note that
HALCON operators do not have “real” default parameter values, i.e., you cannot leave out a parameter and
let HALCON use a default value. Instead, the listed default value is a typical value chosen for the parameter.
• The Object Browser lists all HALCON/.NET classes with their methods, including a short description.
Via which classes you can call a HALCON operator is listed in the reference manual. Figure 11.1 on page 70
shows the corresponding part of the description of the operator GrabImage:
Figure 11.1: The head and parts of the parameter section of the reference manual entry for GrabImage.
As you can see, the operator can be called via three classes: HOperatorSet, HImage, and HFramegrabber. The
first variant, via HOperatorSet, is mainly used for the export of HDevelop programs (see section 12.3 on page
88).
For normal applications, we recommend calling operators via the other classes, in the example HImage and
HFramegrabber as in the following code example:
HImage Image1;
HImage Image4 = new HImage();
HFramegrabber Framegrabber = new HFramegrabber("File", 1, 1, 0, 0, 0, 0, "default", -1,
"default", -1, "default", "board/board.seq", "default", -1, -1);
Image1 = Framegrabber.GrabImage();
HImage Image3 = null;
Note that in the call via HFramegrabber the grabbed image is the return value of the method, whereas the call via
HImage has no return value and the calling class instance is modified instead. Usually, calling class instances are
not modified by an operator call - with the exception of “constructor-like” operator calls as in the example above.
Some operators like CountSeconds are available as class methods, i.e., you can call them directly via the class
and do not need an instance:
11.1 Using HALCON/.NET Classes 71
s1 = HSystem.CountSeconds();
In the reference manual, these operator calls start with the keyword static:
Figure 11.2: The head of the reference manual entry for CountSeconds.
.NET
During the lifecycle of an object, i.e., from declaration to finalization, different amounts of memory are allocated
and released.
The following declaration just declares a variable of the class HImage that does not yet refer to any object:
HImage Image1;
In this state, you cannot use the variable to call operators; depending on the programming language, you might not
even be able to use it as an output parameter (e.g., in Visual Basic 2005). However, you can assign image objects
to the variable, e.g., from the return value of an operator:
Image1 = Framegrabber.GrabImage();
Note that you can check the initialization state of a class instance with the method IsInitialized.
11.1.3.1 Constructors
In contrast, the following declaration calls the “empty” constructor of the class HImage, which creates an unititial-
ized class instance:
This class instance can be used to call “constructor-like” operators like GrabImage, which initializes it with a
grabbed image:
Image4.GrabImage(Framegrabber);
Besides the empty constructor, most HALCON/.NET classes provide one or more constructors that initialize the
created object based on HALCON operators. For example, HImage provides a constructor based on the operator
ReadImage:
You can check which constructors are provided via the online help:
72 HALCON/.NET Interface
• The reference manual pages for the classes don’t list the constructors themselves but the operators they are
based on. The constructor then has the same signature as the operator (minus the output parameter that
corresponds to the class, of course).
• The online help in Visual Studio lists the constructors but not the operators they are based on.
11.1.3.2 Finalizers
The main idea behind memory management in .NET is that the programmer does not worry about it and lets the
garbage collector delete all objects that are not used anymore. HALCON/.NET fully complies to this philosophy
by providing corresponding finalizers for all classes so that even unmanaged resources, e.g., a connection to an
image acquisition device, are deleted correctly and automatically.
For most classes, the finalizer automatically calls suitable operators like CloseFramegrabber to free resources.
Which operator is called is listed in the reference manual page of a class (for example, see the entry for
HFramegrabber). This operator cannot be called via the class, as can be seen in the corresponding reference
manual entry:
Figure 11.3: The head of the reference manual entry for CloseFramegrabber.
You do not even need to call such an operator if you, e.g., want to re-open the connection with different parameters,
because this is done automatically.
! Do not call Close or Clear operators via HOperatorSet when using the normal classes like HFramegrabber.
As remarked above, the .NET philosophy is to let the garbage collector remove unused objects. However, because
the garbage collector deletes unused objects only from time to time, the used memory increases in the meantime.
Even more important is that, to the garbage collector, HALCON’s iconic variables (images, regions, ...) seem to
be rather “small”, because they only contain a reference to the (in many cases rather large) iconic objects in the
database. Thus, the garbage collector may not free such variables even if they are not used anymore.
Therefore, you might need to force the removal of (unused) objects. There are two ways to do this:
• Call the garbage collector manually. In the example Matching, this is done after each processing run in the
timer event:
private void Timer_Tick(object sender, System.EventArgs e)
{
Action();
GC.Collect();
GC.WaitForPendingFinalizers();
}
Besides reducing memory consumption, another reason to manually dispose of objects is to free resources, e.g.,
close a connection to an image acquisition device or a serial interface.
HTuple instances that contain handles also need to be disposed if the referenced resource is to be released in a
deterministic way.
11.1 Using HALCON/.NET Classes 73
Please note that HALCON operators always create a new object instance for output parameters and return values
(but not in the “constructor-like” operator calls that modify the calling instance). If the variable was already
initialized, its old content (and the memory allocated for it) still exists until the garbage collector removes it. If
you want to remove it manually, you must call Dispose before assigning an object to it.
Some classes overload standard operators like + (addition) to call HALCON operators. The following line, e.g.,
adds two images by internally calling AddImage:
.NET
- (unary) inverts an image
+ (image) adds two images
- (image) subtracts image2 from image1
∗ (image) multiplies two images
+ (scalar) adds a constant gray value offset
- (scalar) subtracts a constant gray value offset
∗ (scalar) scales an image by the specified factor
/ (scalar) scales an image by the specified divisor
>= (image) segments an image using dynamic threshold
<= (image) segments an image using dynamic threshold
>= (scalar) segments an image using constant threshold
<= (scalar) segments an image using constant threshold
& (region) reduces the domain of an image
A strength of HALCON is that most operators automatically work with multiple input values (tuple values). For
example, you can call the operator AreaCenter with a single or with multiple input regions; the operator automat-
ically returns the area and center coordinates of all passed regions. Analogously, if you call GenRectangle1 with
multiple values for the rectangle coordinates, it creates multiple regions.
The following sections provide more detailed information about
• how to find out whether an operator can be called in tuple mode (section 11.2.1 on page 74)
• tuples of iconic objects (section 11.2.2 on page 75)
• tuple of control values (section 11.2.3 on page 75)
You can check whether an operator also works with tuples in the reference manual. Below, e.g., we show the
relevant parts of the operators AreaCenter and GenRectangle1.
As you see, the iconic classes like HRegion automatically handle multiple values; whether such a parameter accepts
/ returns multiple values is not visible from the signature but only in the parameter section: Here, an appended
(-array) (in the example: HRegion(-array)) signals that the parameter can contain a single or multiple values.
static void HOperatorSet.AreaCenter (HObject regions, out HTuple area, out HTuple row,
out HTuple column)
HTuple HRegion.AreaCenter (out HTuple row, out HTuple column)
int HRegion.AreaCenter (out double row, out double column)
static void HOperatorSet.GenRectangle1 (out HObject rectangle, HTuple row1, HTuple column1,
HTuple row2, HTuple column2)
public HRegion (HTuple row1, HTuple column1, HTuple row2, HTuple column2)
public HRegion (double row1, double column1, double row2, double column2)
void HRegion.GenRectangle1 (HTuple row1, HTuple column1, HTuple row2, HTuple column2)
void HRegion.GenRectangle1 (double row1, double column1, double row2, double column2)
Parameter Broadcasting
rectangle (output_object) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegion
row1 (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; HTuple (double / int / long)
column1 (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; HTuple (double / int / long)
row2 (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; HTuple (double / int / long)
column2 (input_control) . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; HTuple (double / int / long)
In contrast, control parameters show by their data type whether they contain a single or multiple values: In the first
case, they use basic data types like double, in the second case the HALCON/.NET class HTuple. Thus, you can
call GenRectangle1 via HRegion in two ways, either by passing doubles or HTuples (here using the constructor
form):
11.2 Working With Tuples 75
Below, we provide additional information about iconic tuples (section 11.2.2 on page 75) and control tuples (sec-
tion 11.2.3 on page 75).
.NET
The iconic classes HImage, HRegion, and HXLD can contain single or multiple objects. To process all elements of
a tuple you first query the number of elements with the operator CountObj
and then access elements either with the HALCON operator SelectObj or (when using C#) with the operator []:
For control tuples, HALCON/.NET provides the class HTuple. Instances of HTuple can contain elements of the
types double, int, string, and HHandle. They can also contain a mixture of element types.
The following sections describe
• how to access tuple elements (section 11.2.3.1 on page 75)
• how to create tuples (section 11.2.3.2 on page 76)
• the automatic cast methods and how to resolve ambiguities caused by the casts (section 11.2.3.3 on page 76)
• HALCON operators for processing tuples (section 11.2.3.4 on page 77)
• proved overloads for arithmetic operations (section 11.2.3.5 on page 78)
To process all elements of a tuple, you first query its length via the property Length:
Note that you get an exception if you try to read a non-existing tuple element or if you try to assign an element to
a variable with a different type without cast.
The class HTuple provides many different constructors (see the Visual Studio’s Object Browser for a list). The
following line creates an int tuple with a single value:
You can also pass multiple values to a constructor. Note that when mixing double and int values as in the
following line, a double tuple is created:
In contrast, when the list of values also contains a string, a mixed type tuple is created, in which the second
value is stored as an int:
The type of a tuple or of a tuple element can be queried via its property Type:
You can also append elements to a tuple by writing into a non-existing element:
Tuple3[2] = 3;
The class HTuple provides many implicit cast methods so that you can intuitively use the basic data types in most
places. For example, the line
automatically casts the element, which is in fact an instance of the class HTupleElement, into a double.
Similarly, basic types are automatically casted into instances of HTuple. The drawback of the casts is that the
compiler often cannot decide whether you want to use the simple or the tuple version of an operator and issues
11.2 Working With Tuples 77
a corresponding error. For example, if you used the following line, the values can either be casted from int to
double or to HTuple:
You can resolve the ambiguity very simply by appending .0 to the first parameter:
The example Matching contains two other cases of ambiguities, both arising because basic-type and HTuple
parameters are mixed in the same call. In the first, the ambiguity is solved by explicitly casting the double
parameters into instances of HTuple:
.NET
result.GetGenericShapeModelResult(0, "row"),
result.GetGenericShapeModelResult(0, "column"),
angleCheck);
In the second case, the instances of HTuple (which only contain single values) are explicitly casted into doubles
by using the property D, which returns the value of the first element as a double (actually, it is a shortcut for
tuple[0].D):
With similar properties, you can cast tuple elements into the other basic types. Note, however, that you get an
exception if you try to cast an element into a “wrong” type.
In contrast to input parameters, output parameters are not automatically casted. Sometimes, this leads to unex-
pected results. In the following code, e.g., doubles are used for the output parameters and the return value in a
call to AreaCenter with a tuple of regions:
Consequently, only the area and the center of the first region are returned. The same happens if you assign the
return value to an HTuple, but still pass doubles for the output parameters:
In contrast, if you pass HTuples for the output parameters and assign the return value to a double, the operator
returns the center coordinates of all regions but only the area of the first region:
HALCON provides many operators for processing tuples. In the reference manual, these operators can be found
in the chapter “Tuple”. An overview of these operators is given in the HDevelopUser’s Guide in chapter 8 on page
78 HALCON/.NET Interface
247. Note that instead of the operator name, the name of the corresponding HDevelop function is used, which
omits the Tuple and uses lowercase characters, e.g., rad instead of TupleRad.
For the basic arithmetic operations, HALCON/.NET provides operator overloads. For example, the operator +
automatically calls the HALCON operator TupleAdd.
In the following some basic information about the use of vectors in HALCON/.NET is given when using C#.
Construction of Vectors
As already mentioned, an instance of a vector can only be created from HObjectVector or HTupleVector.
The vector type cannot be changed after its construction. Thus, a tuple cannot be assigned to a vector of iconic
objects and vice versa.
You may also create a multi-dimensional vector, i.e., a vector of vectors and so on, by specifying the number of
dimensions in brackets. However, the dimension of a vector has to remain constant within the program and cannot
be changed. The following code line describes how to create a vector of two dimensions, i.e., a vector of vectors
of tuples.
Note that the vectors created by these calls are still empty. How to access and set vector elements is described
below.
The specified index in square brackets defines the element to be accessed. If a subelement of a multi-dimensional
vector is to be accessed, you have to use the indices of the corresponding subvector and its subelement instead.
When setting a vector element the expression for accessing a vector element is needed as reference to the HObject
or HTuple, respectively. The value to be set must be specified on the right side of the assignment.
In the example code the image is copied and set as the first element of vectorObj. The tuple is also copied but set
.NET
as the second vector element of vectorTup.
Setting a subelement of a multi-dimensional vector can be done analogously to setting an element in a one-
dimensional vector when using the corresponding indices of the subvector(s) and its subelement.
If a non-existing vector element is set or accessed, the vector is automatically enlarged and filled with empty
elements if necessary.
Destruction of Vectors
If a HObjectVector or HTupleVector is not needed anymore for further processing its contents should be cleared
with .Dispose().
vectorObj.Dispose();
Additional Information
In addition to accessing and setting the elements of vectors, HObjectVector and HTupleVector provide further
functionalities for the use of HALCON vectors such as inserting and removing vector elements or concatenation
of vectors. For more details on the provided vector functionality you may use the automatic context help in Visual
Studio, IntelliSense.
The .NET programming languages each offer a mechanism for error handling. In C# and managed C++, you use
try...catch blocks. Within this standard mechanism, HALCON/.NET offers its special exceptions:
• HOperatorException is raised when an error occurs within a HALCON operator.
• HTupleAccessException is raised when an error occurs upon accessing a HALCON tuple.
The following code shows how to catch the error that occurs when the operator ReadImage is called with a wrong
image file name. Then, a message box is shown that displays the error code in the caption and the HALCON error
message:
80 HALCON/.NET Interface
HImage Image;
try
{
Image = new HImage("unknown");
}
catch (HOperatorException exception)
{
MessageBox.Show(exception.Message, "HALCON error # " + exception.GetErrorCode());
}
All HALCON error codes and their corresponding error messages are summarized in the Extension Package Pro-
grammer’s Manual, appendix A on page 105.
The HSmartWindowControl and HSmartWindowControlWPF provide the event HErrorNotify. This event al-
lows the user to react to errors that take place internally within the control, but can have external causes, like for
example an unplugged dongle or a missing license file.
11.5 Visualization
Applications can use an instance of HSmartWindowControl to display results. However, this is only available for
.NET Framework and the MVTec.HalconDotNet-Windows .NET Core packages. How to configure this control
is described in section 11.7 on page 82. The actual display operators, however, do not use the control but the
HALCON graphics window (class HWindow) encapsulated inside. You can access the graphics window via the
property HalconWindow of HSmartWindowControl:
In the code above, the variable for the instance of HWindow was declared globally and initialized in the event Load
of the form.
You can configure the display parameters like pen color or line width with the operators in the reference manual
chapter “Graphics . Parameters”:
window.SetDraw("margin");
window.SetLineWidth(3);
Images and other iconic objects are displayed with the operator DispObj, which can be called via the object to
display with the window as parameter or vice versa:
img.DispObj(window);
More display operators, e.g., to display lines or circles, can be found in the reference manual chapter “Graphics .
Output”.
Instead of (or in addition to) using HSmartWindowControl, you can also open a HALCON graphics windows
directly with the operator OpenWindow:
In the code above, the window was opened “free-floating” on the display. You can also open it within another GUI
element by passing its handle in the parameter fatherWindow.
Before displaying anything in the graphics window, you should set the image part to display with the operator
SetPart. In the example code below, the opened window is used to display a zoomed part of the image:
11.6 Window Controls for Visualization 81
More information about visualization in general can be found in the Solution Guide I, chapter 21 on page 223.
Note that in this manual, the HDevelop version of the display operators is used, i.e., with the prefix dev_, e.g.,
dev_open_window instead of OpenWindow.
.NET
• HSmartWindowControl (Windows Forms), and
• HSmartWindowControlWPF (WPF).
See section 12.2.4 on page 88 for information about other GUI libraries.
The smart window control provides several advantages over HWindowControl:
• It is used like any other control (e.g., it can be embedded in TabControls or ScrollViewers, or overlaid
with other controls).
• Predefined mouse interaction is provided (moving of the window contents and zooming using the mouse
wheel). The view can be reset by double-clicking the window.
• The control automatically rescales without flickering.
In addition, you need to transform the mouse coordinates, so that they are relative to the upper left corner of the
HSmartWindowControl.
Using the smart window control, the following events are triggered and can be reacted to:
• Click
• GotFocus, LostFocus
• MouseEnter, MouseLeave, MouseHover
• Resize, SizeChanged
• KeyDown, KeyUp, KeyPress
Not all operators can be used with the smart window control. The following operators are not supported:
82 HALCON/.NET Interface
In most applications you want to visualize at least some results. Then, you start by adding HSmartWindowControl
to the form by double-clicking the corresponding icon in the toolbar. An empty (black) window appears (see
figure 11.4 on page 82).
HALCON XL applications:
! Please note that you should use HALCON XL only when you need its features.
If you already added the HALCON version of the control, but now want to use HALCON XL, simply delete the
reference to halcondotnet.dll in the Solution Explorer and add a reference to halcondotnetxl.dll instead.
If you want to fit an image automatically without the need to double click, you can use the operator SetPart to
adjust the part to the size of the last image displayed:
img.DispObj(window);
The properties specific to this control are listed below in alphabetical order. They can be adapted in the Properties
window (see figure 11.4 on page 82). Note that some properties are only available for HSmartWindowControlWPF
elements. All properties of the HSmartWindowControlWPF support data binding.
Do not modify the “Brush” properties in Visual Studio. They are disabled for HSmartWindowControlWPF to
prevent undesired side-effects.
HColor
Specifies the color of HRegion and HXLDCont objects.
11.7 Customizing HSmartWindowControl for the Visualization 83
HColored
Specifies the colors for displaying multiple HRegion or HXLDCont objects in different colors.
HDisableAutoResize
If set to true, images are not automatically scaled when they are displayed.
HDisplayCurrentObject
Displays the assigned HImage or HObject.
HDoubleClickToFitContent
If set to true (the default), double clicking resizes the content of the HSmartWindowControl to fit the size
of the control. If the HKeepAspectRatio is also set to true, the contents are rescaled so that the aspect ratio
is maintained.
HDraw
Specifies the fill mode of HRegion objects. If HDraw is set to ’fill’, output regions are filled, if set to
’margin’, only contours are displayed.
HDrawingObjectsModifier
.NET
Specifies the modifier key to interact with drawing objects. If a modifier key is set, the user can only interact
with drawing objects while keeping the modifier key pressed. This is especially useful when interacting with
XLD drawing objects. By default, it is set to None. Other possible values are Alt, Ctrl, or Shift.
HFont
Specifies the font for displaying messages in the HSmartWindowControlWPF.
HImagePart
Specifies the image part of the corresponding HALCON window. Note that the part is specified with the
values X, Y, Width, and Height, whereas the corresponding operator SetPart expects the four corner
points. Note that you can modify the displayed part in your application at any time, e.g., to display a zoomed
part of the image. See section 11.5 on page 80 for more information about actually visualizing results.
HKeepAspectRatio
If set to true (the default), the content of the HSmartWindowControl keeps its aspect ratio when the control
is resized or zoomed. The aspect ratio is the quotient Width/Height set at design time with HImagePart.
HLineStyle
Specifies the contour pattern of HRegion and HXLDCont objects.
HLineWidth
Specifies the contour thickness of HRegion and HXLDCont objects.
HMoveContent
If set to true (the default), the contents of the HALCON window can be dragged using the mouse.
HZoomContent
Specifies the behavior of the mouse wheel. If set to WheelForwardZoomsIn (the default), the contents
of the HALCON window is zoomed in and out when moving the mouse wheel forwards and backwards,
respectively. Setting the property to WheelBackwardZoomsIn reverses the behavior. If set to Off, zooming
using the mouse wheel is disabled.
HZoomFactor
Specifies the step size when zooming with the mouse wheel. The default is 1.41. Values must be greater
than 1 and less or equal to 100. A higher value leads to faster zooming.
The HSmartWindowControlWPF can be used to implement the Model-View-Viewmodel (MVVM) pattern, as all
properties of the control support data binding. By adding objects to the Items collection or setting the ItemsSource
property you can specify what the control should display, also in pure XAML code. The following example
illustrates how to show an image, color a region in “magenta”, and display a text message:
84 HALCON/.NET Interface
<ha:HSmartWindowControlWPF HDraw="fill">
<!--Iconic items can be added using HIconicDisplayObjectWPFs-->
<ha:HIconicDisplayObjectWPF IconicObject="{Binding DisplayImage}"/>
<!--Also with individual drawing properties-->
<ha:HIconicDisplayObjectWPF IconicObject="{Binding DisplayRegion}"
HDraw="margin" HColor="magenta"/>
<!--Messages can be displayed using HMessageDisplayObjectWPFs-->
<ha:HMessageDisplayObjectWPF HMessageText="{Binding ImageName}"/>
</ha:HSmartWindowControlWPF>
Note that DisplayImage, DisplayRegion and ImageName have to exist in the DataContext of the
HSmartWindowControlWPF.
Additional Information 85
Chapter 12
Additional Information
This chapter provides additional information for developing applications with HALCON/.NET:
.NET
• Section 12.1 on page 85 gives an overview of the available example applications.
• Section 12.2 on page 87 explains how to use HALCON/.NET applications under Linux using Mono.
• Section 12.3 on page 88 shows how to use HDevelop programs or procedures in your .NET application.
• Section 12.4 on page 89 contains information to keep in mind if your environment allows remote access.
The following sections briefly describe the provided example applications for
• C# (section 12.1.1 on page 85)
• Visual Basic.NET (section 12.1.2 on page 86)
• (managed) C++ (section 12.1.3 on page 86)
All paths are relative to %HALCONEXAMPLES%.
12.1.1 C#
12.1.3 C++
Chapter 10 on page 63 describes in detail how to develop HALCON/.NET applications in general. If you want to
create applications under Linux using Mono, see the following sections for additional information:
• restrictions (section 12.2.1 on page 87)
• how to deploy applications created under Windows (section 12.2.2 on page 87)
• how to compile an application with Mono (section 12.2.3 on page 87)
• other GUI libraries (section 12.2.4 on page 88)
If you want to target Linux and do not need Windows Forms, consider using .NET Core.
12.2.1 Restrictions
Please note the following restrictions when developing or using HALCON/.NET applications via Mono:
.NET
• Mono only supports Windows Forms 2.0.
• HWindowControl is not yet initialized in the event Load of a form, due to a different initializa-
tion order of X Window widgets. Please place initialization and similar code in the event handler of
HSmartWindowControl’s (or HWindowControl’s) event HInitWindow.
private void hWindowControl1_HInitWindow(object sender, System.EventArgs e)
{
window = hWindowControl1.HalconWindow;
window.SetDraw("margin");
window.SetColor("cyan");
}
Because of HALCON/.NET’s platform independence, you can copy an application created under Windows to a
Linux computer and simply start it there – provided that Mono and HALCON are installed on the destination
computer (see section 10.4 on page 66 for more information).
Most of the HALCON/.NET examples provide a set of makefiles in the subdirectory makefiles to let you com-
pile them under Linux (see section 12.1 on page 85 for a list of the examples that support Linux). To start the
compilation, simply type
gmake
gmake XL=1
In some cases, Mono may not find the native HALCON library libhalcon.so, which should be resolved via the
environment variable LD_LIBRARY_PATH and issue a corresponding error. You can create configuration files for
the HALCON/.NET (and HDevEngine/.NET) assembly that explicitly specify the path to the HALCON library
(see figure 12.1 on page 88 for an example) by calling
88 Additional Information
<configuration>
<dllmap dll="halcon"
target="/opt/halcon/lib/x64-linux/libhalcon.so"/>
</configuration>
Figure 12.1: Example for a configuration file with HALCON being installed in the directory /opt/halcon.
gmake config
If you want to create a configuration file for only one of the assemblies, use the make commands config_halcon
and config_engine.
Note that you can also use xbuild (Mono’s implementation of msbuild) with the project files.
In principle, you can also use other GUI libraries instead of Windows Forms or WPF, e.g., Gtk#. However,
HSmartWindowControl or HSmartWindowControlWPF are Windows Forms or WPF elements, respectively,
and thus can no longer be used. Instead, you can open HALCON graphics windows directly with the operator
OpenWindow. If you want to place a graphics window inside another element, pass the element’s native window
handle in the parameter fatherWindow.
Note that HALCON/.NET has not been tested with other GUI libraries.
In most cases, you will manually integrate the exported code into your application. To quickly test the exported
code, you can integrate it into the so-called template project (available for C# and Visual Basic.NET) in the subdi-
rectory HDevelopTemplate (or HDevelopTemplateWPF, depending on your preferred GUI platform) as follows:
1. Move or copy the exported source code file into subdirectory source of the template application.
2. Open the solution file, right-click the current project in the Solution Explorer, and select the menu item
Add Existing Item. Navigate to the source code file and select Add As Link, which is accessed via
the arrow on the right side of the Add button (see figure 12.2 on page 88).
3. When you run the application, the form depicted in figure 12.3 on page 89 appears. Click Run to start the
exported HDevelop program.
4. If you did not add the exported code correctly, the error message depicted in figure 12.4 on page 89 appears.
In Visual Basic.NET, different error messages appear.
12.4 HALCON/.NET and Remote Access 89
.NET
Figure 12.3: The template form for exported code.
Figure 12.4: Error message upon running a template without exported code.
The exported code does not use the classes like HImage described in the previous chapter. Instead, all operators
are called via the special class HOperatorSet. Iconic parameters are passed via the class HObject (which is the
base class of HImage, HRegion, and HXLD), control parameters via the class HTuple.
You can combine the exported code easily with “normal” HALCON/.NET code because iconic classes provide
constructors that initialize them with instances of HObject. Furthermore, iconic classes can be passed to methods
that expect an HObject.
For performance reasons, HALCON/.NET suppresses unmanaged code security when making calls into the native
HALCON library. Should your machine vision application run in an environment that allows remote access, you
might wish to explicitly check permissions for code calling within your application or library.
90 Additional Information
Part IV
Chapter 13
Introducing HALCON/Python
This chapter introduces you to HALCON/Python. Chapter 14 on page 95 shows how to use it to create Python
applications, chapter 15 on page 97 contains detailed information.
What is HALCON/Python?
HALCON/Python is a set of native Python language bindings for HALCON. This includes interfaces for operators,
HDevEngine and interoperability for third-party libraries like NumPy.
The major design goals for HALCON/Python are simplicity and rapid prototyping.
Python
Platform Independence
HALCON/Python is officially supported for CPython, the reference implementation of the Python programming
language. We test the interface on x64-win64and x64-linux. In addition, successful experiments were performed
on ARM with CPython.
Other Python implementations should work as long as they are appropriate implementations of the Python standard.
What’s more, not only can you use it on all these platforms, but you can run an application created on one of
them on the other ones without having to recompile it. This is possible because applications written in Python are
interpreted at runtime, instead of being compiled ahead of time.
HDevEngine/Python
By using the HDevEngine/Python language bindings, you can execute HDevelop programs and procedures from a
Python application. For more information, please refer to part VI on page 139.
Figure 13.1: Left: Input image of a printed circuit board. Middle: Regions found by threshold, colored red. Right:
Connected regions, a result of connection.
if __name__ == '__main__':
img = ha.read_image('pcb')
6. To run the application, type the following command in the same shell:
python program.py
As a result, you should see the following output ’Number of Regions: 43’.
Creating Applications With HALCON/Python 95
Chapter 14
Python
1. x64-win64
2. x64-linux
Newer Python versions should work without problems. It is possible that other platforms and alternative Python
implementations are functional, of course native HALCON binaries also need to be available on that platform.
While PEP 440 and by extension PyPI does not require SemVer, HALCON/Python and other language interface
packages follow a SemVer approach to avoid unnecessary conflicts and tooling issues. However, HALCON ver-
sions are not SemVer compatible, so Python packages receive a SemVer-compatible version by combining the
major, minor, and revision into a new version, e.g.:
• 22.11.1 → 22111.0.0
• 24.05.0 → 24050.0.0
• 24.11.1 → 24111.0.0
HALCON/Python is not a self-contained package but an interface to the native HALCON library. Therefore, the
package version used by your project has to match the installed HALCON version exactly.
Even for maintenance releases, which are backwards compatible at application level, mixing of binaries from dif-
ferent releases is not recommended because the internal communication between HALCON/Python and the native
HALCON library is not guaranteed to be always compatible. Therefore, the revision of the HALCON release is
also part of the SemVer major version. The SemVer minor and patch version are reserved for fully backwards-
compatible intermediate releases of the package itself. See section 14.4 on page 96 for updating dependencies.
To use the packages offline, download them from the PyPI website.
96 Creating Applications With HALCON/Python
There is no standard way for assembling Python applications into ready-to-use applications. Approaches range
from just copying files to embedding the source code, interpreter and runtime via tools like cx_Freeze.
Note that native DLLs are resolved at runtime from the system environment. Therefore, a matching HALCON
version and license must be installed on the destination computer, and the environment variables set correctly (see
the Installation Guide,section A.4 on page 45).
You can check which HALCON/Python version is installed in your Python environment by running pip freeze.
If you want to update to a newer HALCON version you must install the new version in your Python environment.
For example, to update to 24.11.1, run this command in a shell inside your project directory:
Chapter 15
HALCON/Python Interface
To strike a good balance between ease of use, readability, and traceability we recommend importing the HAL-
CON/Python module like this:
import halcon as ha
Python
15.2 Using HALCON Operators From HALCON/Python
In HALCON/Python, you call HALCON operators directly as non-member functions, exposed directly through
the top level halcon module.
The following code grabs the first image of an image sequence using a framegrabber and displays the image in a
window:
98 HALCON/Python Interface
framegrabber = ha.open_framegrabber(
name='File',
horizontal_resolution=1,
vertical_resolution=1,
image_width=0,
image_height=0,
start_row=0,
start_column=0,
field='default',
bits_per_channel=-1,
color_space='default',
generic=-1,
external_trigger='default',
camera_type='board/board.seq',
device='default',
port=1,
line_in=-1
)
img = ha.grab_image(framegrabber)
width, height = ha.get_image_size_s(img)
window = ha.open_window(
row=0,
column=0,
width=width,
height=height,
father_window=0,
mode='visible',
machine=''
)
ha.disp_obj(img, window)
ha.open_framegrabber(...)
ha.grab_image(...)
ha.get_image_size_s(...)
ha.open_window(...)
ha.disp_obj(...)
Another important aspect of HALCON/Python is the split of inputs and outputs. Inputs are function parameters,
and outputs are return values.
img = ha.grab_image(framegrabber)
width, height = ha.get_image_size_s(img)
Single outputs are returned directly, and multiple outputs are returned as Python tuple. This allows clearer rea-
soning about data transformations, aided by ergonomic features such as destructuring. This can be seen with
get_image_size_s, which returns two values, both of which can be given names directly.
15.5 HALCON Tuples Are Represented With Native Python Types 99
img = ha.read_image('pcb')
width, height = ha.get_image_size_s(img)
In HALCON/Python, HTuple maps to either one of the following types or to a possibly mixed list of them:
• int
• float
• str
• The class HHandle
Python
Python’s float maps to HALCON’s real type. While Python’s int is of arbitrary precision, calling operators with
int values outside what a signed integer of platform size can represent, e.g.: ptrdiff_t in C, will result in an
exception.
15.6 HHandle
HHandle is a class that represents control handle values.
camera_model = ha.create_camera_setup_model(num_cameras=4)
assert isinstance(camera_model, ha.HHandle)
Here, create_camera_setup_model returns a HHandle that represents a camera model. This HHandle can later
be passed to other operators that work with camera models. Other than equality comparison, HHandle does not
implement any further functionality by itself.
15.7 HObject
HObject is a class that represents iconic objects.
In HALCON, iconic objects model a hierarchy:
object
HALCON/Python does not model this object hierarchy with a class hierarchy, rather it only provides a single class
HObject.
Iconic objects in HALCON can represent collections of objects, such as a sequence of images, or multiple regions
etc. HALCON/Python mirrors this behavior:
img = ha.read_image('pcb')
img_seq = ha.concat_obj(img, ha.read_image('fuse'))
Here, img_seq represents two images, and follow-up operators like get_image_size work in a batch fashion
accordingly.
HObject behaves similarly to lists in Python:
assert len(img_seq) == 2
This includes support for len, iteration, positive and negative indexing, and efficient slicing.
15.8 HDict
HALCON HDicts can be converted to Python dicts and vice versa with the following functions:
A HDict can always be represented as a Python dict. However, not all Python dicts can be represented as HDict.
Consult the documentation of from_python_dict for more details and examples.
HALCON/Python can convert both single values and lists of values to their HTuple representation, that is, the
Python values 345 and [345] share the same HTuple representation. As a consequence, once Python values
have been converted to their HALCON counterparts, this information is lost. As a consequence, roundtrip con-
verting a Python dict through an HDict and back is a lossy operation. as_python_dict represents all HTuples
as lists. In addition, as_python_dict_s can be used if the user expects that all HTuple values are single val-
ues. as_python_dict_s represents all HTuples as single values and not as lists. as_python_dict_s raises an
HError if any HTuple has more than one value.
An example usage of the conversion hooks can be found in section 15.9 on page 100.
HALCON images can be converted to NumPy arrays and vice versa with the following functions:
The functions are only usable if the third-party library NumPy package has been installed. Usage example:
import halcon as ha
import numpy as np
if __name__ == '__main__':
# Single-channel image.
img = ha.read_image('pcb')
numpy_array = ha.himage_as_numpy_array(img)
assert (numpy_array[0][:4] == [225, 216, 224, 230]).all()
img_roundtrip = ha.himage_from_numpy_array(numpy_array)
assert ha.compare_obj(img, img_roundtrip, 0)
Python
The dict conversion functions (see section 15.8 on page 100) have customization points that can be used in con-
junction with the NumPy conversion functions. For example:
import halcon as ha
import numpy as np
if __name__ == '__main__':
numpy_image = np.array([[5, 6, 7], [8, 2, 6], [4, 4, 5]], dtype=np.int32)
py_dict = {'val': [4, 6], 'img': numpy_image}
hdict = ha.from_python_dict(py_dict, unknown_hook=ha.himage_from_numpy_array)
py_dict_roundtrip = ha.as_python_dict(hdict, hobject_hook=ha.himage_as_numpy_array)
img = ha.read_image('pcb')
Asking for the size of a single image, and getting a list with a single element is not particularly useful. _s versions
express the expectation that there should always be exactly one answer, neither zero nor many, explicitly and
conveniently.
For information about which operators have such versions, see the HALCON operator reference.
Just like Python, HALCON/Python handles errors via exceptions. As shown in the example below, HALCON
error constants are defined at the module level.
def load_custom_pcb_img_or_fallback(custom_pcb_filename):
try:
return ha.read_image(custom_pcb_filename)
except ha.HOperatorError as err:
if err.error_code != ha.errors.H_ERR_FNF: # HALCON error code File not found.
raise err
return ha.read_image('pcb')
img = load_custom_pcb_img_or_fallback('does-not-exist')
In this example, we want to either load a custom PCB image or fallback to the default PCB image if the image
cannot be found. If another error occurs, we want to propagate the original error further up the call stack.
The custom exceptions used by HALCON/Python form an inheritance hierarchy:
Exceptions
HError
It starts with the standard Python Exception, from which HError inherits, followed by four more specific excep-
tions that inherit from HError. They occur in different situations. Operators and other functions may raise more
than one type of exception.
15.12 Garbage Collection 103
class CustomClass(object):
pass
img = ha.read_image(CustomClass())
HALCON/Python does not know how to pass the custom user defined class to the HALCON operator
read_image. For any instance where a conversion to or from a native HALCON tuple fails, an instance of
HTupleConversionError is raised.
Python
This means no additional care needs to be taken to ensure that native resources such as memory are freed after a
variable is no longer reachable.
For example, CPython uses ref counting to implement garbage collection, which results in moderately deterministic
behavior.
framegrabber = ha.open_framegrabber(
name='File',
horizontal_resolution=1,
vertical_resolution=1,
image_width=0,
image_height=0,
start_row=0,
start_column=0,
field='default',
bits_per_channel=-1,
color_space='default',
generic=-1,
external_trigger='default',
camera_type='board/board.seq',
device='default',
port=1,
line_in=-1
)
try:
# Replace invalid UTF-8 when encoding \Halcon strings for use in Python.
ha.ffi.enable_utf8_error_replace()
Disabling the safe default mode is only recommended as a workaround and should only be done where needed, for
as long as needed.
import os
os.environ['HALCON_PYTHON_XL'] = 'true'
import halcon as ha
Alternatively, it’s possible to set the environment variable through the usual system specific settings. If possible
we recommend using the suggested method, to minimize external dependencies.
• HUseSpinLock
See section 2.5.3 on page 20.
15.17 Global HALCON Functions in HALCON/Python 105
• HDoLicenseError
Controls the display license error messages.
• HStartUpThreadPool
See section 2.5.3 on page 20.
• HCancelDraw
Cancels draw operators explicitly.
• HSetMemoryAllocatorType
Sets the allocator used by HALCON. Can be used to avoid mimalloc initialization. Supported values are
’system’ and ’mimalloc’.
Example usage:
import halcon as ha
ha.ffi.HUseSpinLock(False)
ha.ffi.HSetMemoryAllocatorType('system')
if __name__ == '__main__':
img = ha.read_image('pcb')
assert ha.get_system_s('memory_allocator') == 'system'
Python
ha.ffi.HSetMemoryAllocatorType('mimalloc')
# The same can be achieved with set_system.
ha.set_system('memory_allocator', 'mimalloc')
106 HALCON/Python Interface
Part V
Chapter 16
Introducing HALCON/C
HALCON/C is the interface of the image analysis system HALCON to the programming language C. Together
with the HALCON library, it allows to use the image processing power of HALCON inside C programs.
This part is organized as follows: We start with a first example program to show you how programming with
HALCON/C looks like. Chapter 17 on page 111 introduces the different parameter classes of HALCON operators.
We will explain the use of HALCON tuples (section 17.2.4 on page 114) for supplying operators with tuples of
control parameters in great detail: Using tuples, the two calls to select_shape in our example program could be
combined into only one call. We will further explain the use of HALCON vectors in section 17.3 on page 117.
Chapter 18 on page 125 is dedicated to the return values of HALCON operators. Chapter 19 on page 127 gives an
overview over all the include files and C libraries necessary for compiling C programs and shows how to create a
stand-alone application. Finally, chapter 20 on page 133 contains example solutions for some common problems
in image processing (like edge detection).
C
This section demonstrates how to create a simple HALCON application with C. For a more comprehensive de-
scription, see chapter 19 on page 127.
The task is to read an image and compute the number of connected regions in it, as illustrated in figure 16.1 on
page 109
Figure 16.1: Left: Input image of a printed circuit board. Middle: Regions found by threshold, colored red. Right:
Connected regions, a result of connection.
#include <HalconC.h>
int main()
{
Hobject img;
read_image(&img, "pcb");
Hobject region;
threshold(img, ®ion, 0, 122);
Hobject connected_regions;
connection(region, &connected_regions);
Hlong num_regions = 0;
count_obj(connected_regions, &num_regions);
./region_example
As a result, you should see the following output ’Number of Regions: 43’.
The HALCON Parameter Classes 111
Chapter 17
C
on page 112 for more details). Whether an operator can be called in tuple mode can be seen in the HALCON
reference manual.
HALCON/C provides the data structure Htuple for tuples of control parameters (see section 17.2.4 on page 114 for
details) and the data structure Hobject for image objects (single objects as well as object tuples; see section 17.1).
HALCON/C provides the data type Hobject for image objects (both images and regions). In fact, Hobject is a
surrogate of the HALCON database containing all image objects. Input image objects are passed to the HALCON
operators by value as usual, output image objects are passed by reference, using the &-operator. Variables of type
Hobject may be a single image object as well as tuples of image objects. Single objects are treated as tuples with
length one.
Of course, users can access specific objects in an object tuple, too. To do so, it is necessary to extract the specific
object key (converted to integer) first, using the operators obj_to_integer or copy_obj. The number of objects
in a tuple can be queried with count_obj. To convert the keys (returned from obj_to_integer) back to image
objects again, the operator integer_to_obj has to be used. Note that integer_to_obj duplicates the image
objects. (This does not necessarily mean that the corresponding gray value arrays are also duplicated. As long
as there is only read-access, a duplication of the references is sufficient). Therefore, all extracted objects have to
be deleted explicitly from the HALCON database, using clear_obj. Figure 17.1 contains an excerpt from a C
program to clarify that approach.
...
Hobject objects; /* tuple of image objects */
Hobject obj; /* single image object */
Hlong surrogate; /* object key, converted to integer */
Htuple Tsurrogates; /* tuple of object keys */
Htuple Index,Num; /* temporary tuple for parameter passing */
Hlong i; /* loop variable */
Hlong num; /* number of objects */
...
count_obj(objects, &num);
/* variant 1: object key -> control parameter */
create_tuple_i(&Index,1);
create_tuple_i(&Num,num);
T_obj_to_integer(objects,Index,Num,&Tsurrogates);
for (i=0; i<num; i++)
{
surrogate = get_i(Tsurrogates,i);
/* process single object */
}
/* variant 2: copying objects individually */
for (i=1; i<=num; i++)
{
copy_obj(objects,&obj,i,1);
/* process single object */
}
...
Figure 17.1: Accessing the i-th image object in a tuple of image objects.
Some HALCON operators like difference allow the use of the following specific image objects as input param-
eters:
HALCON/C supports the following data types as types for control parameters of HALCON operators:
• integers,
17.2 Control Parameters 113
Regardless of the encoding of the HALCON library (set_system(’filename_encoding’, ...)) the HAL-
CON/C interface expects raw char pointer strings that are passed to HALCON operators and to Htuple in-
stances to be UTF-8 encoded. The encoding of the HALCON/C interface (interface encoding) can be changed
to local-8-bit encoding via a call of SetHcInterfaceStringEncodingIsUtf8(false). Note that the en-
coding must not be changed when using HDevEngine. The current interface encoding can be requested via !
IsHcInterfaceStringEncodingUtf8(). It is not recommended to switch the interface encoding back and
forth. The setting should be adjusted only once at the very beginning of the program (before the first HALCON
operator or assignment), because the Htuple structure can not store in which encoding the contained strings are
present, i.e, for all write and read accesses, the same encoding must be set. Furthermore, the interface encoding
is set globally and is therefore not suitable for multithreading programs: Changing the setting in one thread has
an effect on other threads. Note also, that UTF-8 encoded strings may take more memory space than strings in
local-8-bit-encoding. This must be considered when providing the buffer for strings returned by HALCON oper-
ators. As long as the maximum length of the strings returned is not known for sure, it is recommended preferring
operator calls in tuple mode over simple mode.
If the string encoding needs to be converted without changing the interface encoding, the following functions for
converting wchar_t* strings and char* strings to or from tuples are provided:
C
get_s_to_utf8 get_s_to_local8bit get_s_to_wcs
When converted to a different encoding, a string may need a buffer of bigger size. To check on whether you have
to allocate more memory for your string you can use the get_s_to_*-functions mentioned in the table above (see
also figure 17.7). The functions transcode a string to the respective encoding and write it into the buffer provided
by the user. If the returned size of the string is greater or equal to the provided buffer, the passed buffer size was
too small.
Using control parameter tuples in C is not as elegant as using image object tuples. To circumvent the missing
generic lists in C, it was necessary to introduce two different working modes into HALCON/C: The simple mode
and the tuple mode. If a tuple is necessary for at least one control parameter, the tuple mode has to be used for
operator calls. In tuple mode, all control parameters of an operator must be passed as type Htuple. Mixing of
the two modes is not possible. The tuple mode also has to be used if the number or type of values that a operator
calculates is unknown beforehand.
Basically, there are three ways to determine the default type of control parameters for a given operator:
Sometimes the manuals mention more than one possible type. If only integers and floating point numbers are
allowed for a parameter, values have to be passed as parameters of type double. For all other combinations of
types, the tuple mode has to be used.
HALCON operators, that are called in tuple mode are distinguished from simple mode calls by a preceding T_.
This means that the following is a call of the HALCON operator select_shape (as described in the HALCON
reference manual) in simple mode
select_shape
whereas
T_select_shape
In the so-called simple mode, all control parameters of operator calls are variables (or constants) of the data types
Hlong and double input control parameters are passed by value as usual, the corresponding output control param-
eters are passed by reference, using the &-operator. String parameters are pointers to char in both cases. Note that
the memory for output control parameters (in particular strings) has to be provided by the caller! We recommend
allocating memory for at least 1024 characters for string parameters of unknown length. Output parameter values
that are of no further interest can be set to NULL.
Examples for HALCON operator calls in simple mode can be found in the C programs in figure 17.1 and figure 16.1
on page 109.
Operators with parameters resembling handles must always be called in the tuple mode as described in the follow-
ing section. The simple mode for these operators is only available in legacy handle mode (see set_system).
We mentioned already that control parameter tuples for HALCON operators need special treatment. In this chapter
we will give the details on how to construct and use those tuples. The HALCON reference manual describes a large
number of operators that don’t operate on single control values but on tuples of values. Using those operators, it is
easy to write very compact and efficient programs, because often it is possible to combine multiple similar operator
calls into a single call.
Unfortunately, C provides no generic tuple or list constructor. In contrast, HALCON allows tuples with mixed
types as control parameter values (e.g., integers mixed with floating point numbers).
Therefore, in addition to the very intuitive simple mode there is another mode in HALCON/C: the tuple mode.
Using this mode is a little more elaborate. If at least one of the control parameters of a HALCON operator is
passed as a tuple, the tuple mode has to be used for all control parameters (Mixing of both modes isn’t possible).
Furthermore, the tuple mode also has to be used if the number or type of the calculated values are unknown
beforehand.
Syntactically, tuple mode is distinguished from simple mode by a T_ preceding the operator name. For example,
calling disp_circle in tuple mode is done by
T_disp_circle(...)
To ease the usage of the tuple mode, HALCON/C provides the abstract data type Htuple for control parameter
tuples. Objects of type Htuple may be constructed using arrays of the types
17.2 Control Parameters 115
First, memory must be allocated for all tuples of input control parameters, using create_tuple or
C
create_tuple_type, respectively (see figures 17.2). Memory for output control parameter tuples is allocated
by HALCON/C (a call of create_tuple isn’t necessary). With create_tuple_i etc. you can create a tuple of
length 1 and set its value in a single step (see figures 17.3). With reuse_tuple_i etc. you can reuse an existing
tuple, i.e., destroy and reallocate it and set a single value (see figures 17.4).
You set tuple elements using the appropriate procedures set_*. set_s, which insert a string into a tuple, allocates
the needed memory by itself, and then copies the string (see figure 17.5).
Then, the HALCON operator is actually called. The operator name is (as already explained) preceded by a T_ to
denote tuple mode.
Further processing of the output parameter tuples takes place, using the procedures length_tuple, get_type
(see figure 17.2) and get_* (see figure 17.6 and figure 17.7). When processing strings (using get_s), please note
that the allocated memory is freed automatically upon deleting the tuple with destroy_tuple. If the string has
to be processed even after the deletion of the tuple, the whole string must be copied first. Also note that output
handles might be freed when deleting the last tuple. If a handle should be used further, it should be kept in a tuple.
116 The HALCON Parameter Classes
void create_tuple_type(tuple,length,type)
Htuple *tuple;
Hlong length;
Hlong type;
/* creates a tuple of 'type' that can hold 'length' entries.
* 'type' can hold either LONG_PAR, DOUBLE_PAR, STRING_PAR,
* HANDLE_PAR, or MIXED_PAR. */
Finally the memory allocated by all the tuples (input and output) has to be freed again. This is done with
destroy_tuple. If you still need the values of the tuple variables, remember to copy them first. Now, the
whole series can start again – using different or the same tuple variables.
An example for the tuple mode can be found in figure 17.8 or the file example3.c: The aim is to obtain information
about the current HALCON system state. The operator get_system(’?’,Values) (here in HDevelop syntax)
returns all system flags with their current values. Since in our case neither number nor type of the output parameters
is known beforehand, we have to use tuple mode for the actual operator call in HALCON/C. The rest of the program
should be self explanatory.
There is also an alternative generic calling mechanism for HALCON operators in tuple mode. This mechanism
is intended for the use in interpreters or graphical user interfaces:
T_call_halcon_by_id(id, ...)
calls the HALCON operator id in tuple mode, passing input parameters and getting the output parameters (see fig-
ure 17.9 on page 123 for the complete signature). The id of an operator can be requested with get_operator_id.
17.3 Vectors 117
void create_tuple_i(tuple,value)
Htuple *tuple;
Hlong val;
/* creates a tuple with specified integer value */
void create_tuple_d(tuple,value)
Htuple *tuple;
double val;
/* creates a tuple with specified double value */
void create_tuple_h(tuple,value)
Htuple *tuple;
Hphandle val;
/* creates a tuple with specified handle value */
void create_tuple_s(tuple,value)
Htuple *tuple;
char *val;
/* creates a tuple with specified string value */
void create_tuple_s_from_local8bit(tuple,value)
Htuple *tuple;
char *val;
/* creates a tuple with specified string value converted */
/* from local-8-bit encoding */
void create_tuple_s_from_utf8(tuple,value)
Htuple *tuple;
char *val;
/* creates a tuple with specified string value converted */
/* from UTF-8 encoding */
void create_tuple_s_from_wcs(tuple,value)
Htuple *tuple;
wchar_t *val;
C
/* creates a tuple with specified string value converted */
/* from wide-character encoding */
17.3 Vectors
HALCON/C provides the data structure Hvector for the use of the vector functionality of the HDevelop language.
A HALCON vector is a container that can hold an arbitrary number of elements of the identical data type (i.e.,
tuples, iconic objects, or vectors) and dimension. The type of a vector, i.e., its dimension and the type of its
elements is defined when initializing the vector instance and cannot be changed during its lifetime. A vector with
one dimension may be a vector of tuples or a vector of iconic objects. A two-dimensional vector may be a vector
of vectors of tuples or a vector of vectors of iconic objects, and so on.
Construction of Vectors
When creating such a vector in HALCON/C you have to differ between vectors of iconic objects and vectors of
tuples.
118 The HALCON Parameter Classes
void reuse_tuple_i(tuple,val)
Htuple *tuple;
Hlong val;
/* reuses a tuple with specified integer value */
void reuse_tuple_d(tuple,val)
Htuple *tuple;
double val;
/* reuses a tuple with specified double value */
void reuse_tuple_h(tuple,val)
Htuple *tuple;
Hphandle val;
/* reuses a tuple with specified handle value */
void reuse_tuple_s(tuple,val)
Htuple *tuple;
char *val;
/* reuses a tuple with specified string value */
void reuse_tuple_s_from_local8bit(tuple,val)
Htuple *tuple;
char *val;
/* reuses a tuple with specified string value converted */
/* from local-8-bit encoding */
void reuse_tuple_s_from_utf8(tuple,val)
Htuple *tuple;
char *val;
/* reuses a tuple with specified string value converted */
/* from UTF-8 encoding */
void reuse_tuple_s_from_wcs(tuple,val)
Htuple *tuple;
wchar_t *val;
/* reuses a tuple with specified string value converted */
/* from wide-character encoding */
These calls create empty vectors of one dimension, e.g., a vector of tuples. It is also possible to create multi-
dimensional vectors, i.e., a vector of vectors of tuples or a vector of vectors of iconic objects and so on, by
specifying the number of dimensions in the call.
V_create_object_vector(2,&vectorObjMulti);
Note that the vector type and its dimension cannot be changed after the creation of the vector.
C
/* ('index' in [0,length_tuple(tuple) - 1]). */
V_get_vector_tuple(vectorTup,index,tuple);
For accessing elements in vectors of iconic objects V_get_vector_obj can be used instead.
V_get_vector_obj(image,vectorTup,index);
120 The HALCON Parameter Classes
The element to be accessed is specified by its index in form of a tuple. It may either contain a single index of an
element in one-dimensional vectors or several indices of the corresponding subvector(s) and its subelement(s) in
multi-dimensional vectors.
You may also query a whole subvector of a multi-dimensional vector using V_get_vector_elem.
Before accessing the contents of a vector you may set some vector elements first. Again a distinction is made
between vectors of tuples, vectors of iconic objects, and multi-dimensional vectors. The following lines show how
to set vector elements of one-dimensional vectors.
The element to be set is again addressed by the specified index, which is represented as a Htuple. Beside the
index, the vector itself and the respective Hobject or Htuple to be set (e.g., image or tuple) must be added to
the call.
For multi-dimensional vectors the specified index tuple must contain the indices of the subvector(s) and its subele-
ment. The following code lines show the whole process from creating a two-dimensional vector, the image to be
set, and the index tuple up to specifying the indices and finally setting the element of the vector.
17.3 Vectors 121
C
/* the string is greater or equal to the provided */
/* buffer, the buffer was too small. */
/* Attention: indices must be in [0,length_tuple(tuple) - 1] */
V_create_object_vector(2,&vectorObjMulti);
read_image(&img,"Image");
set_i(indices,0,0);
set_i(indices,1,1);
#include "HalconC.h"
main ()
{
Htuple In, SysFlags, Info;
Hlong i, num;
printf("System information:\n");
/* prepare query */
create_tuple(&In, 1);
/* "?" = list of all informations */
set_s(In, "?", 0);
T_get_system(In, &SysFlags);
destroy_tuple(In);
num = length_tuple(SysFlags);
for (i = 0; i < num; i++)
{
create_tuple(&In, 1);
set_s(In, get_s(SysFlags, i), 0);
printf("%s ", get_s(SysFlags, i));
T_get_system(In, &Info);
destroy_tuple(In);
if (length_tuple(Info) > 0)
{
switch (get_type(Info, 0))
{
case INT_PAR:
printf("(Hlong): %" LONG_FORMAT "d\n", get_i(Info, 0));
break;
case DOUBLE_PAR:
printf("(double): %f\n", get_d(Info, 0));
break;
case STRING_PAR:
printf("(string): %s\n", get_s(Info, 0));
break;
case HANDLE_PAR:
printf("(handle): %" LONG_FORMAT "d\n", (Hlong)get_h(Info, 0));
break;
}
}
else
{
printf("(--): no data\n");
}
destroy_tuple(Info);
}
}
Figure 17.8: Tuple mode example program: Printing the current HALCON system state.
Destruction of Vectors
If a Hvector is not needed for further processing its contents and allocated memory must be freed with
V_destroy_vector.
V_destroy_vector(vectorTup);
Additional Information
In addition to the previously mentioned basic information the data structure of Hvector provides some more func-
tionality, e.g., inserting or removing vector elements, or concatenation of vectors. Please refer to the corresponding
17.3 Vectors 123
Figure 17.9: Generic calling mechanism for the HALCON/C tuple mode.
C
124 The HALCON Parameter Classes
Return Values of HALCON Operators 125
Chapter 18
HALCON operator return values (type Herror) can be divided into two categories:
• Messages (H_MSG_*) and
• Errors (H_ERR_*).
HALCON operators return H_MSG_TRUE, if no error occurs. Otherwise, a corresponding error value is returned.
Errors in HALCON operators usually result in an exception, i.e., a program abort with the appropriate error mes-
sage in HALCON/C (default exception handling). However, users can disable this mechanism (with a few excep-
tions, like errors in Htuple operators), using
set_check("~give_error");
to provide their own error handling routines. In that case, the operator get_error_text is very useful: This
operator returns the plain text message for any given error code. Finally, the operator
C
set_check("give_error");
enables the HALCON error handling again. Several examples showing the handling of error messages can be seen
in the file example5.c.
126 Return Values of HALCON Operators
Creating Applications With HALCON/C 127
Chapter 19
The HALCON distribution contains examples for creating an application with HALCON/C. The following sections
show
• the relevant directories and files (section 19.1 on page 127)
• the list of provided example applications (section 19.2 on page 128)
• the relevant environment variables (section 19.3 on page 128)
• how to create an executable under Windows (section 19.4 on page 129)
• how to create an executable under Linux (section 19.5 on page 130)
C
• include\HalconC.h
Include file; contains all user-relevant definitions of the HALCON system and the declarations necessary for
the C interface
• bin\%HALCONARCH%\halcon.dll, lib\%HALCONARCH%\halcon.lib
HALCON library (Windows)
• bin\%HALCONARCH%\halconc.dll, lib\%HALCONARCH%\halconc.lib
HALCON/C library (Windows)
• bin\%HALCONARCH%\halconxl.dll, halconcxl.dll,
lib\%HALCONARCH%\halconxl.lib, halconcxl.lib
Corresponding libraries of HALCON XL (Windows)
• lib/$HALCONARCH/libhalcon.so
HALCON library (Linux)
• lib/$HALCONARCH/libhalconc.so
HALCON/C library (Linux)
• lib/$HALCONARCH/libhalconxl.so,libhalconcxl.so
Corresponding libraries of HALCON XL (Linux)
• include\HProto.h
External function declarations
• %HALCONEXAMPLES%\c\CMakeLists.txt
Example CMake file, which can be used to compile the example programs
128 Creating Applications With HALCON/C
• %HALCONEXAMPLES%\c\README.md
Information about building the examples using CMake
• %HALCONEXAMPLES%\c\source\
Directory containing the source files of the example programs
• images\
Images used by the example programs
• help\operators_*
Files necessary for online information
• doc\*
Various manuals (in subdirectories)
#include "HalconC.h"
To create an application, you must link the library halconc.lib/.dll to your program.
The example projects show the necessary Visual C++ settings. For the examples, the project should be of the WIN
32 ConsoleApplication type. Please note that the Visual C++ compiler implicitly calls “Update all dependencies”
if a new file is added to a project. Since HALCON runs under Linux as well as under Windows, the include file
HalconC.h includes several Linux-specific headers as well if included under Linux. As they do not exist under
Windows, and as the Visual C++ compiler ignores the operating system-specific cases in the include files, you will
get a number of warning messages about missing header files. These can safely be ignored.
Make sure that the stacksize is sufficient. Some sophisticated image processing problems require up to 1 MB
stacksize, so ensure to configure your compiler accordingly. See your compiler manual for additional information
on this topic.
C
HALCON XL applications:
Please note that you should use HALCON XL only when you need its features.
If you want to use HALCON XL, you have to link the libraries halconxl.lib/.dll and halconcxl.lib/.dll !
instead of halcon.lib/.dll and halconc.lib/.dll in your project.
To configure, CMake needs to know the location of the HALCON installation, the location of the example
files, and which HALCON architecture to use:
• Specify the location of the HALCON installation via the HALCON_DIR CMake option, or via the
%HALCONROOT% environment variable if the option is not set.
• Specify the location of the HALCON example files via the %HALCONEXAMPLES% environment vari-
able.
130 Creating Applications With HALCON/C
• Specify the HALCON architecture with the HALCON_ARCHITECTURE CMake option, or via the
%HALCONARCH% environment variable. If neither the option nor the environment variable are set,
CMake will try to guess the architecture based on the host build system.
For general information on how to use CMake, see the CMake documentation.
HALCON XL applications: By default, the examples will be built using the normal version of HALCON.
If you want to build using HALCON XL, set the option HALCON_XL to ON or 1 in CMake during the
configuration step. For this, use the following syntax:
3. Optionally, you can use the -G option to specify the generator for a new build tree.
For more information about CMake generators, see the CMake documentation.
Your own C programs that use HALCON operators must include the file HalconC.h, which contains all user-
relevant definitions of the HALCON system and the declarations necessary for the C interface. Do this by adding
the following command near the top of your C file:
#include "HalconC.h"
Using this syntax, the compiler looks for HalconC.h in the current directory only. Alternatively, you can tell
the compiler where to find the file by giving it the -I<pathname> command line flag to denote the include file
directory.
To create an application, link two libraries to your program: The library libhalconc.so contains the various
components of the HALCON/C interface. libhalcon.so is the HALCON library.
HALCON XL applications:
! Please note that you should use HALCON XL only when you need its features.
If you want to use HALCON XL, you have to link the libraries libhalconcxl.so and libhalconxl.so instead.
To link and run applications under Linux, ensure that the system variable LD_LIBRARY_PATH contains the HAL-
CON library path $HALCONROOT/lib/$HALCONARCH.
1. If required, download CMake (version 3.7.1 or later) from the CMake website and install it.
2. Create a build directory and then run cmake to configure the build and create the application:
mkdir build
cd build
cmake $HALCONEXAMPLES/c
cmake --build .
To configure, CMake needs to know the location of the HALCON installation, the location of the example
files, and which HALCON architecture to use:
• Specify the location of the HALCON installation via the HALCON_DIR CMake option, or via the
$HALCONROOT environment variable if the option is not set.
• Specify the location of the HALCON example files via the $HALCONEXAMPLES environment variable.
19.5 Linux 131
• Specify the HALCON architecture with the HALCON_ARCHITECTURE CMake option, or via the
$HALCONARCH environment variable. If neither the option nor the environment variable are set,
CMake will try to guess the architecture based on the host build system.
For general information on how to use CMake, see the CMake documentation.
HALCON XL applications: By default, the examples will be built using the normal version of HAL-
CON. If you want to build using HALCON XL, set the option HALCON_XL to ON or 1 in CMake during
configuration.
3. Optionally, you can use the -G option to specify the generator for a new build tree.
For more information about CMake generators, see the CMake documentation.
C
132 Creating Applications With HALCON/C
Typical Image Processing Problems 133
Chapter 20
This final chapter shows the possibilities of HALCON and HALCON/C on the basis of several simple image
processing problems.
20.1 Thresholding
read_image(&Image,"File_xyz");
threshold(Image,&Thres,0.0,120.0);
connection(Thres,&Conn);
select_shape(Conn,&Result,"area","and",10.0,100000.0);
C
• The remaining image regions are split into connected components.
• By suppressing regions that are too small, noise is eliminated.
read_image(&Image,"File_xyz");
sobel_amp(Image,&Sobel,"sum_abs",3);
threshold(Sobel,&Max,30.0,255.0);
skeleton(Max,&Edges);
read_image(&Image,"File_xyz");
mean_image(Image,&Lp,11,11);
dyn_threshold(Image,Lp,&Thres,5.0,"light");
• The size of the filter mask (11 x 11, in this case) depends directly on the size of the expected objects (both
sizes are directly proportional to each other).
• In this example, the dynamic threshold operator selects all pixels that are at least 5 gray values brighter than
their surrounding (11 x 11) pixels.
read_image(&Image,"File_xyz");
Filter = "ee";
texture_laws(Image,&TT,Filter,2,5);
mean_image(TT,&Lp,31,31);
threshold(Lp,&Seg,30.0,255.0);
• The size of the circular mask (3.5, in this case) determines the smallest size of the remaining objects.
• It is possible to use any kind of mask for object elimination (not only circular masks).
• segmentation(...) is used to denote a segmentation operator that calculates a tuple of image objects
(Seg).
• The rectangle’s shape and size (length and width) determine the smallest size of the remaining objects.
• The rectangle’s orientation determines the orientation of the remaining regions (In this case, the main axis
and the horizontal axis form an angle of 0.5 rad).
• Lines with an orientation different from the mask’s (i.e., the rectangle’s) orientation are suppressed.
• segmentation(...) is used to denote a segmentation operator that calculates a tuple of image objects
(Seg).
The third (and final) application example of morphological operations covers another common image processing
problem — the smoothing of region boundaries and closing of small holes in the regions:
...
segmentation(Image,&Seg);
gen_circle(&Mask,100.0,100.0,3.5);
closing(Seg,Mask,&Res);
• For the smoothing of region boundaries, circular masks are suited best.
• The mask size determines the degree of the smoothing.
• segmentation(...) is used to denote a segmentation operator that calculates a tuple of image objects
(Seg).
C
136 Typical Image Processing Problems
Part VI
Using HDevEngine
Introducing HDevEngine 139
Chapter 21
Introducing HDevEngine
As the name suggests, HDevEngine is the “engine” of HDevelop. This chapter briefly introduces you to its basic
concepts. Chapter 22 on page 143 explains how to use it in C++ applications, and chapter 23 on page 155 how to
use it in .NET applications (C#, Visual Basic.NET, etc.). Additional information that is independent of the used
programming language can be found in chapter 25 on page 189.
HDevEngine
What HDevEngine Does Not Do
Note that HDevEngine does not implement the complete functionality of HDevelop, only what is necessary to
execute programs and procedures. In particular, it does not implement the display of variables and results in the
graphics window, i.e., the internal operators like dev_display. However, you can “redirect” these operators to
your own implementation. Thus, you can decide which visualization is important and where and how it is to take
place in your application.
What is HDevEngine?
HDevEngine is provided as a C++ class library and a .NET assembly. It consists of the following classes:
• (C++), (.NET)
This is the main class of HDevEngine. With it you manage global settings.
• (C++), (.NET)
With this class you load an HDevelop program and get general information about it.
• (C++), (.NET)
With this class you execute a program and get the values of its variables.
• (C++), (.NET)
With this class you load an HDevelop procedure and get general information about it.
140 Introducing HDevEngine
• (C++), (.NET)
With this class you pass input parameters to an HDevelop procedure, execute it, and retrieve its output
parameters.
• (C++),
, , (.NET)
As noted above, HDevEngine does not implement internal HDevelop operators like dev_display. All
HDevEngine variants provide a class or interface to create your own implementation for those operators
that are useful in your application. HDevEngine/.NET also includes two convenience classes that provide a
default implementation of the operators.
• (C++), (.NET)
Instances of this class are “thrown” if an exception occurs inside HDevEngine, e.g., because the application
tried to load a non-existing program or because of an error inside an operator in the executed program or
procedure.
• When developing the image processing part of your application, you will create an HDevelop program.
Thus, as a first test of your (programmed) application, it is useful to execute the HDevelop program via
HDevEngine. This test will already assure that the general configuration of your application (environment
variables, procedure path, etc.) is correct.
The HDevelop program itself should of course use the same procedures that you plan to execute from the
programmed application.
• After you finished its development, you integrate the image processing part into your programmed applica-
tion by executing the corresponding HDevelop procedures. Typically, you display image processing results
by using the methods of the underlying HALCON programming language interface, i.e., HALCON/C++ for
HDevEngine/C++, or HALCON/.NET for HDevEngine/.NET (C#, Visual Basic.NET, etc.), but you can also
encapsulate recurring display tasks in HDevelop procedures.
• Whether to use local or external procedures depends on the reusability of the procedure. External proce-
dures should be used for widely reusable tasks, e.g., opening the connection to the image acquisition device
and configuring it, or for standard image processing tasks like bar code or data code reading. Groups of
closely related external procedures may be combined into a procedure library to keep them as a unit in a
single file.
In contrast, local procedures are suitable for tasks that are not completely reusable, e.g., for training and
configuring a shape model to find objects. Then, different applications can use their optimized variant of the
procedure instead of creating a single procedure with many parameters and internal switches that suits all
applications.
Using local procedures means that you must load the HDevelop program that contains them. However,
as noted above, loading and executing the corresponding HDevelop program is a good test of the general
configuration of the application.
• Use the import statement to make the external procedures available from within your program. For more
information, see also the HDevelop example program hdevelop/Control/import.hdev.
• Alternatively, set the procedure path (via SetProcedurePath) and create the program or procedure (via /)
before you start parallelization.
141
• If the above approaches are not possible, ensure that setting the procedure paths and creating the programs
and procedures both happen within a single critical section to prevent this operation from being interrupted
by other threads. Otherwise, if another thread calls SetProcedurePath after the current thread has called
SetProcedurePath and before the current thread has finished creating its programs or procedures, the
resulting behavior would be undefined.
• dev_error_var
• procedure calls using the par_start qualifier
• par_join
• dev_display with a vector expression as variable
• for loop with a vector expression as index variable
• call of any procedure that cannot be JIT compiled due to the above reasons.
If one of these features is found, the corresponding procedure is executed uncompiled as before by HDevEngine.
HDevEngine XL
Like HALCON, the language-dependent versions of HDevEngine are provided in two variants: based on HALCON
HDevEngine
and based on HALCON XL. The latter use the XL versions of the HALCON library and of HALCON/C++, and
HALCON/.NET, respectively.
142 Introducing HDevEngine
HDevEngine in C++ Applications 143
Chapter 22
This chapter explains how to use HDevEngine in C++ applications. Section 22.1 on page 143 quickly summarizes
some basic information, e.g., how to compile and link such applications. Section 22.2 on page 144 then explains
how to use HDevEngine based on examples.
An overview about the classes of HDevEngine and their methods can be found in section 25.1 on page 189.
You create executable HDevEngine applications in a way similar to normal HALCON/C++ applications. Chapter 7
on page 51 describes this in detail; here, we summarize the most important points and include the extensions for
HDevEngine:
1. In your application, you include the main header file HalconCpp.h and HDevEngine’s header file
HDevengineCpp.h and use the corresponding namespaces on Windows and Linux systems:
#include "HalconCpp.h"
# include "HDevEngineCpp.h"
HDevEngine
2. To compile the application, use the following include paths on Windows systems
/I "$(HALCONROOT)\include" /I "$(HALCONROOT)\include\halconcpp"
/I "$(HALCONROOT)\include\hdevengine"
-I$HALCONROOT/include -I$HALCONROOT/include/halconcpp
-I$HALCONROOT/include/hdevengine
HDevEngine XL applications: If you want to use HDevEngine XL, link the following libraries on Win-
dows systems
144 HDevEngine in C++ Applications
This section explains how to use HDevEngine based on example applications, which reside in the subdirectory
%HALCONEXAMPLES%\hdevengine\cpp. Like the examples for HALCON/C++ described in chapter 7 on page
51, they are provided with CMake files for Linux, and Windows systems.
The example applications show how to
• execute an HDevelop program (section 22.2.1 on page 144),
• execute HDevelop procedures (section 22.2.2 on page 146),
• implement display operators (section 22.2.3 on page 148),
• error handling (section 22.2.4 on page 150).
Section 22.2.5 on page 152 contains additional information for creating multithreaded applications using HDev-
Engine.
In this section, we explain how to load and execute an HDevelop program with HDevEngine. The code fragments
stem from the example application exec_program (source file exec_program.cpp), which checks the boundary
of a plastic part for fins. Figure 22.1 on page 144 shows a screenshot of the application.
First, we include the main header files of HALCON/C++ and of HDevEngine and the corresponding names-
paces. Note that in this example application the HDevEngine header file is already included via the header file
my_hdevoperatorimpl.h so we don’t have to include the HDevEngineCpp.h header file explicitly:
#include "HalconCpp.h"
# include "my_hdevoperatorimpl.h"
The main procedure just calls a procedure that does all the work of the example. First, we create an instance of the
main HDevEngine class .
HDevEngine my_engine;
The path to the HDevelop program and the external procedure path are stored in string variables, with a suitable
syntax for the used platform. Note that in Windows applications you can use both / and \ in path strings:
std::string halcon_examples =
(std::string)HSystem::GetSystem("example_dir")[0].S();
std::string program_path(halcon_examples), ext_proc_path(halcon_examples);
program_path += "/hdevengine/hdevelop/fin_detection.hdev";
ext_proc_path += "/hdevengine/procedures";
If the HDevelop program calls external procedures, you must set the external procedure path with the method :
my_engine.SetProcedurePath(ext_proc_path.c_str());
Now, we create an instance of the class and load the HDevelop program with the method . Note that changes
the working directory if a program is loaded successfully.
The call is encapsulated in a try...catch-block to handle exceptions occurring in the HDevEngine method,
e.g., because the file name was not specified correctly. A detailed description of error handling can be found in
section 22.2.4 on page 150.
HDevProgram my_program;
try
{
my_program.LoadProgram(program_path.c_str());
}
catch (HDevEngineException& hdev_exception)
...
HDevEngine
22.2.1.3 Step 3: Execute Program
If the program could be loaded successfully, we execute the program with the method and store the returned
instance of the class in a variable for later use:
That’s all you need to do to execute an HDevelop program. You can also access its “results”, i.e., its variables with
the method . In the example program, the area of the extracted fin is queried and then displayed:
Note that program variables can only be accessed when the program has terminated.
How to display results while the program is running is described in section 22.2.3 on page 148.
146 HDevEngine in C++ Applications
Figure 22.2: Executing an external HDevelop procedure that detects fins on a boundary.
In this section, we explain how to load and execute an external HDevelop procedure with HDevEngine. The code
fragments in the following stem from the example application exec_extproc (source file exec_extproc.cpp),
which, like the example described in the previous section, checks the boundary of a plastic part for fins. Figure 22.2
on page 146 shows a screenshot of the application.
In contrast to the previous example, the result display is programmed explicitly in HALCON/C++ instead of relying
on the internal display operators. How to provide your own implementation of the internal display operators is
described in section 22.2.3 on page 148.
As when executing an HDevelop program, we include the main header files of HALCON/C++ and of HDevEn-
gine and the namespaces. In this example application the HDevEngine header file is included via the header file
my_error_output.h so we don’t need to include it explicitly. The main procedure just calls the procedure run
that does all the work of the example. We create an instance of the main HDevEngine class and directly set the
external procedure path with the method . If the external procedure is from a procedure library, the external
procedure path may include the name of the library file.
#include "HalconCpp.h"
# include "my_error_output.h"
void run(void)
{
std::string halcon_examples =
(std::string)HSystem::GetSystem("example_dir")[0].S();
std::string ext_proc_path(halcon_examples);
...
HDevEngine().SetProcedurePath(ext_proc_path.c_str());
DetectFin();
}
22.2 How to Use HDevEngine/C++ 147
In the “action” routine, we load the external procedure with the constructor of the class
, specifying the name of the procedure, and store the returned procedure call in an instance
of the class . The call is encapsulated in a try...catch-block to handle exceptions occur-
ring in the constructor, e.g., because the file name or the procedure path was not specified cor-
rectly. A detailed description of error handling can be found in section 22.2.4 on page 150.
void DetectFin()
{
try
{
HDevProcedure proc("detect_fin");
HDevProcedureCall proc_call(proc);
Before executing the procedure, we open and initialize the graphics window in which the results are to be
displayed and load an example image sequence:
Each image should now be processed by the procedure, which has the following signature, i.e., it expects an image
as (iconic) input parameter and returns the detected fin region and its area as iconic and control output parameter,
respectively:
We pass the image as input object by storing it in the instance of with the method . Which parameter to set is
HDevEngine
specified via its index (starting with 1); there is also a method to specify it via its name (see section 25.1.5 on page
200):
proc_call.SetInputIconicParamObject(1, image);
As as alternative to passing parameters, you can also use global variables in HDevEngine (compare
the HDevelopUser’s Guide, section 8.3.2 on page 252). You set the value of a global variable with
the methods SetGlobalIconicVarObject or SetGlobalCtrlVarTuple and query it with the methods
GetGlobalIconicVarObject and GetGlobalCtrlVarTuple.
However, take care not to overwrite the value of a variable of one program with that of another: Each global
variable can have only one value at a time for all running HDevEngine instances.
proc_call.Execute();
148 HDevEngine in C++ Applications
If the procedure was executed successfully, we can access its results, i.e., the fin region and its area, with the
methods and of the class ; again, you can specify the parameter via its index or name (see section 25.1.5 on page
200).
Now, we display the results in the graphics window. Note how we access the area by selecting the first element
of the returned tuple:
char fin_area_str[200];
sprintf(fin_area_str, "Fin Area: %ld", (long)(fin_area[0].L()));
win.DispImage(image);
win.SetColor("red");
win.DispRegion(fin_region);
win.SetColor("white");
win.SetTposition(150, 20);
win.WriteString(fin_area_str);
The example application exec_procedures (source file exec_procedures.cpp) executes local and external
HDevelop procedures with HDevEngine. It mimics the behavior of the HDevelop program described in sec-
tion 22.2.1 on page 144. The display of results is partly programmed explicitly and partly delegated to an HDe-
velop procedure, using the implementation of the internal display operators described in section 22.2.3 on page
148.
Local and external procedures are created and executed in exactly the same way. The only difference is that in
order to use a local procedure, you must load the program it is contained in, whereas to load external procedures
you must set the procedure path. provides different constructors to facilitate this task (see section 25.1.4 on page
197).
22.2.3 Display
In this section, we explain how to provide your own implementation of HDevelop’s internal display operators. The
files my_hdevoperatorimpl.h and my_hdevoperatorimpl.cpp contain an example implementation, which
is used in the applications exec_program (source file exec_program.cpp), which was already discussed in
section 22.2.1 on page 144, and exec_procedures (source file exec_procedures.cpp).
In fact, HDevEngine does not provide an implementation of the internal display operators but provides the class ,
which contains empty virtual methods for all those operators that you can implement yourself. The methods are
called like the object-oriented version of the operators, e.g., for dev_display and have the same parameters (see
section 25.1.6 on page 202 for the definition of the class).
The first step towards the implementation is to derive a child of this class and to specify all meth-
ods that you want to implement. The example file implements the operators dev_open_window,
dev_set_window_extents, dev_set_part, dev_set_window, dev_get_window, dev_clear_window,
dev_clear_window, dev_close_window, dev_display, dev_set_draw, dev_set_shape, dev_set_color,
dev_set_colored, dev_set_lut, dev_set_paint, and dev_set_line_width:
22.2 How to Use HDevEngine/C++ 149
In addition to these methods, the class contains methods to handle multiple graphics windows. These methods use
HDevEngine
a second class that manages all open windows. This class is thread-safe and reentrant but not described in detail in
this section.
class WinIdContainer
In the executed HDevelop program, two graphics windows are used, one for the main display and one for zooming
into the image (see figure 22.1 on page 144).
To use the implementation of , you include the header file:
#include "my_hdevoperatorimpl.h"
With the method , you pass an instance of your version of to HDevEngine, which then calls its methods when the
corresponding operator is used in the HDevelop program or procedure.
my_engine.SetHDevOperatorImpl(&op_impl);
150 HDevEngine in C++ Applications
Now, we take a closer look at the implementation of the display operators in the example. It tries to mimic the
behavior in HDevelop: Multiple graphics windows can be open, with one being “active” or “current”. The methods
for the internal display operators simply call the corresponding non-internal display operator: For example, a call
to dev_display in the HDevelop program is “redirected” in to disp_obj, with the iconic object to display and
the handle of the active window as parameters:
As you can see, these operators can be implemented quite easily. The implementation of the operators for handling
graphics windows is not described here. We recommend using the example implementation as it is because it
provides all the necessary functionality for single- and multithreaded applications.
In this section, we take a closer look at exceptions in HDevEngine. The code fragments in the following stem from
the example application error_handling (source file error_handling.cpp), which provokes different types of
exceptions and “catches” them.
HDevEngine “throws” exceptions in form of the class , which contains the type (category) of the exception, a
message describing the exception, and, depending on the exception type, information like the name of the executed
procedure or the HALCON error code (see section 25.1.7 on page 202 for the declaration of the class).
The example code for displaying information about exceptions in a graphics window is contained in the files
my_error_output.cpp and my_error_output.h. You can use it in your application by including the header
file:
#include "my_error_output.h"
The files provide two procedures. The simpler one displays only the error message and waits for a mouse click to
continue:
The more complex one prints all available information for the exception (only relevant code shown):
22.2 How to Use HDevEngine/C++ 151
WriteMessageNL(win, exception.Message());
This procedure is called when an exception occurs. The example provokes different errors and displays the corre-
sponding information; some of them are described in the following. Figure 22.3 on page 151 displays an exception
that occurred because the application tried to load a non-existing HDevelop program (category ).
try
{
program.LoadProgram(wrong_program_path.c_str());
}
catch (HDevEngineException& hdev_exception)
{
DispErrorMessage(hdev_exception,
"Error #1: Try to load a program that does not exist");
}
HDevEngine
Figure 22.3: Content of the exception if an HDevelop program could not be found.
The same exception category occurs when a program is loaded whose external procedures are not found (see
figure 22.4 on page 152).
The exception displayed in figure 22.5 on page 152 occurs because an input iconic parameter is not initialized
(category ). It contains very detailed information about where the error occurred and why.
The exception displayed in figure 22.6 on page 152 is provoked by calling an operator with an invalid parameter
(category ).
152 HDevEngine in C++ Applications
Figure 22.4: Content of the exception if external procedures of an HDevelop program could not be loaded.
Figure 22.5: Content of the exception if an input parameter was not initialized.
With the method UserData (see section 25.1.7 on page 202), you can also access user exception data
that is thrown within an HDevelop program or procedure by the operator throw similarly to the operator
dev_get_exception_data.
In case of an exception (which is not caught within the procedure) the procedure call is cleaned up. This means all
subthreads are destroyed and all values of input and output parameters are cleared. Therefore, we recommend that
you always set all input parameters before executing a call even if some of them did not change.
Note that you can configure the behavior of HDevEngine when loading programs or procedures that contain invalid
lines or unresolved procedure calls with the method SetEngineAttribute (see section 25.1.1 on page 190).
In the example mfc\exec_procedures_mt_mfc , three threads execute HDevelop procedures for image acquisi-
tion, data code reading, and visualization in parallel (see figure 22.7 on page 153). Please have a look at the example
source files (in the directory mfc\exec_procedures_mt_mfc\source\) to see how the threads synchronize their
input and output data.
The example exec_programs_mt (source file exec_programs_mt.cpp) shows how one or several different HDe-
velop programs can be executed in different threads in parallel. Note that it is kept very general and does not realize
a specific application.
Figure 22.6: Content of the exception if an error occurred in a HALCON operator call.
22.3 Using the Just-in-time Compiler With HDevEngine/C++ 153
Figure 22.7: Example program with three threads performing image acquisition, data code reading, and visualization
in parallel.
The HDevelop program(s) must be passed as command line arguments. Optionally, you can pass for every program
the number of threads and/or how often the program should be performed consecutively within each thread. The
command line parameters are explained when calling the executable without parameters.
The example application use_vector_variables shows how to load and execute an HDevelop program that
contains vector variables in HDevengine/C++. In the example two vectors are used for processing: one con-
taining the input images and one containing scaling factors. When executing the program the gray values of
the input images are scaled according to the scaling factors. Please have a look at the example source file
use_vector_variables.cpp for more details on how to work with vector variables in HDevengine/C++.
HDevEngine
The just-in-time compilation of procedures needs to be enabled in your instance of the class:
Procedures (and procedures referenced by it) are compiled at the moment a corresponding instance of or is
created.
You can also explicitly pre-compile all used procedures of a HDevelop program or procedure using the method
CompileUsedProcedures of or , respectively.
In the following example, all used procedures of a procedure call are just-in-time compiled:
HDevProgram my_program(program_path.c_str());
HDevProcedure proc_fib(my_program, "fib");
...
proc_fib.CompileUsedProcedures();
154 HDevEngine in C++ Applications
HDevEngine in .NET Applications 155
Chapter 23
This chapter explains how to use HDevEngine in C# and Visual Basic.NET applications. Section 23.1 on page 155
quickly summarizes some basic information about creating HDevEngine applications with .NET Core and .NET
Framework. Section 23.2 on page 155 then explains how to use HDevEngine/.NET based on examples.
23.1 Basics
A short reference of the C++ classes for the HDevEngine can be found in section 25.1 on page 189. The .NET
classes are very similar; their exact definition can be seen in the online help of Visual Studio (see section 11.1.1 on
page 70).
To use HDevEngine in Visual Studio .NET, you must add a reference to the HDevEngine/.NET assembly
HDevEngine
hdevenginedotnet.dll via the Solution Explorer. See section 10.3.3 on page 66.
HDevEngine XL applications: If you want to use HDevEngine/.NET XL, you must add the XL versions of the
HALCON/.NET and HDevEngine/.NET assembly instead.
23.2 Examples
This section explains how to create a simple HDevEngine/.NET application with .NET Core. For a more compre-
hensive description, read section 23.2.2 on page 156.
using HalconDotNet;
namespace hdevengine_example
{
class Program
{
static void Main(string[] args)
{
string ExampleDir = HSystem.GetSystem("example_dir");
string ProcedurePath = "/hdevengine/procedures";
ProcCall.SetInputIconicParamObject("Image", Image);
ProcCall.Execute();
As as result, you should see the following output ’Fin Area: 1634’.
This section explains how to use HDevEngine/.NET with the help of example applications written in C#, which
reside in the subdirectory %HALCONEXAMPLES%\hdevengine\c#. Most examples use Windows Forms, which is
only available for .NET Core on Windows. The HDevEngine/.NET specific information also applies to .NET Core
in general.
For some examples, Visual Basic.NET versions are available, which reside in the subdirectory
%HALCONEXAMPLES%\hdevengine\vb.net. They are identical except for the standard differences between the
two languages.
The example applications show how to
In this section, we explain how to load and execute an HDevelop program with HDevEngine. The code fragments
stem from the example application ExecProgram, which checks the boundary of a plastic part for fins. Figure 23.1
on page 157 shows a screenshot of the application; it contains two buttons to load and execute the HDevelop
program.
Upon loading the form, we store the path to the HDevelop program and set the external procedure path with the
method :
String ProgramPathString;
HDevEngine
ProgramPathString = Path.GetFullPath(
ExampleDir + "/hdevengine/hdevelop/fin_detection.hdev"
);
}
Note that the latter is only necessary if the HDevelop program calls external procedures.
When you click the button to load the HDevelop program, an instance of the class is created, with the path of the
program as parameter. Furthermore, an instance of is created for later use. Note that the working directory will be
changed if a program is loaded.
Exceptions occurring in the constructors, e.g., because the file name was not specified correctly, are handled with
the standard C# error handling mechanism:
158 HDevEngine in .NET Applications
...
}
More information on error handling can be found in section 23.2.6 on page 163.
When you click the button to execute the program, the method is called:
That’s all you need to do to execute a HDevelop program. You can also access its “results”, i.e., its variables with
the method . In the example program, the area of the extracted fin is queried and then displayed:
double FinArea;
FinArea = ProgramCall.GetCtrlVarTuple("FinArea");
Window.SetTposition(150, 20);
Window.WriteString("Fin Area: ");
Note that program variables can only be accessed when the program has terminated.
How to display results while the program is running is described in section 23.2.5 on page 163.
Figure 23.2: Executing an external HDevelop procedure that detects fins on a boundary.
In this section, we explain how to load and execute an external HDevelop procedure with HDevEngine. The code
fragments in the following stem from the example application ExecExtProc, which, like the example described
in the previous section, checks the boundary of a plastic part for fins. Figure 23.2 on page 159 shows a screenshot
of the application; it contains two buttons to load and execute the HDevelop procedure.
In contrast to the previous example, the result display is programmed explicitly instead of relying on the internal
display operators.
As when executing an HDevelop program, we create a global instance of the main HDevEngine class and set the
external procedure path with the method upon loading the form (code for constructing the path omitted). If the
external procedure is from a procedure library, the external procedure path may include the name of the library file.
HDevEngine
In contrast to the C++ version of this example application, we want to display the results not in a free-floating
graphics window, but within the form, i.e, inside an instance of HSmartWindowControl (also see section 11.7 on
page 82 and section 11.5 on page 80). For calling the HALCON operators, we declare a global variable of the
class HWindow for the underlying HALCON window; upon loading the form, we set this variable to the HALCON
window in the HSmartWindowControl and initialize the window:
Window.SetDraw("margin");
Window.SetLineWidth(4);
}
When you click the button Load, the HDevelop procedure is loaded with the constructor of the class , specifying
the name of the procedure, and a corresponding procedure call is created as an instance of the class . Exceptions
160 HDevEngine in .NET Applications
occurring in the constructors, e.g., because the file name or the procedure path was not specified correctly, are
handled with the standard C# error handling mechanism. More information on error handling can be found in
section 23.2.6 on page 163.
Executing a procedure consists of multiple steps. First, we load an example image sequence:
Each image should now be processed by the procedure, which has the following signature, i.e., it expects an image
as (iconic) input parameter and returns the detected fin region and its area as iconic and control output parameter,
respectively:
We pass the image as an input object by storing it in the instance of with the method . Which parameter to set is
specified via its name (as an alternative, you can specify it via its index):
ProcCall.SetInputIconicParamObject("Image", Image);
As as alternative to passing parameters, you can also use global variables in HDevEngine (compare
the HDevelopUser’s Guide, section 8.3.2 on page 252). You set the value of a global variable with
the methods SetGlobalIconicVarObject or SetGlobalCtrlVarTuple and query it with the methods
GetGlobalIconicVarObject and GetGlobalCtrlVarTuple.
However, take care not to overwrite the value of a variable of one program with that of another: Each global
variable can have only one value at a time for all running HDevEngine instances.
ProcCall.Execute();
23.2 Examples 161
If the procedure was executed successfully, we can access its results, i.e., the fin region and its area, with the
methods and of the class ; again, you can specify the parameter via its name or index. Note that you can get iconic
output objects either as instances of the corresponding class (here, HRegion) or as instance of HObject by using .
FinRegion = ProcCall.GetOutputIconicParamRegion("FinRegion");
FinArea = ProcCall.GetOutputCtrlParamTuple("FinArea");
this.Invoke((MethodInvoker)delegate
{
Image.DispObj(Window);
Window.SetColor("red");
Window.DispObj(FinRegion);
Window.SetColor("white");
Window.SetTposition(150, 20);
Window.WriteString("FinArea: " + FinArea.D);
});
HDevEngine
23.2.4.8 Executing Local and External HDevelop Procedures
The example application ExecProcedures executes local and external HDevelop procedures with HDevEngine.
It mimics the behavior of the HDevelop program described in section 23.2.3 on page 157. The display of results
is partly programmed explicitly and partly delegated to an HDevelop procedure, using the implementation of the
internal display operators described in section 23.2.5 on page 163. Figure 23.3 on page 161 shows a screenshot of
the application.
In the following, we briefly describe parts of the code.
Local and external procedures are created and executed in exactly the same way. The only difference is that in
order to use a local procedure, you must load the program it is contained in, whereas to load external procedures
you must set the procedure path. In the example, the image processing procedure is local, the other external. Note
that the code for constructing the program and procedure path is omitted.
162 HDevEngine in .NET Applications
One of the procedures opens the image acquisition device. It returns the corresponding handle, which we store in
an instance of the class HFramegrabber.
In the example application, the device is closed when the application terminates and calls the finalizer of the class
HFramegrabber, which in turn calls the operator CloseFramegrabber. If you use an HDevelop procedure for
closing the connection to the device, you would invalidate the handle so that the finalizer raises an exception.
As in the previous example, the results of image processing (button Process Image) are displayed “manually”
by calling HALCON/.NET operators. In contrast, when you click the button Visualize Details, an HDevelop
procedure is executed that zooms onto the extracted fin. For this, we pass an implementation of HDevelop’s
internal display operators (see section 23.2.5 on page 163 for more information about the implementation classes)
and remove it again after the procedure has been executed.
VisualizeDetailsProcCall.SetInputIconicParamObject("Image", Image);
VisualizeDetailsProcCall.SetInputIconicParamObject("Region", FinRegion);
VisualizeDetailsProcCall.SetInputCtrlParamTuple("ZoomScale", 2);
VisualizeDetailsProcCall.SetInputCtrlParamTuple("Margin", 5);
VisualizeDetailsProcCall.Execute();
MyEngine.SetHDevOperators(null);
}
23.2 Examples 163
The instance of the implementation class is initialized with the HALCON window of the form.
If the class is initialized without specifying the window, a new HALCON window will open automatically to em-
ulate the behavior of HDevelop. Consequently, using the operator dev_open_window in your HDevelop program
or procedure will open another window. The newly opened window is set active automatically.
23.2.5 Display
In contrast to the C++ version of HDevEngine, HDevEngine/.NET already provides convenience implementations
of HDevelop’s internal display operators in form of two classes:
• directs all display operators to a single graphics window (passed in the constructor), even if the HDevelop
program or procedure uses multiple windows.
• can handle multiple graphics windows. You can pass an arbitrary number of graphics windows in the
constructor; if the HDevelop program or procedure uses more than them, HDevEngine opens additional
free-floating windows.
In the example code, some of the actual program and procedure execution is delegated to a background thread. This
is good practice because long-running execution would otherwise lead to an unresponsive GUI. Further, HDevelop
code using interactive drawing objects would not work with HSmartWindowControl if the GUI thread is blocked.
While HALCON display operators are thread-safe, access to Windows Forms elements is not (for example, to en-
able buttons or set label texts). Therefore, result visualization is delegated back to the GUI thread using Invoke()
calls in these examples.
Finally, using dev_* operators for visualization via or is limited for multithreaded applications (executing multi-
ple procedures in parallel). This is because there is only one global “active” window at any given time as controlled
by dev_set_window, hence threads cannot control their output windows independently. This behavior is consis-
tent with the behavior in HDevelop (which also has only one active window) when using multiple threads via
par_start.
HDevEngine
If parallel visualization is desired, we recommend writing explicit visualization code using HALCON operators
that output directly to the desired window. For more information, see section 23.2.7 on page 166.
The example program ExecProgram uses . To use this class (or ), you pass an instance of it to with the method :
MyEngine.SetHDevOperators(new HDevOpMultiWindowImpl(Window));
}
If your application has special display requirements that are not satisfied by the two classes, you can provide your
own implementation of the display operators similar to the C++ version of HDevelop (see section 22.2.3 on page
148) by creating a class implementing the interface and overloading its methods , , etc.
In this section, we take a closer look at exceptions in HDevEngine. The code fragments in the following stem
from the example application ErrorHandling, which provokes and catches different types of exceptions when
you press some buttons. Figure 23.4 on page 164 shows a screenshot of the application.
164 HDevEngine in .NET Applications
HDevEngine throws exceptions as instances of the class , which contains the type (category) of the exception, a
message describing the exception, and, depending on the exception type, information like the name of the executed
procedure or the HALCON error code (also see section 25.1.7 on page 202).
In the example application, the following procedure displays all the information contained in in a message box:
MessageBox.Show(FullMessage, Title);
}
This procedure is called when an exception occurs; note that the example applications described in the previous
sections only display the exception message.
try
{
HDevProgram Program = new HDevProgram(ProgramPathString);
new HDevProgramCall(Program);
}
Figure 23.5 on page 164 displays an exception that occurred because the application tried to load a non-existing
HDevelop program (category ). As you can see, only the message contains useful information in this case.
Figure 23.5: Content of the exception if an HDevelop program could not be loaded.
The next exception occurs when executing a procedure in which an input parameter is not initialized (category ):
23.2 Examples 165
Figure 23.6 on page 165 displays the content of the exception, which now contains very detailed information about
where the error occurred and why.
Figure 23.6: Content of the exception if an input parameter was not initialized.
The final exception is provoked by executing a procedure in which the call to the operator closing_circle fails
because the third parameter is not valid (category ).
HDevEngine
Figure 23.7: Content of the exception if an error occurred in a HALCON operator call.
With the method UserData (see section 25.1.7 on page 202), you can also access user exception data
that is thrown within an HDevelop program or procedure by the operator throw similarly to the operator
dev_get_exception_data.
In case of an exception (which is not caught within the procedure) the procedure call is cleaned up. This means all
subthreads are destroyed and all values of input and output parameters are cleared. Therefore, we recommend that
you always set all input parameters before executing a call even if some of them did not change.
Note that you can configure the behavior of HDevEngine when loading programs or procedures that contain invalid
lines or unresolved procedure calls with the method SetEngineAttribute (see section 25.1.1 on page 190).
166 HDevEngine in .NET Applications
Main Thread
(MultiThreadingForm)
Control Thread Processing Thread
GUI (buttons, HALCON window)
(ControlThread) (EngineThread)
initialize application
acquire images
pass image to processing thread
process image
pass results
collect results
delegate result display
display results
HALCON provides two C# example applications that use multithreading with HDevEngine/.NET:
• In MultiThreading, the application is sped up by executing the same HDevelop procedure in parallel
using two threads.
This example is described in detail in section 23.2.7.1 on page 166.
• In contrast, MultiThreadingTwoWindows executes different procedures in parallel.
This example is very similar to the previous one. Therefore, in section 23.2.7.2 on page 172 only the differ-
ences are described.
In the following, we briefly list the most important rules to observe when creating multithreaded HDevEngine ap-
plications. Also have a look at the general information about parallel programming using HALCON in section 2.2
on page 16, in particular the style guide in section 2.2.2 on page 17.
• When multiple threads execute HDevelop programs in parallel, each thread must create its own instance
of the corresponding .
• External procedure path and the implementation of HDevelop’s display operators are always set glob-
ally for all instances of HDevEngine. We recommend setting them via a separate HDevEngine instance to
keep the code more readable.
The example application MultiThreading presented in this section exploits multi-core or multi-processor systems
by executing the same HDevelop procedure (task) in parallel by two threads. The procedure finds bottle caps using
shape-based matching.
Figure 23.8 on page 166 shows an overview of the structure of the application. It consists of four threads: The
main thread (i.e., the form) is in charge of the graphical user interface (GUI), which is depicted in figure 23.9 on
page 167. It consists of a HALCON window for the display of results and buttons to initialize, start, and stop the
application.
The main thread also initializes the application by training the shape model via an HDevelop procedure and by
creating and initializing the other three threads: two processing threads and the so-called control thread, which
controls the two processing threads.
The control thread acquires the images and passes them to the processing threads, which then process the images
and pass back the results. The control thread collects the results, but does not display them itself, because all
activities in the HALCON window must be performed by the thread that created it, i.e., the main thread.
Now, we take a closer look at the corresponding code. Please note that we do not show all details; in particular,
error handling, and termination including memory management are left out.
23.2 Examples 167
Initialization
The application is initialized in the event handler of the Init button (file: MultiThreadingForm.cs).
HOperatorSet.SetSystem("parallelize_operators", "false");
First, the automatic operator parallelization is switched off, otherwise the two mechanisms (multithreading and
operator parallelization) would use more than the available number of cores / processors and thus slow down
the application instead of speeding it up (see the style guide in section 2.2.2 on page 17). If you have a system
with more than two cores or processors, you can consider to allocate some of them to the automatic operator
parallelization as described in section 2.5.1 on page 19.
HDevEngine
Step 2: Set external procedure path
Then, we create an instance of and set the path for searching the HDevelop procedures (code for constructing the
path omitted). If the external procedure is from a procedure library, the external procedure path may include the
name of the library file.
HDevProcedureCall ProcTrain;
ModelID = ProcTrain.GetOutputCtrlParamTuple("ModelID");
ModelContours = ProcTrain.GetOutputIconicParamXld("ModelContours");
The main thread creates and initializes two instances of this class and also stores their events (file:
MultiThreadingForm.cs).
An EngineThread initializes itself by creating the procedure call for detecting the caps in the images. Because
the input parameters of the procedure that concern the shape model are the same for each call, they can be set once
in advance (file: EngineThread.cs).
Image Processing
When you click the Run button, the application starts to process images in a loop.
Step 1: Starting the processing threads and the control thread
First, the main thread starts the processing engines (file: MultiThreadingForm.cs).
The corresponding method creates and starts their thread and sets the “ready” signal (file: EngineThread.cs).
Then, the main thread starts the control thread (file: MultiThreadingForm.cs):
HDevEngine
EngineThread WorkerEngine; // Variable to switch between processing threads.
Image = AcqHandle.GrabImageAsync(-1);
WorkerEngine.SetImage(Image);
Then, it acquires the next image and passes it to the engine, which stores it in a member variable (file:
EngineThread.cs).
170 HDevEngine in .NET Applications
ProcCall.SetInputIconicParamObject("Image", InputImage);
ProcCall.Execute();
After executing the procedure, the processing thread accesses its results and stores them in a new instance of the
result class (“result container”), together with the processed image.
ResultContainer Result;
HTuple ResultTuple;
The processing thread then passes the result container to the control thread by appending it to a list.
ResultMutex.WaitOne();
ResultList.Add(Result);
ResultMutex.ReleaseMutex();
This list is a member variable of the main thread (file: MultiThreadingForm.cs). It is protected by a mutex so
that the threads can access it safely.
23.2 Examples 171
public MultiThreadingForm()
{
ResultDataMutex = new Mutex();
ResultList = new ArrayList();
}
The processing threads store references to the list and to the mutex in own member variables (file:
EngineThread.cs).
ArrayList ResultList;
Mutex ResultMutex;
InputImage = null;
this.EngineIsReady.Set();
Result Display
Step 1: Checking whether new results are available
Let’s return to the action method (Run) of the control thread (file: MultiThreadingForm.cs). After triggering a
processing thread by passing the image to process, it checks whether the result list contains new items.
ResultDataMutex.WaitOne();
HDevEngine
Count = ResultList.Count;
ResultDataMutex.ReleaseMutex();
public MultiThreadingForm()
{
DelegatedDisplay = new FuncDelegate(DisplayResults);
}
Note that all HALCON visualization operators are automatically delegated to the correct thread as described in
chapter section 2.3 on page 18.
172 HDevEngine in .NET Applications
Window.ClearWindow();
Window.DispImage(Result.InputImage);
Window.DispObj(Result.FoundContours);
Result.InputImage.Dispose();
Result.FoundContours.Dispose();
}
In contrast to the previous section, the example application MultiThreadingTwoWindows presented here executes
different HDevelop procedures (tasks) in parallel by two threads. One task is to find bottle caps using shape-based
matching, the other to read ECC 200 data codes.
Figure 23.10 on page 173 shows an overview of the structure of the application. Like the application described in
the previous section, it consists of four threads: The main thread (i.e., the form) is in charge of the graphical user
interface (GUI), which is depicted in figure 23.9 on page 167. It consists of a HALCON window for the display of
results and buttons to initialize, start, and stop the application.
The main thread also initializes the application by creating and initializing the other three threads: two processing
threads and the so-called control thread, which controls the two processing threads. In contrast to the previous
application, here the processing threads initialize the image processing tasks by training the shape model and the
data code model, respectively, via HDevelop procedures.
The control thread acquires the images and passes them to the processing threads, which then process the image and
pass back the results. The control thread collects the results, but does not display them itself, because all activities
in the HALCON window must be performed by the thread that created it, i.e., the main thread. In contrast to the
previous application the results of the two tasks are displayed in two separate windows.
Below, we take a closer look at the corresponding code, restricting ourselves, however, to the parts that are different
to the previous application.
Initialization
As in the previous example, the application is initialized in the event handler of the Init button (file:
MultiThreadingTwoWindowsForm.cs).
Step 1: Create and initialize the processing engines
The processing engines are created and initialized similarly to the previous example, with some exceptions: First,
the shape and the data code model are now trained by the processing threads instead of the control thread (see the
step below). Secondly, the processing engines now also have a variable that indicates “their” HALCON window
(file: EngineThread.cs).
Main Thread
Processing Thread
(MultiThreadingTwoWindowsForm)
Control Thread (EngineThread)
GUI (buttons, HALCON window)
(ControlThread)
initialize application initialize task
acquire images
pass image to processing thread
process image
pass results
collect results
delegate result display
display results
HDevEngine
The control thread sets this variable after creating the engines (file: MultiThreadingTwoWindowsForm.cs).
WorkerEngine1.Init("shape");
...
WorkerEngine2.Init("datacode");
The HDevelop procedures for training the models and for performing the image processing have similar names for
the two tasks, so that their names can be generated automatically (file: EngineThread.cs). The task name itself
is stored in a variable of the class EngineThread.
this.Task = Task;
Then, the model of the shape or datacode, respectively, is trained by executing the corresponding HDevelop pro-
cedure and the returned model data is stored in variables of the class.
HDevProcedure Procedure = new HDevProcedure(TrainMethod);
ProcTrain = new HDevProcedureCall(Procedure);
ProcTrain.Execute();
ModelID = ProcTrain.GetOutputCtrlParamTuple("ModelID");
if (Task.Equals("shape"))
{
ModelContours = ProcTrain.GetOutputIconicParamXld("ModelContours");
}
Image Processing
Step 1: Triggering the processing threads
The control thread’s action is contained in the method Run (file: MultiThreadingTwoWindowsForm.cs). As
long as the Stop is not pressed, it checks whether the processing engines are ready and, if this is the case, acquires
23.2 Examples 175
After executing the procedure, the processing thread accesses its results and stores them in a new instance of the
result container, together with the processed image and the window index.
HDevEngine
ResultContainer Result;
Result Display
As in the previous example, the display of results is performed by the main thread in the method ResultDisplay
(file: MultiThreadingTwoWindowsForm.cs). The main difference is that the display now is switched between
the two HALCON windows, based on the variable in the result container.
176 HDevEngine in .NET Applications
if (Result.WindowIndex == 1)
{
Window = Window1;
}
else
{
Window = Window2;
}
Furthermore, the display method now checks the success of the image processing to avoid accessing non-existing
result elements. For both tasks, the resulting contours, i.e., the found shape or data code region, respectively, are
displayed. For the data code task, also the read code is displayed.
Window.ClearWindow();
Window.DispImage(Result.InputImage);
if (Result.DetectionSuccessful)
{
Window.DispObj(Result.FoundContours);
// Additional display for data code result: code.
if (Result.WindowIndex == 2)
{
Row = (int)Result.ResultData[0].D;
Col = (int)Result.ResultData[1].D;
Window.SetTposition(Row, Col);
Window.WriteString((string)Result.ResultData[2].S);
}
}
else
{
Window.SetColor("red");
Window.SetTposition(20, 20);
Window.WriteString("Detection failed!");
Window.SetColor("green");
}
The example application UseVectorVariables shows how to load and execute an HDevelop example that con-
tains vector variables in HDevengine/C#. In the example two vectors are used for processing: one containing the
input images and one containing scaling factors. When executing the program the gray values of the input images
are scaled according to the scaling factors. Please have a look at the source file UseVectorVariablesForm.cs
for more details on how to work with vector variables in HDevengine/.NET.
The just-in-time compilation of procedures needs to be enabled in your instance of the class:
...
Engine = new HDevEngine();
Procedures (and procedures referenced by it) are compiled at the moment a corresponding instance of or is
created.
23.3 Using the Just-in-time Compiler With HDevEngine/.NET 177
You can also explicitly pre-compile all used procedures of a HDevelop program or procedure using the method
CompileUsedProcedures of or , respectively.
In the following example, all used procedures of a procedure call are just-in-time compiled:
HDevEngine
178 HDevEngine in .NET Applications
HDevEngine In Python Applications 179
Chapter 24
This chapter explains how to use HDevEngine in Python applications. Section 24.1 on page 179 quickly sum-
marizes some basic information about creating HDevEngine applications with Python. Section 24.3 on page 180
provides a more comprehensive overview.
24.1 Introduction
The HDevEngine/Python interface is similar to the HDevEngine/.NET and HDevEngine/C++ interface. Most
concepts and functions have a one-to-one mapping.
A short reference of the C++ classes for the HDevEngine can be found in section 25.1 on page 189. The Python
classes are similar.
This chapter only describes HDevEngine/Python specifics. If a topic e.g., error handling is not mentioned, the
relevant part in Part IV on page 93 applies.
This section explains how to create a simple HDevEngine/Python application. For a more comprehensive descrip-
tion, read section 24.3 on page 180.
HDevEngine
1. Install HALCON 24.11.
2. Install Python 3.8 or newer on your system.
3. Set up your Python environment of choice, e.g., using python -m venv
path_to_new_virtual_environment
4. Run the following commands in a shell:
mkdir hdevengine_example
cd hdevengine_example
pip install mvtec-halcon==24111
import os
import halcon as ha
if __name__ == '__main__':
example_dir = ha.get_system_s('example_dir')
procedure_path = os.path.join(example_dir, 'hdevengine', 'procedures')
hdev_engine = ha.HDevEngine()
hdev_engine.set_procedure_path(procedure_path)
img = ha.read_image('fin2')
procedure = ha.HDevProcedure.load_external('detect_fin')
proc_call = ha.HDevProcedureCall(procedure)
proc_call.set_input_iconic_param_by_name('Image', img)
proc_call.execute()
fin_area = proc_call.get_output_control_param_by_name('FinArea')[0]
print(f'Fin Area: {fin_area}')
6. To run the application, type the following command in the same shell:
python hdevengine_example.py
As as result, you should see the following output ’Fin Area: 1634’.
No HDevEngine-specific actions are required. For more information, see section 14.2 on page 95.
While you can have multiple Python instances of HDevEngine/Python, they all share the same implementation as
a mutable singleton.
This mostly affects configuration. Specific program and procedure call instances are more or less independent
from each other.
Here HALCON is queried for the example directory path, based on which the path containing the ’detect_fin’
procedure is constructed. Then an HDevEngine instance is initialized and the procedure search path set to it.
example_dir = ha.get_system_s('example_dir')
procedure_path = os.path.join(example_dir, 'hdevengine', 'procedures')
hdev_engine = ha.HDevEngine()
hdev_engine.set_procedure_path(procedure_path)
24.3.1.1 Attributes
These functions let you set specific attributes. For example, by default, the attribute ’ignore_invalid_results’
is set to true. This means that by default, an empty region object or an empty tuple is returned if a variable
or parameter is queried that was not previously set by the program or procedure. Think of it like this: Should
accessing an uninitialized variable return a default or should it raise an exception?
hdev_engine = ha.HDevEngine()
assert hdev_engine.get_attribute('ignore_invalid_results') == 1
hdev_engine.set_attribute('ignore_invalid_results', 0)
assert hdev_engine.get_attribute('ignore_invalid_results') == 0
HDevEngine
These functions let you start and stop the server required for debugging the engine execution. You can control the
port via the attribute ’debug_port’.
HDevEngine
These functions let you set and extend the list of paths searched when trying to load a procedure.
HDevEngine
HDevEngine
def get_procedure_names(self) -> List[str]:
def get_loaded_procedure_names(self) -> List[str]:
def get_global_control_var_names(self) -> List[str]:
def get_global_iconic_var_dimension(self, name: str) -> int:
def get_global_control_var_dimension(self, name: str) -> int:
These functions let you query global metadata, such as which procedures are loaded, the vector dimensions of
global variables, and more.
HDevEngine
These functions let you read and write global variables, both iconic and control.
procedure = ha.HDevProcedure.load_external('detect_fin')
proc_call = ha.HDevProcedureCall(procedure)
proc_call.set_input_iconic_param_by_name('Image', img)
proc_call.execute()
fin_area = proc_call.get_output_control_param_by_name('FinArea')[0]
print(f'Fin Area: {fin_area}')
HDevProcedure
@staticmethod
def load_external(name: str) -> 'HDevProcedure':
@staticmethod
def load_local(
program: Union[HDevProgram, str],
name: str
) -> 'HDevProcedure':
Procedures are loaded via these static methods. Use only these functions to initialize HDevProcedure instances.
hdev_engine.set_procedure_path(proc_dir)
external_proc = ha.HDevProcedure.load_external('detect_fin')
While Python allows calling static methods on instances, e.g.: ha.HDevProcedure().load_external this is
not recommended as it needlessly wastes resources.
HDevEngine
These functions let you unload procedures again, once they are loaded. For example, this can be useful to free up
unused memory.
24.3 HDevEngine/Python Interface 183
HDevProcedure
- name : str
- short_description : str
- loaded : bool
- input_iconic_param_names : List[str]
- output_iconic_param_names : List[str]
- input_control_param_names : List[str]
- output_control_param_names : List[str]
- input_iconic_param_dimensions : List[int]
- output_iconic_param_dimensions : List[int]
- input_control_param_dimensions : List[int]
- output_control_param_dimensions : List[int]
HDevProcedure
HDevProcedure
HDevEngine
Compile all procedures that are used by the program and that can be compiled with a just-in-time compiler. Pro-
cedures that could not be compiled are called by the HDevEngine interpreter in the usual way. To check which
procedure could not be compiled and what the reason is for that, start HDevelop and check the compilation states
there.
This functions returns whether all used procedures were JIT compiled.
proc_call = ha.HDevProcedureCall(procedure)
The only way to initialize an HDevProcedureCall instance is using a loaded HDevProcedure instance.
184 HDevEngine In Python Applications
HDevProcedureCall
These functions let you set input parameters. We recommend always setting all input parameters again every time
you want to execute the procedure call. This helps make your code more robust in the face of error conditions.
Indices here start at 1 instead of 0.
24.3.2.7 Execution
HDevProcedureCall
Use this function when you have set all input parameters to execute the procedure.
HDevProcedureCall
Use these functions to read output parameters after the call to execute has finished successfully.
Indices here start at 1 instead of 0.
HDevProcedureCall
24.3.2.10 Reseting
HDevProcedureCall
This is mainly for situations when you want to abort execution from another thread or possibly free native resources
even while some instances are still alive.
24.3 HDevEngine/Python Interface 185
The general concept behind calling HDevelop programs from Python is as follows:
example_dir = ha.get_system_s('example_dir')
program_path = os.path.join(
example_dir,
'hdevelop',
'Transformations',
'Poses'
)
pose = program_call.get_control_var_by_name('PoseComposeAlternative')
rounded_pose = [round(x, 8) for x in pose]
Programs are loaded via the initializer of HDevProgram, which expects a full path to an HDevelop program in the
format of the operating system, including file name.
HDevEngine
Access program metadata via these read-only member variables:
HDevProgram
- name : str
- loaded : bool
- inconic_var_names : List[str]
- control_var_names : List[str]
- inconic_var_dimensions : List[int]
- control_var_dimensions : List[int]
HDevProgram
HDevProgram
Compile all procedures that are used by the program and that can be compiled with a just-in-time compiler. Pro-
cedures that could not be compiled are called by the HDevEngine interpreter in the usual way. To check which
procedure could not be compiled and what the reason is for that, start HDevelop and check the compilation states
there.
Returns whether all used procedures were JIT compiled.
program_call = ha.HDevProgramCall(program)
The only way to initialize an HDevProgramCall instance is using a valid HDevProgram instance.
24.3.3.5 Execution
HDevProgramCall
HDevProgramCall
Use these functions to read variables after the call to execute has finished successfully.
Indices here start at 1 instead of 0.
HDevProgramCall
24.3.3.8 Reseting
HDevProgramCall
This is mainly for situations when you want to abort execution from another thread or possibly free native resources
even while some instances are still alive.
Inside HDevelop, dev_* operators can be used for convenience. When embedding an HDevelop program or proce-
dure inside your application, the potential dev_* operator calls have no straightforward mapping. It might be desir-
able to for example map dev_* operator calls to visualization within your application. Thus, HDevEngine/Python
provides a base class, which you can inherit from and overwrite with logic appropriate for your application.
Take for example this simple HDevelop program, which reads an image and then displays this PCB image in a dev
window.
read_image(Image, 'pcb')
dev_display(Image)
By default, this program will not open a window when using HDevEngine/Python. However, you can specify your
own logic of what should happen when dev_display is called.
For example, this Python code registers a very basic implementation of dev_display.
class DevImpl(ha.HDevOperatorBase):
@staticmethod
def dev_display(object):
print(object)
hdev_engine = ha.HDevEngine()
hdev_engine.set_hdev_operator_impl(DevImpl())
To get an overview which dev_* operators are available and which signatures each of them expects, take a look at
the implementation of HDevOperatorBase.
HDevEngine
Note that only one implementation can be registered at a time. This applies to all current and future HDevEngine
instances, until changed.
By default no implementation is registered. Once you have registered an implementation you can return to the
default behavior by calling:
hdev_engine.unset_hdev_operator_impl()
Note that calling register_dev_operators might have surprising lifetime effects on your Python variables. See
the documentation of said function for more details.
Every function that was not overwritten by your implementation of HDevOperatorBase will raise an exception if
called.
It is safe to raise exceptions from within Python code implementing dev_* operators. However, only a generic
HDevEngineError will be raised and the original exception traceback will be logged to stderr. This is due to
technical limitations.
HDevEngine/Python maps HALCON vectors to nested Python lists. There are two separate, incompatible types
of vectors: tuple_vector and iconic_vector. The following examples demonstrate the Python representation
that is used to read and write HALCON vectors in HDevEngine/Python:
188 HDevEngine In Python Applications
empty_tuple_vector = ha.HDevEmptyVector(dimension=1)
1d_tuple_vector = [[23, 'a'], ['ec', 2.5, 77]]
2d_tuple_vector = [[[8], ['b', 'c']], [], [[]]]
empty_iconic_vector = ha.HDevEmptyVector(dimension=1)
1d_iconic_vector = [img1, img2, img3]
2d_iconic_vector = [[img1, img2], [img1, img3, img4], []]
[ [234], [2, 5] ] # ok
[ 234, [2, 5] ] # not ok
24.3.6 Multithreading
Because HDevEngine is a mutable singleton, some functionality affects your entire application:
A multi-threaded application must take care when working with this sort of shared mutable state. For example,
you cannot safely load multiple procedures in parallel using the global procedure path if they require different path
settings, without synchronizing appropriately inside your application. Not applying the required care will lead to
undefined behavior, including crashes and worse.
To avoid the aforementioned issues, we recommend configuring HDevEngine, as well as loading procedures and
programs, at the beginning of your program before starting additional application threads.
In contrast to HDevEngine, HDevProcedure, and HDevProgram, the call instances HDevProcedureCall and
HDevProgramCall are independent from each other.
General Information 189
Chapter 25
General Information
This chapter contains an overview about the main classes of HDevEngine and their methods (section 25.1 on
page 189) and miscellaneous application tips (section 25.3 on page 205). Remote debugging of HDevEngine
applications from HDevelop is described in section 25.2 on page 203.
Note in the following, we print only the declaration of the classes for HDevEngine/C++. In the other variants of
HDevEngine, the methods and properties have the same names.
HDevEngine
190 General Information
25.1.1
.NET:
*****************************************************************************
** class HDevEngine
**===========================================================================
** Class for managing global engine settings:
** + external procedure path
** + implementation of dev_ operators (HDevOperatorImpl)
** + Attention: all changes made to one HDevEngine instance are global
** for all .dev programs or .dvp procedure that are executed in one
** application
*****************************************************************************
*****************************************************************************/
class LIntExport HDevEngine
{
public:
HDevEngine();
(continued declaration of )
// "docu_language" [default: "" -> en_US]
// - could be set to "en_US","de_DE", other languages
// "docu_encoding" [default: "" -> "utf8"]
// - if set to "native" all natural language strings are converted
// to native encoding
// "execute_procedures_jit_compiled" [default: false, 0]
// - if set to true (or "true"), procedures are tried to being compiled
// with a just-in-time compiler for faster execution
// "debug_port" [default: 57786]
// - specifies the port number of the socket where the debug server
// waits for incoming connections
// "debug_password" [default: ""]
// - specifying a password provides a basic layer of protection
// against misuse. For security reasons, it is highly recommended
// to always supply a password. If a password is set, it must be
// entered in HDevelop to allow the connection
// "debug_wait_for_connection" [default: false]
// - if set to true, the engine switches into "stopped state"
// after starting the debug server (see below). This has the effect
// that any application thread that enters procedure execution
// via HDevEngine will stop on the first line of script code.
// This way, you can start debugging from the beginning of your code
// upon connecting from HDevelop
void SetEngineAttribute(const char* name, const HalconCpp::HTuple& value);
HalconCpp::HTuple GetEngineAttribute(const char* name);
HDevEngine
void AddProcedurePath(const wchar_t* path);
#endif
// Get names of all available external procedures
HalconCpp::HTuple GetProcedureNames() const;
// Get names of all loaded external procedures
HalconCpp::HTuple GetLoadedProcedureNames() const;
// Unload a specific procedure <proc_name>
void UnloadProcedure(const char* proc_name);
// Unload all external procedures
void UnloadAllProcedures();
(continued declaration of )
// global variable access
HalconCpp::HTuple GetGlobalIconicVarNames() const;
HalconCpp::HTuple GetGlobalCtrlVarNames() const;
// get dimension of a global variable
int GetGlobalIconicVarDimension(const char* var_name) const;
int GetGlobalCtrlVarDimension(const char* var_name) const;
// get value of a global variable
HalconCpp::HObject GetGlobalIconicVarObject(const char* var_name);
HalconCpp::HTuple GetGlobalCtrlVarTuple(const char* var_name);
HalconCpp::HObjectVector GetGlobalIconicVarVector(const char* var_name);
HalconCpp::HTupleVector GetGlobalCtrlVarVector(const char* var_name);
// these method is provided for efficiency:
// the results are copied directly into the tuple variable provided by
// the user without additional copying
void GetGlobalCtrlVarTuple(const char* var_name, HalconCpp::HTuple* tuple);
// set global variable
void SetGlobalIconicVarObject(const char* var_name, const HalconCpp::HObject& obj);
void SetGlobalCtrlVarTuple(const char* var_name, const HalconCpp::HTuple& tuple);
void SetGlobalIconicVarVector(const char* var_name, const HalconCpp::HObjectVector& vector);
void SetGlobalCtrlVarVector(const char* var_name, const HalconCpp::HTupleVector& vector);
25.1.2
.NET:
*****************************************************************************
** class HDevProgram
**===========================================================================
** Class for managing HDevelop programs
*****************************************************************************
class LIntExport HDevProgram
{
public:
// Create a program from a .dev program file
HDevProgram(const char* file_name = NULL);
#ifdef _WIN32
HDevProgram(const wchar_t* file_name);
#endif
// Copy constructor
HDevProgram(const HDevProgram& hdev_prog);
HDevProgram(const Data& data);
// Assignment operation
HDevProgram& operator=(const HDevProgram& hdev_prog);
// Destructor
virtual ~HDevProgram();
#ifdef _WIN32
void LoadProgram(const wchar_t* file_name);
#endif
HDevEngine
// Get the names of all local and the used external procedures
HalconCpp::HTuple GetUsedProcedureNames() const;
HalconCpp::HTuple GetLocalProcedureNames() const;
// Compile all procedures that are used by the program and that can be
// compiled with a just-in-time compiler.
// The method returns true when all used procedures could be compiled by the
// just-in-time compiler.
// Procedures that could not be compiled are called normally by the
// HDevEngine interpreter.
// To check which procedure could not be compiled and what the reason is for
// that start HDevelop and check there the compilation states.
bool CompileUsedProcedures();
(continued declaration of )
// get some information about the variables of the program's main procedure:
// - get the variable names as a tuple
HalconCpp::HTuple GetIconicVarNames() const;
HalconCpp::HTuple GetCtrlVarNames() const;
25.1.3
.NET:
*****************************************************************************
** class HDevProgramCall
**===========================================================================
** Class for managing the execution of an HDevelop program
*****************************************************************************
class LIntExport HDevProgramCall
{
public:
// Create an empty HDevelop program call instance
HDevProgramCall();
// Create an HDevelop program call from a program
HDevProgramCall(const HDevProgram& prog);
// Copy constructor
HDevProgramCall(const HDevProgramCall& hdev_prog_call);
HDevProgramCall(const Data& data);
// Assignment operation
HDevProgramCall& operator=(const HDevProgramCall& hdev_prog_call);
// Destructor
virtual ~HDevProgramCall();
// Execute program
void Execute();
HDevEngine
// (indices of the variables run from 1 to count)
HalconCpp::HObject GetIconicVarObject(size_t var_idx);
HalconCpp::HObject GetIconicVarObject(const char* var_name);
(continued declaration of )
25.1.4
.NET:
*****************************************************************************
** class HDevProcedure
**===========================================================================
** Class for managing HDevelop procedures
*****************************************************************************
class LIntExport HDevProcedure
{
public:
// Create HDevelop procedure from external or local procedure
HDevProcedure(const char* proc_name = NULL);
HDevProcedure(const char* prog_name, const char* proc_name);
HDevProcedure(const HDevProgram& prog, const char* proc_name);
#ifdef _WIN32
HDevProcedure(const wchar_t* prog_name, const char* proc_name);
#endif
// Copy constructor
HDevProcedure(const HDevProcedure& hdev_proc);
HDevProcedure(const Data& data);
// Assignment operation
HDevProcedure& operator=(const HDevProcedure& proc);
// Destructor
~HDevProcedure();
#ifdef _WIN32
void LoadProcedure(const wchar_t* prog_name, const char* proc_name);
#endif
HDevEngine
// Get the name of the procedure
const char* GetName() const;
(continued declaration of )
// Compile all procedures that are used by the procedure and that can be
// compiled with a just-in-time compiler.
// The method returns true when all used procedures could be compiled by the
// just-in-time compiler.
// Procedures that could not be compiled are called normally by the
// HDevEngine interpreter.
// To check which procedure could not be compiled and what the reason is for
// that start HDevelop and check there the compilation states.
bool CompileUsedProcedures();
(continued declaration of )
HDevEngine
200 General Information
25.1.5
.NET:
*****************************************************************************
** class HDevProcedureCall
**===========================================================================
** Class for executing an HDevelop procedure and managing the parameter
** values
*****************************************************************************
class LIntExport HDevProcedureCall
{
public:
// Create an empty HDevelop procedure call instance
HDevProcedureCall();
// Create HDevelop procedure call instance
HDevProcedureCall(const HDevProcedure& hdev_proc);
// Copy constructor
HDevProcedureCall(const HDevProcedureCall& hdev_proc_call);
HDevProcedureCall(const Data& data);
// Assignment operation
HDevProcedureCall& operator=(const HDevProcedureCall& hdev_proc_call);
// Destructor
~HDevProcedureCall();
// Execute program
void Execute();
(continued declaration of )
Note that HDevEngine/.NET provides additional methods that return iconic output parameters of a procedure call
in the corresponding class (, , ).
HDevEngine
202 General Information
25.1.6
.NET:
*****************************************************************************
** class HDevOperatorImplCpp
**===========================================================================
** Class for the implemention of HDevelop internal operators
*****************************************************************************
class LIntExport HDevOperatorImplCpp
{
public:
HDevOperatorImplCpp();
// Copy constructor
HDevOperatorImplCpp(const HDevOperatorImplCpp& hdev_op_impl);
HDevOperatorImplCpp(const Data& data);
// Assignment operation
HDevOperatorImplCpp& operator=(const HDevOperatorImplCpp& hdev_op_impl);
// Destructor
virtual ~HDevOperatorImplCpp();
25.1.7
.NET:
25.2 Debugging HDevEngine From HDevelop 203
*****************************************************************************
** class HDevEngineException
**===========================================================================
** Class for HDevelop engine exceptions
*****************************************************************************
class LIntExport HDevEngineException
{
public:
// Exception categories
enum ExceptionCategory
{
Exception, // Generic
ExceptionInpNotInit, // Error input parameters not initialized
ExceptionCall, // Error HALCON or HDevelop operator call
ExceptionFile // Error opening or reading HDevelop file
};
// Error text
const char* Message() const;
// Category of exception
ExceptionCategory Category() const;
const char* CategoryText() const;
// Name of executed procedure
const char* ExecProcedureName() const;
// Number of executed procedure or operator program line
int ProgLineNum() const;
// Name of executed procedure or operator program line
const char* ProgLineName() const;
// HALCON error code
Herror HalconErrorCode() const;
HDevEngine
void UserData(HalconCpp::HTuple& user_Data) const;
};
HDevEngine provides two member functions to start and stop the debug server.
MyEngine.StartDebugServer();
...
MyEngine.StopDebugServer();
Usually, HDevEngine executes HDevelop code continuously without any interruption. However, once the debug
server has started, the execution of HDevelop code can be interrupted for debugging purposes.
There are multiple ways for HDevEngine to enter a stopped state. The first two are available through the API.
They work regardless of whether HDevelop is actually attached. Please note that the only way to continue program
execution is to actually attach HDevelop to the debug server and control the execution from there.
Other ways to stop the program execution are triggered only if HDevelop is attached to the debug server:
• A Stop command (F9 ) is sent from HDevelop.
• An activated break point on a program line or variable is reached by HDevEngine.
• An unhandled error occurs. Normally, HDevEngine would throw a HDevException in this case, but in
debug mode a notification is sent out to HDevelop so that the error condition can be examined there. The
delayed exception will be thrown when the program execution continues.
Regardless of the reason the stopped state is always global, i.e., other application threads will also stop when
executing HDevelop code.
25.3 Tips and Tricks 205
Like any remotely accessible server, careful attention must be paid to prevent unauthorized access to the debug
server. Although the firewall must be configured to allow connections to the configured port, it is your responsibil-
ity to limit the access to authorized clients only.
As a minimal security measure, always set up a password for the debug server. Please note that the debug server
itself provides no measures against brute-force or denial-of-service attacks.
Note the following if the debug server is running and no password is set:
Apart from the transmission of passwords, the communication between HDevelop and the debug server is not
encrypted. Protected procedures are transmitted in their encrypted binary form. If you worry about other sensitive
data like images, you should use a VPN (e.g., an SSH tunnel) when connecting from the outside to the local
network.
25.2.4 Limitations
Further limitations of remote debugging from the HDevelop side are listed in the HDevelopUser’s Guide, sec-
tion 9.9 on page 302.
25.3.1 Troubleshooting
? Executed program or procedure raises exception for display operators like set_tposition when not
using implementation of display operators
If you are not using an implementation of HDevelop’s internal display operators (dev_*), calls to these
HDevEngine
operators in the executed HDevelop program or procedure are simply ignored. However, if the program or
procedure contains other, “external” display operators like set_tposition or write_string, which need
a window handle as input parameter, the program / procedure will raise an exception at this operator if the
window handle has not been instantiated.
Typically, this problem will not arise when executing programs, because you will in most cases use an
implementation of the display operators. When executing procedures, we recommend that you leave out
the external display operators that use window handles. If this is not possible, you could place them in a
separate procedure and use the implementation of display operators for just this procedure. Alternatively,
initialize the window handle with a value like -1 and test it before executing the external display operators.
To ensure that programs developed with HDevelop can be executed with HDevEngine without any further action,
all standard procedures (see the HDevelopUser’s Guide, section 5.4 on page 45) are automatically loaded when
HDevEngine is started.
In most applications there is no need to delete loaded HDevelop procedures explicitly using . Possible reasons
might be to free memory or to reload a procedure from a procedure or library file that was changed on disk.
206 General Information
Please note that when creating a procedure with the class , the procedure is loaded and copied together with all
the procedures it uses, and will not be affected by further calls to unload a procedure. For library procedures the
entire library will be unloaded. For non-library external procedures, deletes only the specified procedure. In both
cases dependent procedures will not be unloaded automatically. To delete the automatically loaded procedures,
you can query their names using and then delete them (if you are sure that they are not used by another loaded
procedure!), or you can use to unload all external procedures. Note that after calling or , still returns the names
of the unloaded procedures.
Index 207
Index
Index
Index
UTF-8 encoding (HALCON/Python), 104
parallel programming (HDevEngine)
overview, 140 vectors (HALCON/.NET), 78
parallel programming (HDevEngine/.NET), 166 vectors (HALCON/C), 117
parallel programming (HDevEngine/C**), 152 vectors (HALCON/C++), 48
parallel programming design issues, 17 vectors (HDevEngine/Python), 187
parallel programming with HALCON Visual Basic .NET application
example, 18 example, 86
overview, 16 visualization (HALCON/.NET), 80
parallelize operators on channel level, 15
parallelize operators on domain level, 15
parallelize operators on internal data level, 15
parallelize operators on tuple level, 15
parameters (HALCON/C++), 37
procedural HALCON/C++, 35
procedures (HDevEngine/Python), 182
programs (HDevEngine/Python), 185