HDevEngine in C++ applicationsπ
This section explains how to use HDevEngine based on example applications.
The example applications are located in the %HALCONEXAMPLES%\hdevengine\cpp directory.
Like the examples for HALCON/C++, they are provided with CMake files for Linux and Windows.
The example applications show how to:
- execute an HDevelop program
- execute HDevelop procedures
- implement display operators
- handle errors
- create multithreaded applications
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 in exec_program.cpp, which checks the boundary of a plastic part for fins.
Step 1: Initializationπ
First, we include the main header files of HALCON/C++ and HDevEngine and the corresponding namespaces.
Note that in this example application the HDevEngine header file is already included via my_hdevoperatorimpl.h, so we do not have to include HDevEngineCpp.h explicitly.
#include "HalconCpp.h"
#include "my_hdevoperatorimpl.h"
using namespace HalconCpp;
using namespace HDevEngineCpp;
The main procedure calls a function that performs the work of the example.
First, we create an instance of the main HDevEngine class clHDevEngineName.
The path to the HDevelop program and the external procedure path are stored in string variables with platform-specific syntax.
In Windows applications, both / and \ can be used 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 SetProcedurePath.
Step 2: Load programπ
Now, we create an instance of clHDevProgramName and load the HDevelop program with LoadProgram.
Note that LoadProgram changes the working directory if a program is loaded successfully.
The call is enclosed in a try/catch block to handle exceptions raised by HDevEngine, for example because the file name was not specified correctly.
A detailed description of error handling can be found in Error handling.
HDevProgram my_program;
try
{
my_program.LoadProgram(program_path.c_str());
}
catch (HDevEngineException& hdev_exception)
{
...
}
Step 3: Execute programπ
If the program could be loaded successfully, we execute it with Execute and store the returned HDevProgramCall in a variable for later use.
Step 4: Get resultsπ
That is all you need to do to execute an HDevelop program.
You can also access its βresultsβ, i.e., its variables, with GetCtrlVarTuple.
In the example program, the area of the extracted fin is queried and displayed.
Note that program variables can only be accessed after the program has terminated.
General: display resultsπ
How to display results while the program is running is described in Display.
Executing HDevelop proceduresπ
This section describes example applications that execute HDevelop procedures.
- a single external procedure
- multiple local and external procedures
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 in exec_extproc.cpp, which, like the example described in the previous section, checks the boundary of a plastic part for fins.
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 Display.
Step 1: Initializationπ
As when executing an HDevelop program, we include the main header files of HALCON/C++ and HDevEngine and the namespaces.
In this example application, the HDevEngine header file is included via my_error_output.h, so we do not need to include it explicitly.
The main function calls the procedure run, which performs the work of the example.
We create an instance of the main HDevEngine class clHDevEngineName and set the external procedure path directly with 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();
}
Step 2: Load procedureπ
In the action routine, we load the external procedure with the constructor of clHDevProcedureName, specifying the procedure name, and store the returned procedure call in an instance of clHDevProcedureCallName.
The call is enclosed in a try/catch block to handle exceptions occurring in the constructor, for example because the file name or procedure path was not specified correctly.
A detailed description of error handling can be found in Error handling.
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);
Step 3: Set input parameters of the procedureπ
Each image is processed by the procedure, which has the following signature:
procedure detect_fin (Image: FinRegion: : FinArea)
We pass the image as an input object by storing it in the instance of clHDevProcedureCallName with SetInputIconicParamObject.
Which parameter is set is specified via its index; there is also a method to specify it via its name.
for (long i = 0; i < 3; i++)
{
HImage image = fg.GrabImage();
proc_call.SetInputIconicParamObject(1, image);
As an alternative to passing parameters, you can also use global variables in HDevEngine.
You set the value of a global variable with SetGlobalIconicVarObject or SetGlobalCtrlVarTuple and query it with GetGlobalIconicVarObject and GetGlobalCtrlVarTuple.
However, take care not to overwrite the value of a variable from one program with that of another, because each global variable can have only one value at a time for all running HDevEngine instances.
Step 4: Execute procedureπ
Now, we execute the procedure with Execute.
Step 5: Get output parameters of the procedureπ
If the procedure was executed successfully, we can access its results, i.e., the fin region and its area, with GetOutputIconicParamObject and GetOutputCtrlParamTuple of clHDevProcedureCallName.
Again, you can specify the parameter via its index or name.
HRegion fin_region = proc_call.GetOutputIconicParamObject(1);
HTuple fin_area;
proc_call.GetOutputCtrlParamTuple(1, &fin_area);
Step 6: Display results of the 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);
Executing local and external HDevelop proceduresπ
The example application exec_procedures executes local and external HDevelop procedures with HDevEngine.
It mimics the behavior of the HDevelop program described in 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 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.
clHDevProcedureName provides different constructors to facilitate this task.
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 and exec_procedures.
In fact, HDevEngine does not provide an implementation of the internal display operators, but it provides the class clHDevOperatorImplName, 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, for example DevDisplay for dev_display, and they have the same parameters.
The first step is to derive a child of this class and specify the 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_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 for managing multiple graphics windows. These methods use a second class that manages all open windows. This class is thread-safe and reentrant, but it is not described in detail here.
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
To use the implementation of clHDevOperatorImplName, include the header file.
With SetHDevOperatorImpl, you pass an instance of your version of clHDevOperatorImplName to HDevEngine, which then calls its methods when the corresponding operator is used in the HDevelop program or procedure.
Now, 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 is redirected in DevDisplay to disp_obj.
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.
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 in error_handling.cpp, which provokes different types of exceptions and catches them.
HDevEngine throws exceptions in the form of clHDevEngineExceptionName, which contains the exception category, a message describing the exception, and, depending on the exception type, information such as the name of the executed procedure or the HALCON error code.
The example code for displaying exception information in a graphics window is contained in my_error_output.cpp and my_error_output.h.
You can use it in your application by including the header file.
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.
void DispErrorMessage(const HDevEngineCpp::HDevEngineException& exception,
const char* context_msg /*=NULL*/)
{
try
{
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. The first case is a missing HDevelop program, which leads to a file-related exception.
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");
}
The same exception category occurs when a program is loaded whose external procedures are not found. The next exception occurs because an input iconic parameter was not initialized. It contains very detailed information about where the error occurred and why. The final exception is triggered by calling an operator with an invalid parameter.
With UserData, you can also access user exception data thrown within an HDevelop program or procedure by the operator throw, similarly to the operator dev_get_exception_data.
If an exception is not caught inside the procedure, the procedure call is cleaned up. This means that all subthreads are destroyed and all values of the 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 SetEngineAttribute.
Creating multithreaded applicationsπ
The example mfc\exec_procedures_mt_mfc contains three threads that execute HDevelop procedures for image acquisition, 2D code reading, and visualization in parallel.
Please look at the example source files in the directory mfc\exec_procedures_mt_mfc\source\ to see how the threads synchronize their input and output data.
The example exec_programs_mt in 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 implement a specific application.
The HDevelop program or programs 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.
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 look at the example source file use_vector_variables.cpp for more details on how to work with vector variables in HDevEngine/C++.