摘要
机器视觉中经常要用vs(c#版)联合halcon做winform界面开发,那么如何对其进行环境配置呢?
以最简单的readimage为例,本篇总结一下如何进行环境配置以及相关问题的解决。
1️⃣halcon生成库,供c#调用
用halcon读取一张图片,然后导出为c#语言
2️⃣在vs中配置环境,并编写读取图像界面
一,创建vs工程,配置环境
- 打开halcon文件所在目录(以本电脑为例),将D:\MVTec\halcon19\bin\dotnet35下的halcondotnet.dll文件放入vs文件的debug目录下。
- 在vs工程中的引用下添加halcondotnet.dll引用
- 引用halcondotnet.dll命名空间(using HalconDotNet;)
二,添加readimage类(封装该类,便于后续调用)
三,编写界面,并编写代码
readimage类代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HalconDotNet;
namespace readimage
{
class readimage
{
//定义全局变量
public HTuple Hwindows;//定义窗口句柄
HObject currentImg;//定义图像
HTuple imageWidth, imageHeight;//定义宽高
//定义加载图像函数
public void loadimg(HWindowControl HW,string Path)
{
//把当前控件绑定到Hwindows
Hwindows = HW.HalconWindow;
//读取图像
HOperatorSet.ReadImage(out currentImg, Path);
//自适应显示大小
HOperatorSet.GetImageSize(currentImg, out imageWidth, out imageHeight);
HOperatorSet.SetPart(Hwindows, 0, 0, imageHeight-1, imageWidth-1);
//显示图像
HOperatorSet.DispObj(currentImg, Hwindows);
}
}
}
调用readimage类进行图像读取显示:
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 readimage
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
readimage read = new readimage();//对新建类实例化
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofg = new OpenFileDialog())
{
ofg.Filter = "图片|*.jpg;*.png;";//设置选取格式
ofg.Multiselect = false;//不支持多选
ofg.Title = "图片获取";
if (ofg.ShowDialog()==DialogResult.OK)
{
read.loadimg(hWindowControl1,ofg.FileName);
}
}
}
}
}