C#Halcon实现相机实时显示采集图像

c#创建窗体,预期功能为打开相机、图像抓拍、关闭相机,界面如下:

C#Halcon实现相机实时显示采集图像_第1张图片

 

Halcon代码如下:

*调用电脑摄像头
* Image Acquisition 01: Code generated by Image Acquisition 01
open_framegrabber ('DirectShow', 1, 1, 0, 0, 0, 0, 'default', 8, 'rgb', -1, 'false', 'default', '[0] USB2.0 HD UVC WebCam', 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#代码如下

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.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Demo_002
{
public partial class Camera : Form
{
public Camera()
{
InitializeComponent();
}
//批量增加注释:Ctrl + K Ctrl + C
//批量取消注释:Ctrl + K Ctrl + U
//F12反编译

//一个变量
HObject ho_Image = null;
//图像获取设备的句柄
HTuple hv_AcqHandle = null;
//定义抓拍控制变量
int snapcontorl = 0;
//线程标志
Thread thread = null;
//用于获取图片的大小
HTuple hv_Width = new HTuple();
HTuple hv_Height = new HTuple();


//按钮一:打开相机
private void button1_Click(object sender, EventArgs e)
{

// 初始化本地和输出图标变量
HOperatorSet.GenEmptyObj(out ho_Image);
//图像采集
HOperatorSet.OpenFramegrabber("DirectShow", 1, 1, 0, 0, 0, 0, "default",
8, "rgb", -1, "false", "default", "[0] USB2.0 HD UVC WebCam",0, -1, out hv_AcqHandle);

//启动异步抓取句柄和一个过期的默认值-1或者0
HOperatorSet.GrabImageStart(hv_AcqHandle, -1);
//线程
thread = new Thread(cameracontrol);
thread.IsBackground = true;
thread.Start();

HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
HOperatorSet.GetImageSize(ho_Image, out hv_Width, out hv_Height);
//参数1获取窗口的句柄,2 左上角的行默认0,3 左上角的列默认2,4 右下角的行默认-1,5 右下角的列默认-1
HOperatorSet.SetPart(hWindowControl1.HalconWindow, 0, 0, hv_Height - 1, hv_Width - 1);
}

//用于控制相机
private void cameracontrol()
{
while (true)
{
//使用前初始化ho_Image变量
ho_Image.Dispose();
//异步图像抓取(out 图像,句柄,默认值-1)
HOperatorSet.GrabImageAsync(out ho_Image, hv_AcqHandle, -1);
//实时显示
HOperatorSet.DispObj(ho_Image, hWindowControl1.HalconWindow);
if (snapcontorl == 1)
{
//保存图片
//将图片ho_Image,以jpg格式,值默认0,存放在D盘
HOperatorSet.WriteImage(ho_Image, "jpg", 0, @"D:\");
MessageBox.Show("照片已保存");
snapcontorl = 0;
}
else
{ }
}
}
//按钮二:抓拍图像
private void button2_Click(object sender, EventArgs e)
{
snapcontorl = 1;
}


//按钮三:关闭相机
private void button3_Click(object sender, EventArgs e)
{
//关闭线程
thread.Abort();

//关闭图像采集设备的句柄。
HOperatorSet.CloseFramegrabber(hv_AcqHandle);
}

private void hWindowControl1_HMouseMove(object sender, HMouseEventArgs e)
{

}
}
}

效果图:

C#Halcon实现相机实时显示采集图像_第2张图片

C#与Halcon联合编程实例陆续更新中。

你可能感兴趣的:(C#Halocn联合编程,c#,开发语言)