WPF使用Halcon打开图片
1、新建WPF工程,在解决方案资源管理器中选中当前工程项目,鼠标右击,弹出右键菜单,移动鼠标点击【属性】,弹出属性界面,选择【生成】项,勾选中【允许不安全代码】

2、添加引用halcondotnet.dll,下载halcondotnet.dll、halcon.dll、halcondotnet.xml、halconxl.dll到生成目录下。并准备一张RGB图片,重命名为"1.jpeg"

3、在MainWindow.xaml页面中添加如下代码:
<Window x:Class="HalconTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350 <Grid Name="mygrid">
</Grid>
</Window>

4、在MainWindow.xaml.cs页面中添加如下代码:
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace HalconTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public unsafe MainWindow()
{
InitializeComponent();
HObject image;
HOperatorSet.ReadImage(out image, "1.jpeg");
HImage h_image = new HImage();
//HTuple pointer;
HTuple t;
HTuple w;
HTuple h;
HTuple pointerRed;
HTuple pointerGreen;
HTuple pointerBlue;
HOperatorSet.GetImagePointer3(image, out pointerRed, out pointerGreen, out pointerBlue, out t, out w, out h);
h_image.GenImage3(t, w, h, pointerRed, pointerGreen, pointerBlue);
string t2;
int w2;
int h2;
IntPtr pr, pg, pb;
h_image.GetImagePointer3(out pr, out pg, out pb, out t2, out w2, out h2);
int len = w * h;
byte[] datar = new byte[len];
byte[] datag = new byte[len];
byte[] datab = new byte[len];
Marshal.Copy(pr, datar, 0, len);
Marshal.Copy(pg, datag, 0, len);
Marshal.Copy(pb, datab, 0, len);
h_image.Dispose();
byte[] data = new byte[len * 3];
fixed (byte* bp = data, bbp = datab, brp = datar, bgp = datag)
{
byte* b = bp;
byte* bb = bbp;
byte* bg = bgp;
byte* br = brp;
for (int i = 0; i < len; i++)
{
*b = *bb; b++; bb++;
*b = *bg; b++; bg++;
*b = *br; b++; br++;
}
}
WriteableBitmap wb = new WriteableBitmap(w, h, 96, 96, System.Windows.Media.PixelFormats.Bgr24, null);
wb.WritePixels(new System.Windows.Int32Rect(0, 0, w, h), data, w * 3, 0);
mygrid.Background = new System.Windows.Media.ImageBrush(wb);
}
}
}

5、编译代码,生成解决方案。编译成功后,按F5执行。出现图像画面。

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。