4.1   A First Example

This section demonstrates how to create a simple HALCON application with C++. For a more comprehensive description, see chapter “Creating Applications With HALCON/C++”.

The task is to read an image and compute the number of connected regions in it, as illustrated in figure 4.1

Figure 4.1: Left: Input image of a printed circuit board. Middle: Regions found by threshold, colored red. Right: Connected regions, a result of connection.

  1. Install HALCON 21.05
  2. Install a C++11 or newer toolchain on your system.
  3. Setup your C++ environment of choice.
  4. Run the following commands in a shell:

    
    mkdir region_example
    cd region_example
    

  5. Create a file named main.cpp and change the content to:

    #include <iostream>
    
    #include <HalconCpp.h>
    
    using HalconCpp::HImage;
    using HalconCpp::HRegion;
    
    int main()
    {
        HImage img{"pcb"};
    
        HRegion region = img.Threshold(0, 122);
        Hlong numRegions = region.Connection().CountObj();
    
        std::cout << "Number of Regions: " << numRegions << '\n';
    }
    

  6. Compile the program.

    For details see section “Creating an Executable Under Windows” for Windows and section “Creating an Executable Under Linux” for Linux.

  7. To run the application, type the following command in the same shell:

    ./region_example
    

As a result, you should see the following output 'Number of Regions: 43'.