23.2   Examples

23.2.1   Creating an HDevEngine/.NET Application

This section explains how to create a simple HDevEngine/.NET applicaton with .NET Core. For a more comprehensive description, read section “Using HDevEngine/.NET”.

  1. Install the .NET Core SDK for your system.
  2. Run the following commands in a command line:

    
    dotnet new console -n hdevengine-example
    cd hdevengine-example
    dotnet add package MVTec.HalconDotNet -v 21050
    

  3. Change the content of hdevengine_example.cs to:

    using System;
    using System.Diagnostics;
    using System.IO;
    
    using HalconDotNet;
    
    namespace hdevengine_example
    {
      class Program
      {
        static void Main(string[] args)
        {
          string ExampleDir = HSystem.GetSystem("example_dir");
          string ProcedurePath = "/hdevengine/procedures";
          
          HDevEngine Engine = new HDevEngine();
          Engine.SetProcedurePath(Path.GetFullPath(ExampleDir + ProcedurePath));
    
          HImage Image = new HImage("fin2");
    
          HDevProcedure Procedure = new HDevProcedure("detect_fin");
          HDevProcedureCall ProcCall = new HDevProcedureCall(Procedure);
    
          ProcCall.SetInputIconicParamObject("Image", Image);
          ProcCall.Execute();
    
          HTuple FinArea = ProcCall.GetOutputCtrlParamTuple("FinArea");
          Console.WriteLine(String.Format("Fin Area: {0}", FinArea.I));
        }
      }
    }
    

  4. To run the application type the following command in a command line:

    dotnet run
    

As as result, you should see the following output 'Fin Area: 1634'.

23.2.2   Using HDevEngine/.NET

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, they reside in the subdirectory %HALCONEXAMPLES%\hdevengine\vb.net. They are identical except for the standard differences between the two languages.

23.2.3   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 ExecProgram, which checks the boundary of a plastic part for fins. Figure 23.1 shows a screenshot of the application; it contains two buttons to load and execute the HDevelop program.

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

23.2.3.1   Step 1: Initialization

First, we create a global instance of the main HDevEngine class HDevEngine.

private HDevEngine MyEngine = new HDevEngine();

Upon loading the form, we store the path to the HDevelop program and set the external procedure path with the method SetProcedurePath:

String ProgramPathString;

private void ExecProgramForm_Load(object sender, System.EventArgs e)
{
  string ExampleDir = HSystem.GetSystem("example_dir");
  string ProcedurePath = "/hdevengine/procedures";
  MyEngine.SetProcedurePath(Path.GetFullPath(ExampleDir + ProcedurePath));

  ProgramPathString = Path.GetFullPath(
    ExampleDir + "/hdevengine/hdevelop/fin_detection.hdev"
  );
}

Note that the latter is only necessary if the HDevelop program calls external procedures.

23.2.3.2   Step 2: Load Program

When you click the button to load the HDevelop program, an instance of the class HDevProgram is created, with the path of the program as parameter. Furthermore, an instance of HDevProgramCall 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:

private void LoadBtn_Click(object sender, System.EventArgs e)
{
  try
  {
    HDevProgram Program = new HDevProgram(ProgramPathString);
    ProgramCall = new HDevProgramCall(Program);
  }
  catch (HDevEngineException Ex)
  {
    MessageBox.Show(Ex.Message, "HDevEngine Exception");
    return;
  }

  ...
}

More information on error handling can be found in section “Error Handling”.

23.2.3.3   Step 3: Execute Program

When you click the button to execute the program, the method mHDEExecuteName is called:

private void RunProgram()
{
  try
  {
    try
    {
      ProgramCall.Execute();
    }
  ...
  }
}

23.2.3.4   Step 4: Get Results

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

23.2.3.5   General: Display Results

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

23.2.4   Executing HDevelop Procedures

This section describes example applications that execute HDevelop procedures:

23.2.4.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 ExecExtProc, which, like the example described in the previous section, checks the boundary of a plastic part for fins. Figure 23.2 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.

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

boundary.

23.2.4.2   Step 1: Initialization

As when executing an HDevelop program, we create a global instance of the main HDevEngine class HDevEngine and set the external procedure path with the method SetProcedurePath 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.

private HDevEngine MyEngine = new HDevEngine();

private void ExecExtProcForm_Load(object sender, System.EventArgs e)
{
  string ProcedurePath = "/hdevengine/procedures";
  ...
  MyEngine.SetProcedurePath(Path.GetFullPath(ExampleDir + ProcedurePath));
}

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 “Adding and Customizing HSmartWindowControl for the Visualization” and section “Visualization”). 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:

private HWindow Window;

private void WindowControl_Load(object sender, EventArgs e)
{
  Window = WindowControl.HalconWindow;

  Window.SetDraw("margin");
  Window.SetLineWidth(4);
}

23.2.4.3   Step 2: Load Procedure

When you click the button Load, the HDevelop procedure is loaded with the constructor of the class HDevProcedure, specifying the name of the procedure, and a corresponding procedure call is created as an instance of the class HDevProcedureCall. Exceptions 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 “Error Handling”.

private void LoadBtn_Click(object sender, System.EventArgs e)
{
  try
  {
    HDevProcedure Procedure = new HDevProcedure("detect_fin");
    ProcCall = new HDevProcedureCall(Procedure);
  }
  catch (HDevEngineException Ex)
  {
    MessageBox.Show(Ex.Message, "HDevEngine Exception");
    return;
  }
}

Executing a procedure consists of multiple steps. First, we load an example image sequence:

private void ExecuteBtn_Click(object sender, System.EventArgs e)
{
  HFramegrabber Framegrabber = new HFramegrabber();
  Framegrabber.OpenFramegrabber("File", 1, 1, 0, 0, 0, 0, "default",
     -1, "default", -1, "default", "fin.seq", "default", -1, -1);

23.2.4.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 an input object by storing it in the instance of HDevProcedureCall with the method SetInputIconicParamObject. Which parameter to set is specified via its name (as an alternative, you can specify it via its index):

HImage Image = new HImage();
HRegion FinRegion;
HTuple FinArea;

for (int i = 0; i <= 2; i++)
{
  Image.GrabImage(Framegrabber);
  Image.DispObj(Window);

  ProcCall.SetInputIconicParamObject("Image", 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.

23.2.4.5   Step 4: Execute Procedure

Now, we execute the procedure with the method mHDEExecuteName.

  ProcCall.Execute();

23.2.4.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 nmHDEGetOutputIconicParamRegion and GetOutputCtrlParamTuple of the class HDevProcedureCall; 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 GetOutputIconicParamObject.

  FinRegion = ProcCall.GetOutputIconicParamRegion("FinRegion");
  FinArea = ProcCall.GetOutputCtrlParamTuple("FinArea");

23.2.4.7   Step 6: Display Results Of Procedure

Finally, we display the results in the graphics window:

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

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 “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”. Figure 23.3 shows a screenshot of the application.

Figure 23.3: 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.

private HDevProcedureCall InitAcqProcCall;
private HDevProcedureCall ProcessImageProcCall;
private HDevProcedureCall VisualizeDetailsProcCall;

private void ExecProceduresForm_Load(object sender, System.EventArgs e)
{
  string ProcedurePath = "/hdevengine/procedures";
  ...
  MyEngine.SetProcedurePath(Path.GetFullPath(ExampleDir + ProcedurePath));
}

private void LoadBtn_Click(object sender, System.EventArgs e)
{
  try
  {
    HDevProgram Program = new HDevProgram(ProgramPathString);

    HDevProcedure InitAcqProc = new HDevProcedure(Program, "init_acquisition");
    HDevProcedure ProcessImageProc = new HDevProcedure(Program, "detect_fin");
    HDevProcedure VisualizeDetailsProc =
          new HDevProcedure(Program, "display_zoomed_region");

    InitAcqProcCall = new HDevProcedureCall(InitAcqProc);
    ProcessImageProcCall = new HDevProcedureCall(ProcessImageProc);
    VisualizeDetailsProcCall = new HDevProcedureCall(VisualizeDetailsProc);
  ...
}

One of the procedures opens the image acquisition device. It returns the corresponding handle, which we store in an instance of the class HFramegrabber.

private HFramegrabber Framegrabber;

private void InitAcqBtn_Click(object sender, System.EventArgs e)
{
  InitAcqProcCall.Execute();
  Framegrabber =
      new HFramegrabber(InitAcqProcCall.GetOutputCtrlParamTuple("AcqHandle").H);
  ...
}

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 “Display” for more information about the implementation classes) and remove it again after the procedure has been executed.

private void VisualizeDetailsBtn_Click(object sender, System.EventArgs e)
{
  MyEngine.SetHDevOperators(MyHDevOperatorImpl);

  VisualizeDetailsProcCall.SetInputIconicParamObject("Image", Image);
  VisualizeDetailsProcCall.SetInputIconicParamObject("Region", FinRegion);
  VisualizeDetailsProcCall.SetInputCtrlParamTuple("ZoomScale", 2);
  VisualizeDetailsProcCall.SetInputCtrlParamTuple("Margin", 5);
  VisualizeDetailsProcCall.Execute();

  MyEngine.SetHDevOperators(null);
}

The instance of the implementation class is initialized with the HALCON window of the form.

private HDevOpMultiWindowImpl MyHDevOperatorImpl;

private void WindowControl_Load(object sender, EventArgs e)
{
  Window = WindowControl.HalconWindow;
  ...
  MyHDevOperatorImpl = new HDevOpMultiWindowImpl(Window);
}

If the class HDevOpMultiWindowImpl is initialized without specifying the window, a new HALCON window will open automatically to emulate 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:

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 enable 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 HDevOpFixedWindowImpl or HDevOpMultiWindowImpl is limited for multithreaded applications (executing multiple 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 consistent with the behavior in HDevelop (which also has only one active window) when using multiple threads via par_start.

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 “Creating Multithreaded Applications”.

The example program ExecProgram uses HDevOpMultiWindowImpl. To use this class (or HDevOpFixedWindowImpl), you pass an instance of it to HDevEngine with the method nmHDESetHDevOperatorsName:

private void WindowControl_Load(object sender, EventArgs e)
{
  Window = WindowControl.HalconWindow;

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 “Display”) by creating a class implementing the interface IHDevOperators and overloading its methods DevOpenWindow, DevDisplay, etc.

23.2.6   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 ErrorHandling, which provokes and catches different types of exceptions when you press some buttons. Figure 23.4 shows a screenshot of the application.

Figure 23.4: Provoking exceptions in HDevEngine.

HDevEngine throws exceptions as instances 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 (also see section “HDevEngineException”).

In the example application, the following procedure displays all the information contained in HDevEngineException in a message box:

private void DisplayException(HDevEngineException Ex)
{
  string FullMessage = "Message: <" + Ex.Message + ">" +
    ",  Error in program / procedure: <" + Ex.ProcedureName + ">" +
    ",  program line: <" + Ex.LineText + ">" +
    ",  line number: <" + Ex.LineNumber + ">" +
    ",  HALCON Error Number: <" + Ex.HalconError + ">";

  string Title = "HDevEngine Exception (Category: " +
    Ex.Category.ToString() + ")";

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

catch (HDevEngineException Ex)
{
  DisplayException(Ex);
  return;
}

Figure 23.5 displays an exception that occurred because the application tried to load a non-existing HDevelop program (category ExceptionFile). 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 ExceptionInpNotInit):

procedure detect_fin_with_error_inpnotinit (Image: FinRegion: : FinArea)
  bin_threshold (NotExistingImage, Dark)
  ...

Figure 23.6 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 ExceptionCall).

procedure detect_fin_with_error_call (Image: FinRegion: : FinArea)
  bin_threshold (Image, Dark)
  difference (Image, Dark, Background)
  dev_set_color ('blue')
  dev_display (Background)
  closing_circle (Background, ClosedBackground, -1)
  ...

Figure 23.7 shows the content of the exception.

Figure 23.7: 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”).

23.2.7   Creating Multithreaded Applications

HALCON provides two C# example applications that use multithreading with HDevEngine/.NET:

In the following, we briefly list the most important rules to observe when creating multithreaded HDevEngine applications. Also have a look at the general information about parallel programming using HALCON in section “Parallel Programming Using HALCON”, in particular the style guide in section “Program Design Issues for Parallelization”.

23.2.7.1   Executing a Procedure in Parallel by Multiple Threads

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 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. It consists of a HALCON window for the display of results and buttons to initialize, start, and stop the application.

Figure 23.8: Tasks of the threads.

Figure 23.9: Screenshot of 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.

Initialization

The application is initialized in the event handler of the Init button (file: MultiThreadingForm.cs).

private void InitButton_Click(object sender, System.EventArgs e)

Image Processing

When you click the Run button, the application starts to process images in a loop.

Result Display

23.2.7.2   Executing Multiple Procedures in Parallel by Multiple Threads

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 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. 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, whichs 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.

Figure 23.10: Tasks of the threads.

Figure 23.11: Screenshot of the application.

Initialization

As in the previous example, the application is initialized in the event handler of the Init button (file: MultiThreadingTwoWindowsForm.cs).

Image Processing

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.

public void DisplayResults()
{
  HWindow Window;

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

23.2.8   Executing an HDevelop Program with Vector Variables

The example application UseVectorVariables shows how to load and execute an HDevelop example 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 source file UseVectorVariablesForm.cs for more details on how to work with vector variables in HDevengine/.NET.