这两种文件格式其实是很少使用到的,我主要是最近有一个项目需要往图片上写字,并且保存。halcon其实是没有这种功能的,所以只能是用到opencvsharp,然后就涉及到这两种格式的互传了。
因为都是在C#里面,为了追求快速简洁,我选择直接用数据的指针。我看到网上也有使用将数据拿出来数组中,再利用数组去生成,这种方法也是可行的,这里就不讨论。
hoject转mat:
public void HobjectToMat(HObject ho_Img, out Mat dst)
{
dst = new Mat();
HTuple ht_Channels = null;
HTuple ht_Type = null;
HTuple ht_Width = null, ht_Height = null;
try
{
HOperatorSet.CountChannels(ho_Img, out ht_Channels);
if (ht_Channels.Length == 0)
{
return;
}
if (ht_Channels[0].I == 1)
{
HTuple ht_Pointer = null;
IntPtr intPtr = IntPtr.Zero;
HOperatorSet.GetImagePointer1(ho_Img, out ht_Pointer, out ht_Type, out ht_Width, out ht_Height);
intPtr = ht_Pointer;
dst = Mat.FromPixelData(ht_Height, ht_Width, MatType.CV_8UC1, intPtr);
}
else if (ht_Channels[0].I == 3)
{
HTuple ht_ptrRed = null;
HTuple ht_ptrGreen = null;
HTuple ht_ptrBlue = null;
IntPtr ptrRed = IntPtr.Zero;
IntPtr ptrGreen = IntPtr.Zero;
IntPtr ptrBlue = IntPtr.Zero;
HOperatorSet.GetImagePointer3(ho_Img, out ht_ptrRed, out ht_ptrGreen, out ht_ptrBlue, out ht_Type, out ht_Width, out ht_Height);
ptrRed = ht_ptrRed;
ptrGreen = ht_ptrGreen;
ptrBlue = ht_ptrBlue;
//分别生成3张图片
Mat matRed = new Mat();
Mat matGreen = new Mat();
Mat matBlue = new Mat();
matRed = Mat.FromPixelData(ht_Height, ht_Width, MatType.CV_8UC1, ptrRed);
matGreen = Mat.FromPixelData(ht_Height, ht_Width, MatType.CV_8UC1, ptrGreen);
matBlue = Mat.FromPixelData(ht_Height, ht_Width, MatType.CV_8UC1, ptrBlue);
//合成
Mat[] multi = new Mat[] { matBlue, matGreen, matRed };
Cv2.Merge(multi, dst);
//释放
matBlue.Dispose();
matGreen.Dispose();
matRed.Dispose();
}
}
catch (Exception ex)
{
}
}
mat转hobject:
public void MatToHObject(Mat src, out HObject ho_Img)
{
ho_Img = new HObject();
try
{
//判断图片通道数
if (src.Channels() == 1)
{
unsafe
{
HOperatorSet.GenImage1(out ho_Img, "byte", src.Width, src.Height, src.Data);
}
}
else if (src.Channels() == 3)
{
//分割为BGR3张图片,halcon为RGB图
Mat[] mats = new Mat[3];
Cv2.Split(src, out mats);
unsafe
{
HOperatorSet.GenImage3(out ho_Img, "byte", src.Width, src.Height, mats[2].Data, mats[1].Data, mats[0].Data);
}
}
}
catch (Exception ex)
{
}
}
这里使用opencvsharp需要提前在NuGet上下载,版本随个人需求。