13.1   A First Example

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

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

Figure 13.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 Python 3.8 or newer on your system.
  3. Setup your Python environment of choice, e.g., using python -m venv`
  4. Run the following commands in a shell:

    
    mkdir region_example
    cd region_example
    pip install mvtec-halcon==21050
    

  5. Create a file named program.py and change the content to:

    import halcon as ha
    
    if __name__ == '__main__':
        img = ha.read_image('pcb')
    
        region = ha.threshold(img, 0, 122)
        num_regions = ha.count_obj(ha.connection(region))
    
        print(f'Number of Regions: {num_regions}')
    

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

    python program.py
    

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