Skip to content

Working with the C++ and .NET interfaces🔗

Note

This section describes how to use HALCON’s interfaces in unmanaged C++ or .NET (managed C++, C#, or Visual Basic .NET).
For HALCON/Python, see the corresponding section.

How to call operators🔗

How a HALCON operator can be called via the HALCON/C++ interface is described in detail in the operator’s reference entry. As an example, the following code snippet shows parts of the entry for the operator MeanImage:

Head and parts of the parameter section of the reference entry for MeanImage

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* / vector_field) *allowed for compute devices
Image to be smoothed

ImageMean (output_object)
(multichannel-)image(-array) → HObject (byte / int2 / uint2 / int4 / int8 / real / vector_field)
Smoothed image

Note

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.

How a HALCON operator can be called via the HALCON/.NET interface is described in detail in the operator’s reference entry. As an example, the following code snippet shows parts of the entry for the operator GrabImage:

Head and parts of the parameter section of the reference entry for GrabImage

static voidHOperatorSet.GrabImage(out HObject image, HTuple acqHandle)

voidHImage.GrabImage(HFramegrabber acqHandle)

HImage HFramegrabber.GrabImage()


image (output_object)
image → HImage (byte / uint2)

acqHandle (input_control)
framegrabber → HFramegrabber / HTuple (IntPtr)

The operator can be called via three classes: HOperatorSet, HImage, and HFramegrabber.

Note

The first variant, via HOperatorSet, is mainly used for the export of HDevelop programs.

For normal applications, we recommend calling operators via the other classes (here: HImage or 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

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. You can call them directly via the class and do not need an instance:

double  s1, s2;

s1 = HSystem.CountSeconds();

In the operator reference, these operator calls start with the keyword static:

static void HOperatorSet.CountSeconds (out HTuple seconds)
static double HSystem.CountSeconds ()

About parameters🔗

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, for example, to display an image in it.
Besides, handles are used when operators share complex data, for example, the operators for shape-based matching which create and then use the model data, or for accessing input/output devices, for example, image acquisition devices.
For more information, see Classes encapsulating handles.

Both iconic and control parameters can appear as input and output parameters of a HALCON operator. For example, the operator MeanImage expects one iconic input parameter, one iconic output parameter, and two input control parameters.
FindBarCode is an example of an operator that has all four parameter types.

Some parameters “disappear” from within the parentheses if you call an operator via a class. This mechanism is described in more detail below.

HALCON’s philosophy regarding parameters demands that input parameters are not modified by an operator. As a consequence, they are passed by value (for example, Hlong MaskWidth in the example above) or via a constant reference (for example, const HObject& Image). This philosophy also holds if an operator is called via a class, with the calling instance acting as an input parameter. In the following example code, the original image hence is not modified by the call to MeanImage. Instead, the result of the operator call (that is, 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, and therefore must be passed by reference.

Important

Operators expect a pointer to an already existing variable or class instance.

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;

HRegion code_region = barcode.FindBarCode(image, "EAN-13", &result);

The example shows another interesting aspect of output parameters: When calling operators via classes, one output parameter may become the return value (see About classes and instances for more information). Here, 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 the example above). In this case, an array of smoothed images is returned.
This is called the tuple mode.

String parameters

Regardless of the encoding of the HALCON library (compare set_system('filename_encoding', ...)) the HALCON/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. By default, these strings are 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().

Switching the interface encoding back and forth is not recommended. The setting should be adjusted only once at the very beginning of the program (before the first HALCON operator or assignment), because HTuple instances cannot store in which encoding the contained strings are present. This means, 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.

Example

In the following code, the operator InfoFramegrabber is called with two output string parameters to query the currently installed image acquisition board:

HString     sInfo, sValue;

InfoFramegrabber(FGName, "info_boards", &sInfo, &sValue);

It is also unnecessary to allocate memory for the multiple output string parameters returned as an HTuple:

HTuple      tInfo, tValues;

InfoFramegrabber(FGName, "info_boards", &tInfo, &tValues);

Both iconic and control parameters can appear as input and output parameters of a HALCON operator. For example, the operator MeanImage expects one iconic input parameter, one iconic output parameter, and two input control parameters.
FindBarCode is an example of an operator that has all four parameter types.

About classes and instances🔗

As already mentioned above, the HALCON/C++ reference shows via which classes an operator can be called. For example, FindBarCode can be called via objects of the class HImage or HBarCode (see figure 5.2). In both cases, the corresponding input parameter (Image or BarCodeHandle, respectively) does not appear within the parentheses anymore as it is replaced by the calling instance of the class (this).

There is another difference to the procedural operator signature: The first output parameter (in the example, the bar code region SymbolRegions) also disappears from within the parentheses and becomes the return value instead of the error code. For more information, see also About error handling.

The following example shows code examples for the three ways to call FindBarCode:

Using FindBarCode via HBarCode, via HImage, or in the procedural approach

HImage   image("barcode/ean13/ean1301");
HBarCode barcode{HTuple(), HTuple()};
HString  result;

HRegion code_region = barcode.FindBarCode(image, "EAN-13", &result);
HRegion code_region = image.FindBarCode(barcode, "EAN-13", &result);
HObject image;
HTuple  barcode;
HObject code_region;
HTuple  result;

ReadImage(&image, "barcode/ean13/ean1301");
CreateBarCodeModel(HTuple(), HTuple(), &barcode);
FindBarCode(image, &code_region, barcode, "EAN-13", &result);

When comparing the object-oriented and the procedural approach, you can see that the calls to the operators ReadImage and CreateBarCodeModelare replaced by special constructors for the classes HImage and HBarCode, respectively. This topic is discussed in more detail below.

Constructors

As shown in the example, the HALCON/C++ parameter classes provide additional constructors, which are based on suitable HALCON operators. The constructors for HImage and HBarCode used in the example are based on ReadImage and CreateBarCodeModel, respectively.

As a rule of thumb: If a class appears only as an output parameter in an operator, there automatically exists a constructor based on this operator. Thus, instances of HBarCode can be constructed based on CreateBarCodeModel, instances of HShapeModel based on CreateShapeModel, instances of HFramegrabber based on OpenFramegrabber, and so on.
Note that for classes where many such operators exist (for example, HImage), only a subset of commonly used operators with unambiguous parameter list are actually used as constructor.

In addition, all classes have empty constructors to create an uninitialized object. For example, you can create an instance of HBarCode with the default constructor and then initialize it using CreateBarCodeModel as follows:

HBarCode barcode;
barcode.CreateBarCodeModel(HTuple(), HTuple());

If the instance was already initialized, the corresponding data structures are automatically destroyed before constructing and initializing them anew (see also Destructors below). For more information about the handle classes, see also Other handle classes.

HImage image;             // still uninitialized
image.ReadImage("clip");

In brief, the most important classes are the following:

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, that is, the calling instance is modified. In addition, the corresponding handle is returned.
For more information aboutHWindow, see HALCON windows.

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.

Destructors

All HALCON/C++ classes provide default destructors, which automatically free the corresponding memory.

The default destructors of classes encapsulating handles, for example, 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 Constructors above.

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, for example, CloseWindow. Explicit destruction invalidates references, but access is secure.

In HALCON/.NET, you call HALCON operators via instances of classes. The following code grabs the first image of an image sequence and displays it in the graphics window of HSmartWindowControl:

private HWindow               window;
private HFramegrabber         framegrabber;
private HImage                img;
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);

From declaration to finalization

During the lifecycle of an object, i.e., from declaration to finalization, different amounts of memory are allocated and released.

The following declarations 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. However, you can assign image objects to the variable, for example, from the return value of an operator:

Image1 = Framegrabber.GrabImage();

You can also initialize a variable when declaring it:

HImage Image2 = Framegrabber.GrabImage();
HImage Image3 = null;

Tip

You can check the initialization state of a class instance with the method IsInitialized.

Constructors

In contrast, the following declaration calls the “empty” constructor of the class HImage, which creates an unititialized class instance:

HImage Image4 = new HImage();

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:

HImage Image5 = new HImage("fuse");

Note

You can check which constructors are provided via the online help:

  • The reference pages for the classes do not 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).
  • The online help in Visual Studio lists the constructors but not the operators they are based on.

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, for example, 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 on the reference 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 entry:
static void HOperatorSet.CloseFramegrabber(HTuple acqHandle)
void HFramegrabber.CloseFramegrabber()

You do not even need to call such an operator if you, for example, want to re-open the connection with different parameters, because this is done automatically.

Important

Do not call Close or Clear operators via HOperatorSet when using the normal classes like HFramegrabber.

See also Memory management below.

Overloading operators🔗

Some classes overload standard operators like + (addition) to call HALCON operators. The following line adds two images by internally calling AddImage, for example:

Image5 = Image1 + Image2;

Important

Operator overloads are not available in Visual Basic.NET.

The following tables list the currently available operator overloads.

Table 1: Operator overloads for HImage
Operation Type Function
- 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
Table 2: Operator overloads for HRegion
Operation Type Function
& region returns the intersection of regions
| region returns the union of regions
/ region returns the difference of regions
! unary returns the complement of the region (may be infinite)
& image returns the intersection of the region and the image domain
+ region returns the Minkowski addition of regions
- region returns the Minkowski subtraction of regions
+ scalar dilates the region by the specified radius
- scalar erodes the region by the specified radius
+ point translates the region
∗ scalar zooms the region
- unary transposes the region
Table 3: Operator overloads for HFunction1D
Operation Type Function
+ scalar adds a constant offset to the function’s Y values
- scalar subtracts a constant offset from the function’s Y values
- unary negates the Y values of the function
∗ scalar scales the function’s Y values
/ scalar scales the function’s Y values
∗ function composes two functions (not a point-wise multiplication)
! unary calculates the inverse of the function

About memory management🔗

All of HALCON’s classes, that is, 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 Destructors).

Furthermore, when constructing instances anew, for example, by calling CreateBarCodeModel via an already initialized instance (see Constructors), 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 release the resources explicitly before the instance gets out of scope, you can call the method Clear() of the instance.

According to the .NET philosophy, the garbage collector removes unused objects. However, because the garbage collector deletes unused objects only from time to time, the used memory increases in the meantime.
More importantly for garbage collection, HALCON’s iconic variables (images, regions, etc.) seem rather “small” because they only contain references to the often rather large iconic objects in the database. The garbage collector hence may not free such variables even if they are not used anymore.

Therefore, you might need to force the removal of (unused) objects in either of the following ways:

  • 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();
    }
    
  • Dispose of individual objects manually by calling the method Dispose:

    HImage  Image = new HImage("fuse");
      ...
    Image.Dispose();
    

Besides reducing memory consumption, another reason to manually dispose of objects is to free resources, for example, 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.

Note

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.

More Info

For information about general aspects of HALCON’s memory management, see Managing memory.


About error handling🔗

Error handling is fully based on exceptions using try ... catch blocks.

Example

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.

try
{
  image.ReadImage(filename);
}
catch (HException &except)
{
  if (except.ErrorCode() == H_ERR_FNF)
  {
    // Handle file not found error
  }
  else
  {
    // Pass on unexpected error to caller
    throw except;
  }
}

Within the standard try ... catch 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.

Example

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.

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 HALCON error codes.