This section explains how to create a simple HDevEngine/.NET applicaton with .NET Core. For a more comprehensive description, read section “Using HDevEngine/.NET”.
dotnet new console -n hdevengine-example cd hdevengine-example dotnet add package MVTec.HalconDotNet -v 21050
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)); } } }
dotnet run
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, they reside in the subdirectory %HALCONEXAMPLES%\hdevengine\vb.net. They are identical except for the standard differences between the two languages.
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.
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.
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”.
When you click the button to execute the program, the method mHDEExecuteName is called:
private void RunProgram()
{
try
{
try
{
ProgramCall.Execute();
}
...
}
}
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.
How to display results while the program is running is described in section “Display”.
This section describes example applications that execute HDevelop procedures:
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.
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);
}
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);
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.
Now, we execute the procedure with the method mHDEExecuteName.
ProcCall.Execute();
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");
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);
});
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.
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.
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.
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.
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.
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.
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.
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”).
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”.
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.
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.
The application is initialized in the event handler of the Init button (file: MultiThreadingForm.cs).
private void InitButton_Click(object sender, System.EventArgs e)
Switch off automatic operator parallelization
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 “Program Design Issues for Parallelization”). 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 “Customizing the Parallelization Mechanisms”.
Set external procedure path
Then, we create an instance of HDevEngine 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.
HDevEngine MyEngine = new HDevEngine(); string ProcedurePath = "/hdevengine/procedures"; ... MyEngine.SetProcedurePath(Path.GetFullPath(ExampleDir + ProcedurePath));
Train the shape model
To initialize the image processing part, we execute an HDevelop procedure that trains the shape model of the caps.
HDevProcedureCall ProcTrain;
HDevProcedure Procedure = new HDevProcedure("train_shape_model");
ProcTrain = new HDevProcedureCall(Procedure);
ProcTrain.Execute();
Store the model data
The procedure returns the handle of the shape model and the model contours. We store both in variables of the form so that the processing threads can access them.
public HTuple ModelID;
public HXLD ModelContours;
ModelID = ProcTrain.GetOutputCtrlParamTuple("ModelID");
ModelContours = ProcTrain.GetOutputIconicParamXld("ModelContours");
Create and initialize the processing engines
The actual image processing is encapsulated in the class EngineThread (file: EngineThread.cs). The main members of this class are a thread and instances of HDevEngine and HDevProcedureCall. Besides, an EngineThread contains variables for accessing the shape model data trained in the main thread and an event that signals that the “engine” is ready for the next image.
public class EngineThread
{
Thread WorkerObject = null;
HDevProcedureCall ProcCall;
HTuple ModelID;
HXLD ModelContours;
public AutoResetEvent EngineIsReady;
public EngineThread(MultiThreadingForm mainForm)
{
ModelID = mainForm.ModelID;
ModelContours = mainForm.ModelContours;
EngineIsReady = new AutoResetEvent(true);
}
The main thread creates and initializes two instances of this class and also stores their events (file: MultiThreadingForm.cs).
EngineThread WorkerEngine1; // Processing thread. EngineThread WorkerEngine2; // Processing thread. AutoResetEvent Engine1Ready; AutoResetEvent Engine2Ready; WorkerEngine1 = new EngineThread(this); WorkerEngine1.Init(); Engine1Ready = WorkerEngine1.EngineIsReady; WorkerEngine2 = new EngineThread(this); WorkerEngine2.Init(); Engine2Ready = WorkerEngine2.EngineIsReady;
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).
public void Init()
{
HDevProcedure Procedure = new HDevProcedure("detect_shape");
ProcCall = new HDevProcedureCall(Procedure);
ProcCall.SetInputCtrlParamTuple("ModelID", ModelID);
ProcCall.SetInputIconicParamObject("ModelContours", ModelContours);
}
Initialize image acquisition
Finally, we initialize the image acquisition. The handle is stored in a variable of the form, so that the control thread can access it (file: MultiThreadingForm.cs).
private HFramegrabber AcqHandle;
string ImagePath = Path.GetFullPath(ExampleDir + "/images/cap_illumination");
AcqHandle = new HFramegrabber("File", 1, 1, 0, 0, 0, 0, "default", -1,
"default", -1, "default", ImagePath, "default", -1, -1);
When you click the Run button, the application starts to process images in a loop.
Starting the processing threads and the control thread
First, the main thread starts the processing engines (file: MultiThreadingForm.cs).
private void RunButton_Click(object sender, System.EventArgs e)
{
WorkerEngine1.Run();
WorkerEngine2.Run();
The corresponding method creates and starts their thread and sets the “ready” signal (file: EngineThread.cs).
public void Run()
{
EngineIsReady.Set();
WorkerObject = new Thread(new ThreadStart(Process));
WorkerObject.Start();
}
Then, the main thread starts the control thread (file: MultiThreadingForm.cs):
ControlThread = new Thread(new ThreadStart(Run)); ControlThread.Start();
Triggering the processing threads from the control thread
The control thread's action is contained in the method Run (file: MultiThreadingForm.cs). As long as the Stop is not pressed (please take a look at the project's code for more information), it waits until one of the processing engine is ready.
EngineThread WorkerEngine; // Variable to switch between processing threads.
public void Run()
{
HImage Image;
while (!StopEventHandle.WaitOne(0, true))
{
if (Engine1Ready.WaitOne(0, true))
WorkerEngine = WorkerEngine1;
else if (Engine2Ready.WaitOne(0, true))
WorkerEngine = WorkerEngine2;
else
continue;
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).
private HImage InputImage = null;
public void SetImage(HImage Img)
{
InputImage = Img;
}
Processing the image
In their action method (Process), the processing threads wait for the image to be set (file: EngineThread.cs). The actual image processing is performed by the HDevelop procedure, passing the image as input parameter.
public void Process()
{
while (!DelegatedStopEvent.WaitOne(0, true))
{
if (InputImage == null)
continue;
ProcCall.SetInputIconicParamObject("Image", InputImage);
ProcCall.Execute();
Passing the results to the control thread
To pass the results, a class is defined that stores the relevant data: the processed image and the position, orientation, and the contours of the found cap.
public class ResultContainer
{
public HImage InputImage;
public HXLD FoundContours;
public double Row;
public double Column;
public double Angle;
}
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;
Result = new ResultContainer();
Result.InputImage = InputImage;
Result.FoundContours = ProcCall.GetOutputIconicParamXld("ResultObject");
ResultTuple = ProcCall.GetOutputCtrlParamTuple("ResultData");
Result.Row = ResultTuple[0];
Result.Column = ResultTuple[1];
Result.Angle = ResultTuple[2];
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.
public ArrayList ResultList;
public Mutex ResultDataMutex;
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;
public EngineThread(MultiThreadingForm mainForm)
{
ResultList = mainForm.ResultList;
ResultMutex = mainForm.ResultDataMutex;
}
“Ready again”
Finally, the processing thread signals that it is ready for the next image by setting the corresponding event and by setting the input image to null.
InputImage = null; this.EngineIsReady.Set();
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.
int Count = -1; ResultDataMutex.WaitOne(); Count = ResultList.Count; ResultDataMutex.ReleaseMutex();
Delegating the display
The control thread does not perform the display of results itself but delegates it to the main thread (running the form) with the method Invoke.
for (; Count > 0; Count--) Invoke(DelegatedDisplay);
The necessary members are defined by the form.
delegate void FuncDelegate();
FuncDelegate DelegatedDisplay;
public MultiThreadingForm()
{
DelegatedDisplay = new FuncDelegate(DisplayResults);
}
Note that, since HALCON 12, all HALCON visualization operators are automatically delegated to the correct thread as described in chapter section “Threading Issues with Graphics”.
Displaying the results
The actual display is performed by the method DisplayResults. Each time it is called, it removes an item from the result list and displays the processed image with the contours of the found cap. Then, it frees the corresponding HALCON -internal memory.
public void DisplayResults()
{
ResultDataMutex.WaitOne();
Result = (ResultContainer)ResultList[0];
ResultList.Remove(Result);
ResultDataMutex.ReleaseMutex();
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 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.
As in the previous example, the application is initialized in the event handler of the Init button (file: MultiThreadingTwoWindowsForm.cs).
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).
public class EngineThread
{
...
public int WindowIndex = -1;
...
The control thread sets this variable after creating the engines (file:
MultiThreadingTwoWindowsForm.cs).
private void InitButton_Click(object sender, System.EventArgs e)
{
...
WorkerEngine1.WindowIndex = 1;
...
WorkerEngine2.WindowIndex = 2;
Train the shape and data code model
The training of the shape and data code model is now performed by the initialization method of the processing threads, which now has a parameter that specifies the task of the processing thread (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.
public class EngineThread
{
HDevProcedureCall ProcCall;
string Task;
HTuple ModelID;
HXLD ModelContours;
...
public void Init(string Task)
{
string TrainMethod = "train_" + Task + "_model";
string ProcessingMethod = "detect_" + Task;
HDevProcedureCall ProcTrain;
this.Task = Task;
Then, the model of the shape or datacode, respectively, is trained by executing the corresponding HDevelop procedure 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");
}
Store the model data
Finally, those input parameters of the image processing procedure that are the same for each call are set (file: EngineThread.cs).
HDevProcedure Procedure = new HDevProcedure(ProcessingMethod);
ProcCall = new HDevProcedureCall(Procedure);
ProcCall.SetInputCtrlParamTuple("ModelID", ModelID);
if (Task.Equals("shape"))
{
ProcCall.SetInputIconicParamObject("ModelContours", ModelContours);
}
Initialize image acquisition
The two image processing tasks are performed in different images, therefore, two image acquisition devices are opened by the main thread (file:
MultiThreadingTwoWindowsForm.cs, code not shown).
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 and passes images..
public void Run()
{
HImage Image;
while (!StopEventHandle.WaitOne(0, true))
{
if (Engine1Ready.WaitOne(0, true))
{
Image = AcqHandle1.GrabImageAsync(-1);
WorkerEngine1.SetImage(Image);
}
if (Engine2Ready.WaitOne(0, true))
{
Image = AcqHandle2.GrabImageAsync(-1);
WorkerEngine2.SetImage(Image);
}
Passing the results to the control thread
The class storing the result data differs significantly from the one in the previous example: It now also contains a variable that indicates the window in which to display the results and a flag that shows whether the processing was successful. Because the processing results differ between the two tasks, they are encapsulated in a tuple (file: EngineThread.cs).
public class ResultContainer
{
public int WindowIndex; // 1 -> shape, 2 -> datacode.
public HImage InputImage;
public HXLD FoundContours;
public HTuple ResultData;
public bool DetectionSuccessful;
}
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.
public void Process()
{
ResultContainer Result;
Result = new ResultContainer();
...
Result.InputImage = InputImage;
DetectionSuccessful = ProcCall.GetOutputCtrlParamTuple("DetectionSuccessful").S;
if (DetectionSuccessful.Equals("true"))
{
Result.DetectionSuccessful = true;
Result.FoundContours = ProcCall.GetOutputIconicParamXld("ResultObject");
Result.ResultData = ProcCall.GetOutputCtrlParamTuple("ResultData");
}
else
{
Result.DetectionSuccessful = false;
}
Result.WindowIndex = WindowIndex;
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");
}
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.