????????上次讲了bitmap 与hobject 格式的转换。这次讲一下 Mat 与hobject 格式转化方法。这种功能应该比较少有人会用到。因我主要做深度学习工业应用,我常用的图像库是opencv, 而自动化AOI部门主要用halcon,为了对接方便,我就研究了?这个内容。
????????关键点是如何将Mat 转为byte[],由于Mat 是非连续存储的,无法直接将Mat 转为数组,所以我采用一行一行循环的方式,为了提高速度,行内我采用内存复制的方式。如果采用逐点循环的方式,速度会比较慢。
?????????这个功能还是比较有用的,有次我看到opencv 群里面有个人到处询问如何将Mat 转为数组,但没人理他。
? ? ? ??
1.灰度图转换之Mat -> hobject
public void Mat2HObjectBpp8(Mat mat, out HObject image)
{
int ImageWidth = mat.Width;
int ImageHeight = mat.Height;
int channel = mat.Channels();
long size = ImageWidth * ImageHeight * channel;
int col_byte_num = ImageWidth * channel;
byte[] rgbValues = new byte[size];
//IntPtr imgptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(rgbValues.Length);
unsafe
{
for (int i = 0; i < mat.Height; i++)
{
IntPtr c = mat.Ptr(i);
//byte* c1 = (byte*)c;
System.Runtime.InteropServices.Marshal.Copy(c, rgbValues, i * col_byte_num, col_byte_num); // 一行一行将mat 像素复制到byte[],
}
void* p;
IntPtr ptr;
fixed (byte* pc = rgbValues)
{
p = (void*)pc;
ptr = new IntPtr(p);
}
HOperatorSet.GenImage1(out image, "byte", ImageWidth, ImageHeight, ptr);
}
}
? 2.灰度图转换之hobject-> Mat
public void HObject2Mat8(HObject image, out Mat res)
{
HTuple hpoint, type, width, height;
HOperatorSet.GetImagePointer1(image, out hpoint, out type, out width, out height);
IntPtr ptr2 = hpoint;
int bytes = width * height;
byte[] rgbvalues = new byte[bytes];
System.Runtime.InteropServices.Marshal.Copy(ptr2, rgbvalues, 0, bytes);
res = new Mat(height, width, MatType.CV_8UC1, rgbvalues);
}
?3.彩图转换之Mat-> Hobject
public void Mat2HObjectBpp24(Mat mat, out HObject image)
{
int ImageWidth = mat.Width;
int ImageHeight = mat.Height;
int channel = mat.Channels();
long size = ImageWidth * ImageHeight * channel;
int col_byte_num = ImageWidth * channel;
byte[] rgbValues = new byte[size];
//IntPtr imgptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(rgbValues.Length);
unsafe
{
for (int i = 0; i < mat.Height; i++)
{
IntPtr c = mat.Ptr(i);
//byte* c1 = (byte*)c;
System.Runtime.InteropServices.Marshal.Copy(c, rgbValues, i * col_byte_num, col_byte_num);
}
void* p;
IntPtr ptr;
fixed (byte* pc = rgbValues)
{
p = (void*)pc;
ptr = new IntPtr(p);
}
HOperatorSet.GenImageInterleaved(out image, ptr, "bgr", ImageWidth, ImageHeight, 0, "byte", 0, 0, 0, 0, -1, 0);
}
}
4.彩图转换之Hobject-> Mat
?
public void HObject2Mat24(HObject image, out Mat res)
{
HTuple hred, hgreen, hblue, type, width, height;
HOperatorSet.GetImagePointer3(image, out hred, out hgreen, out hblue, out type, out width, out height);
int bytes = width * height*3;
byte[] rgbvalues = new byte[bytes];
unsafe
{
byte* r = ((byte*)hred.I);
byte* g = ((byte*)hgreen.I);
byte* b = ((byte*)hblue.I);
int lengh = width * height;
for (int i = 0; i < lengh; i++)
{
rgbvalues[i * 3] = (b)[i];
rgbvalues[i * 3 + 1] = (g)[i];
rgbvalues[i * 3 + 2] = (r)[i];
//bptr[i * 4 + 3] = 255;
}
}
res = new Mat(height, width, MatType.CV_8UC3, rgbvalues);
}
|