1、从halcon中导出C#代码。先打开halcon,将需要显示的图片拖入halcon中,确定就会在halcon中插入已经读取图片的代码。简单方便快捷。
在增加几句代码,关闭显示窗口,获取图像宽高,按图像的比例打开一个显示窗口
dev_close_window ()
get_image_size (Test, Width, Height)
dev_open_window (0, 0, Width/3, Height/3, 'black', WindowHandle)
dev_display (Test)
导出C#代码
在导出的目录下找到导出的.cs文件,用VS打开
用的到代码有 ,下面三行
using HalconDotNet;
HOperatorSet.ReadImage(out ho_Test, "G:/VS_Project/Res/test.bmp");
HOperatorSet.DispObj(ho_Test, HDevWindowStack.GetActive());
2、在WinForm中添加一个本地图像按钮。双击进入事件中编辑代码
private void button1_Click(object sender, EventArgs e)
{
HObject ho_Test;
HOperatorSet.GenEmptyObj(out ho_Test);
HOperatorSet.ReadImage(out ho_Test, "G:/VS_Project/Res/test.bmp");
HOperatorSet.DispObj(ho_Test, hWindowControl1.HalconID);
}
运行显示如下,点击本地图像按钮即可在控件上显示图片。
这样显示的图像是不完全的,只显示了一部分,要将图像完整显示出来需要加如下代码。
private void button1_Click(object sender, EventArgs e)
{
HObject ho_Test;
HTuple hv_Width = null, hv_Height = null;
HOperatorSet.GenEmptyObj(out ho_Test);
HOperatorSet.ReadImage(out ho_Test, "G:/VS_Project/Res/test.bmp");
HOperatorSet.GetImageSize(ho_Test, out hv_Width, out hv_Height);
HOperatorSet.SetPart(hWindowControl1.HalconID, 0, 0,hv_Height,hv_Width);
HOperatorSet.DispObj(ho_Test, hWindowControl1.HalconID);
}
3.从电脑上自带的摄像头上采集图像,如果有相机的也可以用相机来采集。
用助手插入代码,将得到下面代码
* Image Acquisition 01: Code generated by Image Acquisition 01
open_framegrabber ('DirectShow', 1, 1, 0, 0, 0, 0, 'default', 8, 'rgb', -1, 'false', 'default', '[1] USB2.0 PC CAMERA', 0, -1, AcqHandle)
grab_image_start (AcqHandle, -1)
while (true)
grab_image_async (Image, AcqHandle, -1)
* Image Acquisition 01: Do something
endwhile
close_framegrabber (AcqHandle)
将代码导出C# 代码,在C# 界面上增加,两个按钮,
加入导出的代码。
private void action()
{
// Local iconic variables
HObject ho_Image = null;
// Local control variables
HTuple hv_AcqHandle = null;
// Initialize local and output iconic variables
HOperatorSet.GenEmptyObj(out ho_Image);
//Image Acquisition 01: Code generated by Image Acquisition 01
HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default", 8, "rgb",
-1, "false", "default", "[1] USB2.0 PC CAMERA", 0, -1, out hv_AcqHandle);
HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
while (!isExit)
{
ho_Image.Dispose();
HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconID);
}
HOperatorSet.CloseFramegrabber(hv_AcqHandle);
o_Image.Dispose();
}
在按钮事件上增加如下代码,即可实现采集功能。
bool isExit = false;
//采集图像
private void button2_Click(object sender, EventArgs e)
{
Task.Run(()=> {
isExit = false;
action();
});
}
//退出采集
private void button3_Click(object sender, EventArgs e)
{
isExit = true;
}