Halcon联合C#编程

Halcon联合C#编程

Halcon联合C#编程目前我知晓的有三种方式:1、将Halcon代码导成C#代码然后复制到C#程序中;2、直接采用C#中的Halcon库语句进行程序编写(难度有点大,其实就是第一种的另一种操作); 3、利用Halcon引擎直接在C#中调用Halcon程序,(电脑上必须安装Halcon软件,这是前两种的优势,但它的优势在于可以直接在Halcon改代码后C#中直接观察效果,可以节省很大的工作量)。
ps:我使用的是Halcon17.12(32bit)联合VS2015,只能在VS2015中生成32bit的程序,如果想生成64bit的程序,可以采用Halcon17.12(64bit)联合VS2015编程,Halcon17.12(32bit)的方式一模一样。

一、Halcon导成C#代码

1.1 编写Halcon代码
Halcon代码如下:
Halcon联合C#编程_第1张图片
运行结果如下
Halcon联合C#编程_第2张图片
将Halcon代码导成C#代码
Halcon联合C#编程_第3张图片
导成C#的Halcon代码

/
// File generated by HDevelop for HALCON/.NET (C#) Version 17.12
//

using HalconDotNet;

public partial class HDevelopExport
{
#if !(NO_EXPORT_MAIN || NO_EXPORT_APP_MAIN)
  public HDevelopExport()
  {
    // Default settings used in HDevelop 
    HOperatorSet.SetSystem("width", 512);
    HOperatorSet.SetSystem("height", 512);
    if (HalconAPI.isWindows)
      HOperatorSet.SetSystem("use_window_thread","true");
    action();
  }
#endif

#if !NO_EXPORT_MAIN
  // Main procedure 
  private void action()
  {


    // Local iconic variables 

    HObject ho_Circle, ho_Rectangle, ho_PolygonRegion;

    // Local control variables 

    HTuple hv_WindowHandle = null, hv_Row = null;
    HTuple hv_Column = null, hv_Radius = null, hv_Row1 = null;
    HTuple hv_Column1 = null, hv_Row2 = null, hv_Column2 = null;
    // Initialize local and output iconic variables 
    HOperatorSet.GenEmptyObj(out ho_Circle);
    HOperatorSet.GenEmptyObj(out ho_Rectangle);
    HOperatorSet.GenEmptyObj(out ho_PolygonRegion);

    HOperatorSet.SetWindowAttr("background_color","black");
    HOperatorSet.OpenWindow(0,0,512,512,0,"visible","",out hv_WindowHandle);
    HDevWindowStack.Push(hv_WindowHandle);
    if (HDevWindowStack.IsOpen())
    {
      HOperatorSet.SetDraw(HDevWindowStack.GetActive(), "fill");
    }
    HOperatorSet.DrawCircle(hv_WindowHandle, out hv_Row, out hv_Column, out hv_Radius);
    ho_Circle.Dispose();
    HOperatorSet.GenCircle(out ho_Circle, hv_Row, hv_Column, hv_Radius);
    if (HDevWindowStack.IsOpen())
    {
      HOperatorSet.DispObj(ho_Circle, HDevWindowStack.GetActive());
    }
    HOperatorSet.DrawRectangle1(hv_WindowHandle, out hv_Row1, out hv_Column1, out hv_Row2, 
        out hv_Column2);
    ho_Rectangle.Dispose();
    HOperatorSet.GenRectangle1(out ho_Rectangle, hv_Row1, hv_Column1, hv_Row2, hv_Column2);
    if (HDevWindowStack.IsOpen())
    {
      HOperatorSet.DispObj(ho_Rectangle, HDevWindowStack.GetActive());
    }
    ho_PolygonRegion.Dispose();
    HOperatorSet.DrawPolygon(out ho_PolygonRegion, hv_WindowHandle);
    if (HDevWindowStack.IsOpen())
    {
      HOperatorSet.DispObj(ho_PolygonRegion, HDevWindowStack.GetActive());
    }

    ho_Circle.Dispose();
    ho_Rectangle.Dispose();
    ho_PolygonRegion.Dispose();

  }

#endif


}
#if !(NO_EXPORT_MAIN || NO_EXPORT_APP_MAIN)
public class HDevelopExportApp
{
  static void Main(string[] args)
  {
    new HDevelopExport();
  }
}
#endif

1.2 创建VS程序
新建VS程序,并配置好环境,参考三中的配置过程。
如图,左边为HWindowControl控件
Halcon联合C#编程_第4张图片

在Form.cs中添加导成C#的Halcon代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;

namespace HalconCSharp
{
    public partial class Form1 : Form
    {
        HObject ho_Circle, ho_Rectangle, ho_PolygonRegion;

        // Local control variables 

        HTuple hv_WindowHandle = null, hv_Row = null;
        HTuple hv_Column = null, hv_Radius = null, hv_Row1 = null;
        HTuple hv_Column1 = null, hv_Row2 = null, hv_Column2 = null;

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            ho_Circle.Dispose();
            ho_Rectangle.Dispose();
            ho_PolygonRegion.Dispose();
        }

        HTuple WindowID;

        public Form1()
        {
            InitializeComponent();
            HOperatorSet.GenEmptyObj(out ho_Circle);
            HOperatorSet.GenEmptyObj(out ho_Rectangle);
            HOperatorSet.GenEmptyObj(out ho_PolygonRegion);           
        }

        private void btn_DrawCircle_Click(object sender, EventArgs e)
        {
            HOperatorSet.DrawCircle(hv_WindowHandle, out hv_Row, out hv_Column, out hv_Radius);
            ho_Circle.Dispose();
            HOperatorSet.GenCircle(out ho_Circle, hv_Row, hv_Column, hv_Radius);
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.DispObj(ho_Circle, HDevWindowStack.GetActive());
            }
        }

        private void btn_DrawRect_Click(object sender, EventArgs e)
        {
            HOperatorSet.DrawRectangle1(hv_WindowHandle, out hv_Row1, out hv_Column1, out hv_Row2,
        out hv_Column2);
            ho_Rectangle.Dispose();
            HOperatorSet.GenRectangle1(out ho_Rectangle, hv_Row1, hv_Column1, hv_Row2, hv_Column2);
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.DispObj(ho_Rectangle, HDevWindowStack.GetActive());
            }
        }

        private void btn_DrawPolyn_Click(object sender, EventArgs e)
        {
            ho_PolygonRegion.Dispose();
            HOperatorSet.DrawPolygon(out ho_PolygonRegion, hv_WindowHandle);
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.DispObj(ho_PolygonRegion, HDevWindowStack.GetActive());
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            WindowID = hWindowControl1.HalconWindow;
            HOperatorSet.SetSystem("width", 512);
            HOperatorSet.SetSystem("height", 512);
            HOperatorSet.SetWindowAttr("background_color", "blue");
            HOperatorSet.OpenWindow(0, 0, 512, 512, WindowID, "visible", "", out hv_WindowHandle);
            if (HalconAPI.isWindows)
                HOperatorSet.SetSystem("use_window_thread", "true");
            HDevWindowStack.Push(hv_WindowHandle);
            if (HDevWindowStack.IsOpen())
            {
                HOperatorSet.SetDraw(HDevWindowStack.GetActive(), "fill");
            }
        }
    }
}

1.3 运行看效果
完美运行
Halcon联合C#编程_第5张图片

二、直接在C#中利用Halcon语句编程

2.1 新建项目,配置好环境,添加控件,坐标黑色为HWindowControl。
Halcon联合C#编程_第6张图片
2.2 添加代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;

namespace HalconDraw
{
    public partial class Form1 : Form
    {
        //窗口句柄
        private HTuple WindowHandle;
        //Halcon窗口
        private HWindow Window;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //设置清晰度
            //HOperatorSet.SetSystem("width", 512);
            //HOperatorSet.SetSystem("height", 512);
            HOperatorSet.SetWindowAttr("background_color", "blue");//设置窗体背景色
            Window = hWindowControl1.HalconWindow;
            HOperatorSet.OpenWindow(0, 0, hWindowControl1.Width, hWindowControl1.Height, Window, "visible", "", out WindowHandle);
        }

        private void btn_DrawCircle_Click(object sender, EventArgs e)
        {
            HTuple row, col, radius;
            HOperatorSet.DrawCircle(WindowHandle, out row, out col, out radius);
            HObject circle;
            HOperatorSet.GenCircle(out circle, row, col, radius);
            HOperatorSet.DispObj(circle, WindowHandle);
        }

        private void btn_DrawRect_Click(object sender, EventArgs e)
        {
            HTuple row1, col1, row2, col2;
            HOperatorSet.DrawRectangle1(WindowHandle, out row1, out col1, out row2, out col2);
            HObject rect;
            HOperatorSet.GenRectangle1(out rect, row1, col1, row2, col2);
            HOperatorSet.DispObj(rect, WindowHandle);
        }

        private void btn_DrawPolyn_Click(object sender, EventArgs e)
        {
            HObject polygon;
            HOperatorSet.DrawPolygon(out polygon, WindowHandle);
            HOperatorSet.DispObj(polygon, WindowHandle);
        }
    }
}

上图程序中用的到方法都可以通过Halcon的帮助文档进行查询,点击红色箭头指向的地方就可以获得对应方法的C#方法。
Halcon联合C#编程_第7张图片
2.3 运行
Halcon联合C#编程_第8张图片
上图的圆和多边形都出现锯齿状,原因是清晰度没有设置,将上面程序的下面部分加入程序中,再运行,完美运行!

            //设置清晰度
            //HOperatorSet.SetSystem("width", 512);
            //HOperatorSet.SetSystem("height", 512);

Halcon联合C#编程_第9张图片
不过这一种方法比较麻烦,需要从halcon的帮助文档中查询相关的方法,其实它可以作为第一种方法的补充方法,在Halcon导成C#代码后,在一些简单需要更改的地方,采用这种方法修改代码可以节省导出代码并添加到C#程序中的过程,提高编程的效率。

三、利用Halcon的引擎

3.1 新建和配置VS程序
将halcondotnet.dll和hdevenginedotnet.dll两个文件复制到VS程序的源码文件夹内。
Halcon联合C#编程_第10张图片
再将两个dll文件添加到程序的引用中。
Halcon联合C#编程_第11张图片
将下图路径中的文件全部复制到VS程序的源码文件夹。
Halcon联合C#编程_第12张图片
为了使用VS中自带的Halcon窗口,右击工具箱选择选择项,
Halcon联合C#编程_第13张图片

Halcon联合C#编程_第14张图片
点击浏览,然后选择下图路径中halcondotnet.dll文件,

Halcon联合C#编程_第15张图片

出现并选中了H开头的组件,点击确定,
Halcon联合C#编程_第16张图片
工具箱出现了H开头的工具。这两个控件就可以直接使用啦,一会再程序中有使用。至于他们的区别,可以参考两个控件的区别。
Halcon联合C#编程_第17张图片
3.2 ProgramCall方式调用需要的Halcon程序
在Halcon中创建一个程序,问了方便我就直接打开一个Halcon的例子。
Halcon联合C#编程_第18张图片
为了便于观察效果,对里面的代码稍作修改,如下:

* The following example shows a production line, which carries
* packages of soft cheese. The cheese packages consist of three
* types of flavor: cream, ham and paprika. During quality
* inspection each package is checked for its right content.
* Each has to contain 4 pieces of cream cheese ('Sahne'),
* 2 pieces of ham ('Schinken') and 2 pieces of paprika ('Paprika')
* - any deviation is reported otherwise. To obtain the number of
* each flavor, we use the shape-based matching feature. After we
* define the models, we count the occurrence of the models to
* get the actual number of the cheese flavors. Finally we give out
* the statistics for each inspection.
* 
dev_close_window ()
dev_update_off ()
read_image (Image, 'food/soft_cheese_01')
dev_open_window_fit_image (Image, 0, 0, -1, -1, WindowHandle)
set_display_font (WindowHandle, 14, 'mono', 'true', 'false')
dev_set_line_width (2)
* 
* 
* As a first step, determine the shape models for the three flavors
rgb1_to_gray (Image, GrayImage)
gen_region_polygon_filled (Paprika, [77,84,203], [306,405,347])
erosion_circle (Paprika, Paprika, 3.5)
PaprikaCount := 2
gen_region_polygon_filled (Cream, [94,171,210], [424,488,363])
erosion_circle (Cream, Cream, 3.5)
CreamCount := 4
gen_region_polygon_filled (Ham, [185,285,225], [496,492,367])
erosion_circle (Ham, Ham, 3.5)
HamCount := 2
* 
reduce_domain (GrayImage, Paprika, ImageReduced)
create_shape_model (ImageReduced, 'auto', 0, rad(360), rad(1.5), ['point_reduction_high','no_pregeneration'], 'use_polarity', [25,30], 5, ModelID1)
reduce_domain (GrayImage, Cream, ImageReduced)
create_shape_model (ImageReduced, 'auto', 0, rad(360), rad(1.5), ['point_reduction_high','no_pregeneration'], 'use_polarity', [25,50], 'auto', ModelID2)
reduce_domain (GrayImage, Ham, ImageReduced)
create_shape_model (ImageReduced, 'auto', 0, rad(360), rad(1.5), ['point_reduction_high','no_pregeneration'], 'use_polarity', [25,50], 'auto', ModelID3)
* 
* 
* Check for the occurrence of each cheese flavor by using the find model tool
ModelIDs := [ModelID1,ModelID2,ModelID3]
ColorIndex := ['red','magenta','yellow']
TypesIndex := ['P','C','H']
* 
NumImages := 18
for Index := 1 to NumImages by 1
    AnglesTypes := []
    Types := []
    read_image (Image, 'food/soft_cheese_' + Index$'02')
    rgb1_to_gray (Image, GrayImage)
    threshold (GrayImage, Region, 70, 255)
    fill_up (Region, RegionFillUp)
    opening_circle (RegionFillUp, RegionOpening, 3.5)
    reduce_domain (GrayImage, RegionOpening, ImageReduced)
    shape_trans (RegionOpening, Circle, 'outer_circle')
    find_shape_models (ImageReduced, ModelIDs, 0, rad(360), 0.5, 8, 0.5, 'least_squares', 0, 0.8, Row, Column, Angle, Score, ModelIndex)
    area_center (Circle, Area, RowObj, ColumnObj)
    * 
    * display found matches and all over statistics
    dev_clear_window ()
    dev_display (Image)
    if (|Score| == 0)
        disp_message (WindowHandle, 'No Model found!', true, 25, 20, 'black', 'true')
    else
        CountModels := [0,0,0]
        for I := 0 to |Score| - 1 by 1
            Types := [Types,TypesIndex[ModelIndex[I]]]
            dev_set_color (ColorIndex[ModelIndex[I]])
            CountModels[ModelIndex[I]] := CountModels[ModelIndex[I]] + 1
            get_shape_model_contours (Contour, ModelIDs[ModelIndex[I]], 1)
            vector_angle_to_rigid (0, 0, 0, Row[I], Column[I], Angle[I], HomMat2D)
            affine_trans_contour_xld (Contour, ContoursAffineTrans, HomMat2D)
            dev_display (ContoursAffineTrans)
            * 
            * remember order of flavors
            affine_trans_point_2d (HomMat2D, 0, 0, RowPiece, ColumnPiece)
            angle_lx (RowObj, ColumnObj, RowPiece, ColumnPiece, AngleTyp)
            if (deg(AngleTyp) > 0)
                AnglesTypes := [AnglesTypes,deg(AngleTyp)]
            else
                AnglesTypes := [AnglesTypes,360 + deg(AngleTyp)]
            endif
        endfor
        * 
        display_statistic (Circle, WindowHandle, CountModels, PaprikaCount, CreamCount, HamCount, AnglesTypes, Types)
                disp_message (WindowHandle, Index, 'window', 430, 430, 'red', 'true')
        * 
    endif
    if (Index < NumImages)
        disp_continue_message (WindowHandle, 'black', 'true')
        stop ()
    endif
endfor
clear_shape_model (ModelID1)
clear_shape_model (ModelID2)
clear_shape_model (ModelID3)

运行效果
Halcon联合C#编程_第19张图片
将程序另存为自己喜欢的路径,一会需要调用。
3.3 ProduceCall方式调用的Halcon程序
创建一个函数
Halcon联合C#编程_第20张图片
函数的参数,再配置好参数文档即可。
Halcon联合C#编程_第21张图片
函数的代码:

set_display_font (WindowID, 14, 'mono', 'true', 'false')
dev_set_line_width (2)
* 
* 
* As a first step, determine the shape models for the three flavors
rgb1_to_gray (Image, GrayImage)
dev_display (GrayImage)
gen_region_polygon_filled (Paprika, [77,84,203], [306,405,347])
erosion_circle (Paprika, Paprika, 3.5)
dev_display (Paprika)
PaprikaCount := 2
gen_region_polygon_filled (Cream, [94,171,210], [424,488,363])
erosion_circle (Cream, Cream, 3.5)
dev_display (Cream)
CreamCount := 4
gen_region_polygon_filled (Ham, [185,285,225], [496,492,367])
erosion_circle (Ham, Ham, 3.5)
dev_display (Ham)
HamCount := 2
* 
reduce_domain (GrayImage, Paprika, ImageReduced)
dev_display (ImageReduced)
create_shape_model (ImageReduced, 'auto', 0, rad(360), rad(1.5), ['point_reduction_high','no_pregeneration'], 'use_polarity', [25,30], 5, ModelID1)
reduce_domain (GrayImage, Cream, ImageReduced)
dev_display (ImageReduced)
create_shape_model (ImageReduced, 'auto', 0, rad(360), rad(1.5), ['point_reduction_high','no_pregeneration'], 'use_polarity', [25,50], 'auto', ModelID2)
reduce_domain (GrayImage, Ham, ImageReduced)
dev_display (ImageReduced)
create_shape_model (ImageReduced, 'auto', 0, rad(360), rad(1.5), ['point_reduction_high','no_pregeneration'], 'use_polarity', [25,50], 'auto', ModelID3)
* 
* 
* Check for the occurrence of each cheese flavor by using the find model tool
ModelIDs := [ModelID1,ModelID2,ModelID3]
ColorIndex := ['red','magenta','yellow']
TypesIndex := ['P','C','H']
* 
NumImages := 18
for Index := 1 to NumImages by 1
    AnglesTypes := []
    Types := []
    read_image (Image, ImagePath + Index$'02')
    rgb1_to_gray (Image, GrayImage)
    threshold (GrayImage, Region, 70, 255)
    fill_up (Region, RegionFillUp)
    opening_circle (RegionFillUp, RegionOpening, 3.5)
    reduce_domain (GrayImage, RegionOpening, ImageReduced)
    shape_trans (RegionOpening, Circle, 'outer_circle')
    find_shape_models (ImageReduced, ModelIDs, 0, rad(360), 0.5, 8, 0.5, 'least_squares', 0, 0.8, Row, Column, Angle, Score, ModelIndex)
    area_center (Circle, Area, RowObj, ColumnObj)
    * 
    * display found matches and all over statistics
    dev_clear_window ()
    dev_display (Image)
    if (|Score| == 0)
        disp_message (WindowID, 'No Model found!', true, 25, 20, 'black', 'true')
    else
        CountModels := [0,0,0]
        for I := 0 to |Score| - 1 by 1
            Types := [Types,TypesIndex[ModelIndex[I]]]
            dev_set_color (ColorIndex[ModelIndex[I]])
            CountModels[ModelIndex[I]] := CountModels[ModelIndex[I]] + 1
            get_shape_model_contours (Contour, ModelIDs[ModelIndex[I]], 1)
            vector_angle_to_rigid (0, 0, 0, Row[I], Column[I], Angle[I], HomMat2D)
            affine_trans_contour_xld (Contour, ContoursAffineTrans, HomMat2D)
            dev_display (ContoursAffineTrans)
            * 
            * remember order of flavors
            affine_trans_point_2d (HomMat2D, 0, 0, RowPiece, ColumnPiece)
            angle_lx (RowObj, ColumnObj, RowPiece, ColumnPiece, AngleTyp)
            if (deg(AngleTyp) > 0)
                AnglesTypes := [AnglesTypes,deg(AngleTyp)]
            else
                AnglesTypes := [AnglesTypes,360 + deg(AngleTyp)]
            endif
        endfor
        * 
        display_statistic (Circle, WindowID, CountModels, PaprikaCount, CreamCount, HamCount, AnglesTypes, Types)
        disp_message (WindowID, Index, 'window', 440, 440, 'red', 'true')
        * 
    endif
    if (Index < NumImages)
        disp_continue_message (WindowID, 'black', 'true')
        wait_seconds (0.5)
*         stop ()
    endif
endfor
clear_shape_model (ModelID1)
clear_shape_model (ModelID2)
clear_shape_model (ModelID3)
* 
return ()

将函数保存到以毁需要调用的路径下,选择好函数类型 *.hdev。
Halcon联合C#编程_第22张图片

在主程序中添加如下代码:

dev_close_window()
read_image (Image, 'food/soft_cheese_01')
dev_open_window_fit_image (Image, 0, 0, -1, -1, WindowHandle)
dev_display (Image)
ModelMatch2 (Image, 'food/soft_cheese_', WindowHandle)

运行效果图
Halcon联合C#编程_第23张图片
保存主程序到与函数相同的路径。Halcon程序建立完毕!

3.4 编写VS程序

在Form上添加如下控件,左边控件为之前加载的HWinddowControl控件。
Halcon联合C#编程_第24张图片
在Form代码文件内添加如下代码:

using HalconDotNet;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Halcon
{
    public partial class Form1 : Form
    {
        #region
        private HDevEngine MyEngine = new HDevEngine();
        // 实例化程序触发器
        private HDevProgramCall ProgramCall;
        //实例化函数触发器
        private HDevProcedureCall ProcedureCall;
        //声明一个WindowID
        private HTuple WindowID;
        //外部函数存放路径
        private string OutProPath;
        //模板图片
        private HObject ModelImage;
        //图片路径
        private string PicPath = "C:\\Users\\Public\\Documents\\MVTec\\HALCON-17.12-Progress\\examples\\images\\food\\soft_cheese_";
        #endregion

        public Form1()
        {
            InitializeComponent();
            CreateHalocnWindow();//创建Halcon窗体并打开
        }
        /// 
        /// 创建Halcon窗体并打开
        /// 
        private void CreateHalocnWindow()
        {
            HOperatorSet.SetWindowAttr("background_color", "blue");//设置窗体背景色
            HOperatorSet.OpenWindow(0, 0, hWinCtr_Show.Width, hWinCtr_Show.Height, hWinCtr_Show.HalconWindow, "visible", "", out WindowID);
        }

        private void btn_LoadProList_Click(object sender, EventArgs e)
        {
            //获取 外部函数存放路径
            FolderBrowserDialog ProcedurePath = new FolderBrowserDialog();
            //如果未成功获取
            if (ProcedurePath.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
            {
                return;
            }
            else //绑定并显示 开放读取程序路径控件
            {
                //设定外部函数路径
                MyEngine.SetProcedurePath(ProcedurePath.SelectedPath.Trim());
                //显示路径
                txt_ProList.Text = "外部函数库目录:" + ProcedurePath.SelectedPath.Trim();
                //开放读取程序路径控件
                btn_SelectPro.Enabled = true;
                OutProPath = ProcedurePath.SelectedPath.Trim();
            }
        }

        private void btn_SelectPro_Click(object sender, EventArgs e)
        {
            //获取程序路径
            OpenFileDialog Program_path = new OpenFileDialog();
            //设定允许单选
            Program_path.Multiselect = false;
            //选择框限定文件类型
            Program_path.Filter = "hdev files(*.hdev)|*.hdev|All files(*.*)|*.*";
            //设置文件默认打开路径
            Program_path.InitialDirectory = OutProPath;
            //限定成功读取路径
            if (Program_path.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //通过路径实例化程序
                HDevProgram Program = new HDevProgram(Program_path.FileName);
                /************************************************************
                 * 在载入Halcon外部程序之前 需要检查程序里使用的外部函数是否
                 * 在函数目录里面已经定义好否者会报错 缺少哪些函数的名称
                 ************************************************************/
                Halcon函数对象
                HDevProcedure Procedure = new HDevProcedure(Program,"ModelMatch2");
                绑定程序到函数触发器
                ProcedureCall = new HDevProcedureCall(Procedure);
                //绑定程序到程序触发器
                ProgramCall = new HDevProgramCall(Program);
                //显示路径
                txt_ProPath.Text = "程序路径:" + Program_path.FileName;
                //开放执行控件
                btn_LoadPic.Enabled = true;

            }
        }

        private void btn_RunPro_Click(object sender, EventArgs e)
        {
            //将引擎绑定到窗口
            MyEngine.SetHDevOperators(new HDevOpMultiWindowImpl(WindowID));
            try
            {
                PicPath=PicPath.Replace('\\','/');
                //函数触发器
                #region
                //配置输入参数
                ProcedureCall.SetInputIconicParamObject("Image", ModelImage);
                ProcedureCall.SetInputCtrlParamTuple("ImagePath", PicPath);
                ProcedureCall.SetInputCtrlParamTuple("WindowID", WindowID);
                //执行程序:函数触发
                Task.Factory.StartNew(() => ProcedureCall.Execute());//新开线程执行Halcon代码
                //获取数据 只有执行后才能获取

                #endregion

                //MessageBox.Show("代码结束");
            }
            catch (HDevEngineException Ex)
            {
                MessageBox.Show(Ex.Message, "HDevEngine Exception");
                return;
            }
            // 展示结果

        }

        private void btn_RunSinglePro_Click(object sender, EventArgs e)
        {
            //获取程序路径
            OpenFileDialog Program_path = new OpenFileDialog();
            //设定允许单选
            Program_path.Multiselect = false;
            //选择框限定文件类型
            Program_path.Filter = "hdev files(*.hdev)|*.hdev|All files(*.*)|*.*";
            //限定成功读取路径
            if (Program_path.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //通过路径实例化程序
                HDevProgram Program = new HDevProgram(Program_path.FileName);
                /************************************************************
                 * 在载入Halcon外部程序之前 需要检查程序里使用的外部函数是否
                 * 在函数目录里面已经定义好否者会报错 缺少哪些函数的名称
                 ************************************************************/
                //绑定程序到程序触发器
                ProgramCall = new HDevProgramCall(Program);
                //显示路径
                txt_SingleProPath.Text = "程序路径:" + Program_path.FileName;
            }

            //将引擎绑定到窗口
            MyEngine.SetHDevOperators(new HDevOpMultiWindowImpl(WindowID));
            //执行程序:程序触发
            Task.Factory.StartNew(() => ProgramCall.Execute());
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            btn_SelectPro.Enabled = false;
            btn_RunPro.Enabled = false;
            btn_LoadPic.Enabled = false;
        }
        /// 
        /// 加载模板图片并显示
        /// 
        /// 
        /// 
        private void btn_LoadPic_Click(object sender, EventArgs e)
        {
            HOperatorSet.ReadImage(out ModelImage, PicPath+"01");
            HTuple Width = null, Height = null;
            HOperatorSet.GetImageSize(ModelImage, out Width, out Height);
            HOperatorSet.SetPart(WindowID, 0, 0, Height, Width);
            HOperatorSet.DispObj(ModelImage, WindowID);
            btn_RunPro.Enabled = true;
        }
    }
}


VS中可以采用程序触发ProgramCall和函数触发ProcedureCall,中文名字是我自己为了区别取的,官方的叫法没有查,有兴趣的可以自己去了解,运行程序之上的部分采用的是ProcedureCall,单独运行一个程序使用的是ProgramCall,将配置改为X86,点击运行。
Halcon联合C#编程_第25张图片
选择好程序后如下图:
Halcon联合C#编程_第26张图片
点击加载模板图片
Halcon联合C#编程_第27张图片
点击运行程序,完美运行!
Halcon联合C#编程_第28张图片
点击单独运行一个程序,完美运行!
Halcon联合C#编程_第29张图片

这种方法的效率最高,但是调试的过程无法控制,有利有弊吧!看具体的情况而定。

四、采用Halcon17.12(64bit)联合VS2015编程

安装好Halcon17.12(64bit)版本。新建VS2015项目,配置好环境。
将配置管理器设置为X64
在这里插入图片描述

在ui上添加控件,左边黑色控件为HWindowControl。
Halcon联合C#编程_第30张图片
在代码区添加如下代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using HalconDotNet;

namespace Halcon64bit2
{
    public partial class Form1 : Form
    {
        HDevEngine myEngine = new HDevEngine();
        HDevProgramCall myProgramCall;
        HWindow Window;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btn_RunSinglePro_Click(object sender, EventArgs e)
        {
            //获取程序路径
            OpenFileDialog Program_path = new OpenFileDialog();
            //设定允许单选
            Program_path.Multiselect = false;
            //选择框限定文件类型
            Program_path.Filter = "hdev files(*.hdev)|*.hdev|All files(*.*)|*.*";
            //限定成功读取路径
            if (Program_path.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //通过路径实例化程序
                HDevProgram Program = new HDevProgram(Program_path.FileName);
                /************************************************************
                 * 在载入Halcon外部程序之前 需要检查程序里使用的外部函数是否
                 * 在函数目录里面已经定义好否者会报错 缺少哪些函数的名称
                 ************************************************************/
                //绑定程序到程序触发器
                myProgramCall = new HDevProgramCall(Program);
                //显示路径
                txt_SingleProPath.Text = "程序路径:" + Program_path.FileName;
            }

            Window = hWCtr_Show.HalconWindow;
            //将引擎绑定到窗口
            myEngine.SetHDevOperators(new HDevOpMultiWindowImpl(Window));
            Task.Factory.StartNew(() => myProgramCall.Execute());
        }
    }
}

运行,完美运行
Halcon联合C#编程_第31张图片

你可能感兴趣的:(Halcon,c#,.net)