13.1 第一个示例

本节演示如何使用 Python 创建一个简单的 HALCON 应用程序。有关更全面的描述,参见 "使用 HALCON/Python 创建应用程序" 一章

任务是读取图像并计算其中的连接区域数,如 图 13.1 所示

图 13.1: 左图:印刷电路板的输入图像。中间:通过 threshold 找到的区域,红色。右图:连接区域,connection 的结果。

  1. 安装 HALCON 23.05
  2. 在系统中安装 Python 3.8 或更新版本。
  3. 设置所选的 Python 环境,例如使用 python -m venv path_to_new_virtual_environment
  4. 在 shell 中运行以下命令:

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

  5. 创建名为 program.py 的文件,并将内容更改为:

    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. 要运行应用程序,请在同一 shell 中键入以下命令:

    python program.py
    

结果,您将看到以下输出 'Number of Regions: 43'