16.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 16.1

Figure 16.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 C99 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.c and change the content to:

    #include <stdio.h>
    #include <inttypes.h>
    
    #include <HalconC.h>
    
    int main()
    {
        Hobject img;
        read_image(&img, "pcb");
        
        Hobject region;
        threshold(img, &region, 0, 122);
        
        Hobject connected_regions;
        connection(region, &connected_regions);
        
        Hlong num_regions = 0;
        count_obj(connected_regions, &num_regions);
        
        printf("Number of Regions: \%" PRIdPTR "\n", num_regions);
    }
    

  6. Compile the program.

    For details see section “Creating Applications Under Windows” for Windows and section “Creating Applications 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'.