在vs中引入halcon控件
修改目标平台为 x64
拖出三个控件
代码展示
using System;
using System.Windows.Forms;
//引用支持halcon的命名空间
using HalconDotNet;namespace _1.HalconDisplay {public partial class Form1 : Form {// HObject 是Halcon库中表示图像和其他图形对象的类。在这里,声明了几个图像对象HObject ho_Image, ho_Regions, ho_ConnectedRegions, ho_SeletedRegions;// HTuple 则是Halcon库中用来存储元组(tuple)的类,它可以用来存储各种类型的数据。在这里,声明了几个用来存储图像宽度、高度和窗口句柄的变量。HTuple hy_Width = null, hy_Height = null, hy_WindowHandle = null;public Form1() {InitializeComponent();}// 运行按钮private void btnRun_Click(object sender, EventArgs e) {// HOperatorSet 是Halcon库中的一个操作符集合,包含了大量的图像处理函数和操作符。// GenEmptyObj 用于生成一个空的图像对象。HOperatorSet.GenEmptyObj(out ho_Image);HOperatorSet.GenEmptyObj(out ho_Regions);HOperatorSet.GenEmptyObj(out ho_ConnectedRegions);HOperatorSet.GenEmptyObj(out ho_SeletedRegions);//检测窗口是否打开// HDevWindowStack 是用于管理Halcon显示窗口的堆栈// IsOpen():检查当前是否有Halcon显示窗口处于打开状态if (HDevWindowStack.IsOpen()) {// Pop() 从堆栈中弹出(移除)最顶部的窗口,并返回对应的窗口句柄。HOperatorSet.CloseWindow(HDevWindowStack.Pop());}// Dispose() 释放对象占用的资源ho_Image.Dispose();//ReadImage 读取图像HOperatorSet.ReadImage(out ho_Image, "printer_chip/printer_chip_01");// GetImageSize 获取图像大小HOperatorSet.GetImageSize(ho_Image, out hy_Width, out hy_Height);// SetWindowAttr() 设置Halcon显示窗口的属性HOperatorSet.SetWindowAttr("background_color", "blue");HOperatorSet.OpenWindow(0, 0, hWindowControl1.Width, hWindowControl1.Height, hWindowControl1.HalconWindow, "visible", "", out hy_WindowHandle);HDevWindowStack.Push(hy_WindowHandle);//显示图像if (HDevWindowStack.IsOpen()) {// DispObj 是Halcon库中用于在交互式开发环境中显示图像对象的函数。// HDevWindowStack.GetActive() 获取当前活动的Halcon显示窗口HOperatorSet.DispObj(ho_Image, HDevWindowStack.GetActive());}}// 图像二值化private void btn_Threshold_Click(object sender, EventArgs e) {ho_Regions.Dispose();//二值化HOperatorSet.Threshold(ho_Image, out ho_Regions, 128, 255);ho_ConnectedRegions.Dispose();//连通预处理HOperatorSet.Connection(ho_Regions, out ho_ConnectedRegions);//特征筛选ho_SeletedRegions.Dispose();HOperatorSet.SelectShape(ho_ConnectedRegions, out ho_SeletedRegions, "area", "and", 28084.7, 33809.1);if (HDevWindowStack.IsOpen()) {HOperatorSet.DispObj(ho_Image, HDevWindowStack.GetActive());}//显示筛选后的区域if (HDevWindowStack.IsOpen()) {HOperatorSet.SetColor(HDevWindowStack.GetActive(), "green");HOperatorSet.DispObj(ho_SeletedRegions, HDevWindowStack.GetActive());}ho_Image.Dispose();ho_Regions.Dispose();}}
}
结果
点击运行按钮可以加载出图片
点击二值化按钮可以将该图片进行二值化处理