halcon封装 halcon导出 首先,在halcon里选择 文件 –> 导出 , 在导出菜单中选择C#,窗口导出选择使用导出模板 。点击导出后会获得cs后缀名的文件 。
建议:最好把halcon的代码先封装成函数,这样在导出为C#的类中也存在相应的函数(例如把读取图片,处理图片等步骤封装成一个个函数)
C#项目使用halcon导出的文件 在Visual Studio 中新建C#的windows 窗体应用 ,在引用中添加引用halcondotnet.dll (halcondotnet.dll在halcon安装目录的bin->dotnet35目录下),在工具->选择工具箱项 ,在.NET Framework组件中点击浏览,选择halcondotnet.dll,这时可看见已添加HsmarkWindowControl和HWindowControl (这是图片的显示控件),然后在项目添加现有项,选择halcon导出的cs文件。
这时,便可在Form1.cs[设计] 中点击工具箱,添加HsmarkWindowControl或HWindowControl 到窗口,并添加button来控制图片的显示和处理。
Form1.cs 中先引用halcon
先在Form1的类中定义halcon导出的类
1 2 HDevelopExport hd = new HDevelopExport(); HWindow hwindow; // 窗口
在Form1的创建函数(public Form1)中
1 2 hwindow = hSmartWindowControl1.HalconWindow; hd.InitHalcon();
然后button的点击函数中使用hancon类的处理函数
这时,最简单的halcon导出便完成了。
图片的缩放功能 在Form1的类中先创建my_MouseWheel函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 private void my_MouseWheel (object sender, MouseEventArgs e ) { System.Drawing.Point pt = this .Location; int leftBorder = hSmartWindowControl1.Location.X; int rightBorder = hSmartWindowControl1.Location.X + hSmartWindowControl1.Size.Width; int topBorder = hSmartWindowControl1.Location.Y; int bottomBorder = hSmartWindowControl1.Location.Y + hSmartWindowControl1.Size.Height; if (e.X > leftBorder && e.X<rightBorder && e.Y> topBorder && e.Y<bottomBorder) { MouseEventArgs newe = new MouseEventArgs(e.Button, e.Clicks, e.X - pt.X, e.Y - pt.Y, e.Delta); hSmartWindowControl1.HSmartWindowControl_MouseWheel(sender, newe); } }
在Form1的创建函数(public Form1)中监听
1 this .MouseWheel += new System.Windows.Forms.MouseEventHandler(this .my_MouseWheel);
读取任意图片(打开资源管理器选择) 打开资源管理器选择图片获取图片的地址
1 2 3 4 OpenFileDialog ofd = new OpenFileDialog(); if (ofd.ShowDialog() != DialogResult.OK) return ; string fileName = ofd.FileName;
图片显示
1 2 3 4 5 6 HObject ho_image = new HObject(); HOperatorSet.ReadImage(out ho_image, fileName); HTuple hv_width, hv_height; HOperatorSet.GetImageSize(ho_image, out hv_width, out hv_height); HOperatorSet.DispObj(ho_image, hwindow);
或
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 public void readImage (out HObject ho_Image, HTuple hv_address ) { HTuple hv_Width = new HTuple(), hv_Height = new HTuple(); HTuple hv_WindowID = new HTuple(); HOperatorSet.GenEmptyObj(out ho_Image); ho_Image.Dispose(); HOperatorSet.ReadImage(out ho_Image, hv_address); hv_Width.Dispose();hv_Height.Dispose(); HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height); using (HDevDisposeHelper dh = new HDevDisposeHelper()) { hv_WindowID.Dispose(); dev_open_window_fit_image(ho_Image, 0 , 0 , hv_Width/10 , hv_Height/10 , out hv_WindowID); } HOperatorSet.DispObj(ho_Image, hv_ExpDefaultWinHandle); hv_Width.Dispose(); hv_Height.Dispose(); hv_WindowID.Dispose(); return ; }