22.2   How to Use HDevEngine/C++

This section explains how to employ HDevEngine based on example applications, which reside in the subdirectory %HALCONEXAMPLES%\hdevengine\cpp. Like the examples for HALCON/C++ described in chapter “Creating Applications With HALCON/C++”, they are provided as Visual Studio projects for Windows systems and with makefiles for Linux, macOS, and Windows systems.

The example applications show how to

Section “Creating Multithreaded Applications” contains additional information for creating multithreaded applications using HDevEngine.

22.2.1   Executing an HDevelop Program

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 shows a screenshot of the application.

Figure 22.1: Executing an HDevelop program that detects fins on a boundary.

22.2.1.1   Step 1: Initialization

First, we include the main header files of HALCON/C++ and of HDevEngine and the corresponding namespaces. 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"

using namespace HalconCpp;
using namespace HDevEngineCpp;

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.

    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 SetProcedurePath:

    my_engine.SetProcedurePath(ext_proc_path.c_str());

22.2.1.2   Step 2: Load Program

Now, we create an instance of the class HDevProgram and load the HDevelop program with the method LoadProgram. Note that LoadProgram 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 “Error Handling”.

    HDevProgram my_program;
  try
  {
    my_program.LoadProgram(program_path.c_str());
  }
  catch (HDevEngineException& hdev_exception)
    ...

22.2.1.3   Step 3: Execute Program

If the program could be loaded successfully, we execute the program with the method mHDEExecuteName and store the returned instance of the class HDevProgramCall in a variable for later use:

  HDevProgramCall prog_call = my_program.Execute();

22.2.1.4   Step 4: Get Results

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 GetCtrlVarTuple. In the example program, the area of the extracted fin is queried and then displayed:

  HTuple result = prog_call.GetCtrlVarTuple("FinArea");
  printf("\nFin Area: %f\n\n", result[0].D());

Note that program variables can only be accessed when the program has terminated.

22.2.1.5   General: Display Results

How to display results while the program is running is described in section “Display”.

22.2.2   Executing HDevelop Procedures

This section describes example applications that execute HDevelop procedures:

22.2.2.1   Executing an External HDevelop Procedure

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 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 “Display”.

Figure 22.2: Executing an external HDevelop procedure that detects fins on a

boundary.

22.2.2.2   Step 1: Initialization

As when executing an HDevelop program, we include the main header files of HALCON/C++ and of HDevEngine 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 HDevEngine and directly set the external procedure path with the method SetProcedurePath. 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"

using namespace HalconCpp;
using namespace HDevEngineCpp;

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.2.3   Step 2: Load Procedure

In the “action” routine, we load the external procedure with the constructor of the class HDevProcedure, specifying the name of the procedure, and store the returned procedure call in an instance of the class HDevProcedureCall. The call is encapsulated in a try... catch-block to handle exceptions occurring in the constructor, e.g., because the file name or the procedure path was not specified correctly. A detailed description of error handling can be found in section “Error Handling”.

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:

    const char* image_sequ_str = "fin";

    HWindow win(00, 100, 384, 288);
    win.SetPart(0, 0, 575, 767);
    win.SetDraw("margin");
    win.SetLineWidth(4);

    HFramegrabber fg("File", 1, 1, 0, 0, 0, 0, "default", -1, "default", -1,
                     "default", image_sequ_str, "default", -1, -1);

22.2.2.4   Step 3: Set Input Parameters Of Procedure

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:

  procedure detect_fin (Image: FinRegion: : FinArea)

We pass the image as input object by storing it in the instance of HDevProcedureCall with the method SetInputIconicParamObject. Which parameter to set is specified via its index (starting with 1); there is also a method to specify it via its name (see section “HDevProcedureCall”):

    for (long i = 0; i < 3; i++)
    {
      HImage image = fg.GrabImage();

      proc_call.SetInputIconicParamObject(1, image);

As as alternative to passing parameters, you can also use global variables in HDevEngine (compare the HDevelop User's Guide). You set the value of a global variable with the methods SetGlobalIconicVarObject or SetGlobalCtrlVarTuple and query it with the methods GetGlobalIconicVarObject and GetGlobalCtrlVarTuple.

22.2.2.5   Step 4: Execute Procedure

Now, we execute the procedure with the method mHDEExecuteName.

      proc_call.Execute();

22.2.2.6   Step 5: Get Output Parameters Of Procedure

If the procedure was executed successfully, we can access its results, i.e., the fin region and its area, with the methods GetOutputIconicParamObject and GetOutputCtrlParamTuple of the class HDevProcedureCall; again, you can specify the parameter via its index or name (see section “HDevProcedureCall”).

      HRegion fin_region = proc_call.GetOutputIconicParamObject(1);
      HTuple  fin_area;
      proc_call.GetOutputCtrlParamTuple(1, &fin_area);

22.2.2.7   Step 6: Display Results Of Procedure

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);

22.2.2.8   Executing Local and External HDevelop Procedures

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 section “Executing an HDevelop Program”. 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 “Display”.

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. HDevProcedure provides different constructors to facilitate this task (see section “HDevProcedure”).

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 “Executing an HDevelop Program”, 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 HDevOperatorImplCpp, 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., DevDisplay for dev_display and have the same parameters (see section “HDevOperatorImplCpp” for the definition of the class).

The first step towards the implementation is to derive a child of this class and to specify all methods 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:

class MyHDevOperatorImpl : public HDevEngineCpp::HDevOperatorImplCpp
{
public:
  virtual int DevOpenWindow(const HalconCpp::HTuple& row,
                            const HalconCpp::HTuple& col,
                            const HalconCpp::HTuple& width,
                            const HalconCpp::HTuple& height,
                            const HalconCpp::HTuple& background,
                            HalconCpp::HTuple* win_id);
  virtual int DevSetWindowExtents(const HalconCpp::HTuple& row,
                                  const HalconCpp::HTuple& col,
                                  const HalconCpp::HTuple& width,
                                  const HalconCpp::HTuple& height);
  virtual int DevSetPart(const HalconCpp::HTuple& row1,
                         const HalconCpp::HTuple& col1,
                         const HalconCpp::HTuple& row2,
                         const HalconCpp::HTuple& col2);
  virtual int DevSetWindow(const HalconCpp::HTuple& win_id);
  virtual int DevGetWindow(HalconCpp::HTuple* win_id);
  virtual int DevClearWindow();
  virtual int DevCloseWindow();
  virtual int DevDisplay(const HalconCpp::HObject& obj);
  virtual int DevDispText(const HalconCpp::HTuple& string,
                          const HalconCpp::HTuple& coordSystem,
                          const HalconCpp::HTuple& row,
                          const HalconCpp::HTuple& column,
                          const HalconCpp::HTuple& color,
                          const HalconCpp::HTuple& GenParamName,
                          const HalconCpp::HTuple& GenParamValue);
  virtual int DevSetDraw(const HalconCpp::HTuple& draw);
  virtual int DevSetContourStyle(const HalconCpp::HTuple& style);
  virtual int DevSetShape(const HalconCpp::HTuple& shape);
  virtual int DevSetColor(const HalconCpp::HTuple& color);
  virtual int DevSetColored(const HalconCpp::HTuple& colored);
  virtual int DevSetLut(const HalconCpp::HTuple& lut);
  virtual int DevSetPaint(const HalconCpp::HTuple& paint);
  virtual int DevSetLineWidth(const HalconCpp::HTuple& width);
};

In addition to these methods, the class contains methods to handle multiple graphics windows. These methods use a second class that manages all open windows. This class is thread-safe and reentrant but not described in detail in this section.

  HalconCpp::HTuple GetCurrentWindow()  const;
  size_t            GetCount()          const;
  void              AddWindow(const HalconCpp::HTuple& id);
  HalconCpp::HTuple PopWindow();
  Hlong             SetWindow(const HalconCpp::HTuple& id);

  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).

To use the implementation of HDevOperatorImplCpp, you include the header file:

#include "my_hdevoperatorimpl.h"

With the method SetHDevOperatorImpl, you pass an instance of your version of HDevOperatorImplCpp to HDevEngine, which then calls its methods when the corresponding operator is used in the HDevelop program or procedure.

    my_engine.SetHDevOperatorImpl(&op_impl);

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 DevDisplay to disp_obj, with the iconic object to display and the handle of the active window as parameters:

int MyHDevOperatorImpl::DevDisplay(const HObject& obj)
{
  HCkDev(DispObj(obj, GetCurrentWindow()));
}

Similarly, dev_set_draw is redirected in DevSetDraw to set_draw:

int MyHDevOperatorImpl::DevSetDraw(const HTuple& draw)
{
  HCkDev(SetDraw(GetCurrentWindow(), draw));
}

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.

22.2.4   Error Handling

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 HDevEngineException, 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 “HDevEngineException” 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:

void DispMessage(const char* message)
{
  HWindow win(100, 100, ERR_WIN_WIDTH_SIMPLE, ERR_WIN_HEIGHT_SIMPLE, NULL,
              "visible", "");
  win.SetPart(0, 0, ERR_WIN_HEIGHT_SIMPLE - 1, ERR_WIN_WIDTH_SIMPLE - 1);
  win.SetColor("yellow");
  win.SetTposition(10, 10);
  WriteMessageNL(win, message);

  // wait for mouse click to continue
  win.SetColor("red");
  win.SetTposition(ERR_WIN_HEIGHT_SIMPLE / 2 + 10, ERR_WIN_WIDTH_SIMPLE / 2);
  win.WriteString("...click into window to continue");
  win.Click();
}

The more complex one prints all available information for the exception (only relevant code shown):

void DispErrorMessage(const HDevEngineCpp::HDevEngineException& exception,
                      const char* context_msg /*=NULL*/)
{
  char text[2000];

  HWindow win(100, 100, ERR_WIN_WIDTH_COMPLEX, ERR_WIN_HEIGHT_COMPLEX, NULL,
              "visible", "");

  WriteMessageNL(win, exception.Message());

  sprintf(text, "    Error category: <%d : %s>", exception.Category(),
          exception.CategoryText());
  WriteMessageNL(win, text);

  sprintf(text, "    Error code:   <%d>", exception.HalconErrorCode());
  WriteMessageNL(win, text);

  sprintf(text, "    Procedure:      <%s>", exception.ExecProcedureName());
  WriteMessageNL(win, text);

  sprintf(text, "        Line:         <%d : %s>", exception.ProgLineNum(),
          exception.ProgLineName());
  WriteMessageNL(win, text);
}

This procedure is called when an exception occurs. The example provokes different errors and displays the corresponding information; some of them are described in the following. Figure 22.3 displays an exception that occurred because the application tried to load a non-existing HDevelop program (category ExceptionFile).

  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");
  }

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).

Figure 22.4: Content of the exception if external procedures of an HDevelop program could not be loaded.

The exception displayed in figure 22.5 occurs because an input iconic parameter is not initialized (category ExceptionInpNotInit). It contains very detailed information about where the error occurred and why.

Figure 22.5: Content of the exception if an input parameter was not initialized.

The exception displayed in figure 22.6 is provoked by calling an operator with an invalid parameter (category ExceptionCall).

Figure 22.6: Content of the exception if an error occurred in a HALCON operator call.

With the method UserData (see section “HDevEngineException”), 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 “HDevEngine”).

22.2.5   Creating Multithreaded Applications

In the example mfc\exec_procedures_mt_mfc , three threads execute HDevelop procedures for image acquisition, data code reading, and visualization in parallel (see figure 22.7). 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.

Figure 22.7: Example program with three threads performing image acquisition, data code reading, and visualization in parallel.

The example exec_programs_mt (source file exec_programs_mt.cpp) shows how one or several different HDevelop programs can be executed in different threads in parallel. Note that it is kept very general and does not realize a specific application.

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.

22.2.6   Executing an HDevelop Program with Vector Variables

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 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 example source file use_vector_variables.cpp for more details on how to work with vector variables in HDevengine/C++.