原来网上查过HImage转Mat的方式,本来想直接copy,奈何查到的总有不完美的地方,且最近还从之前的代码发现了bug后改掉了。
这段代码测试后可用,直接分享出来。
我的halcon版本是 17.12 后面新版本是否使用可以同步留言。
OpenCV是用的C# nugget包下拉的,这个根据个人.net Framework 版本做调整就好
csharp
public Mat HImageToMat(HImage hImage)
{
try
{
Mat mImage;
HTuple htChannels;
HOperatorSet.CountChannels(hImage, out htChannels);
if (htChannels.Length == 0 || (htChannels[0].I != 1 && htChannels[0].I != 3))
return null;
HTuple width, height;
hImage.GetImageSize(out width, out height);
// 处理单通道图像
if (htChannels[0].I == 1)
{
HTuple ptr, type;
HOperatorSet.GetImagePointer1(hImage, out ptr, out type, out _, out _);
MatType cvType = GetCvType(type);
mImage = new Mat(height, width, cvType);
unsafe
{
byte* srcPtr = (byte*)ptr.IP;
int step = (int)mImage.Step();
for (int row = 0; row < height; row++)
{
Buffer.MemoryCopy(
srcPtr + row * width,
mImage.DataPointer + row * step,
step,
width
);
}
}
return mImage;
}
// 处理三通道图像
else
{
HTuple ptrR, ptrG, ptrB, type;
HOperatorSet.GetImagePointer3(hImage, out ptrR, out ptrG, out ptrB, out type, out _, out _);
MatType cvType = GetCvType(type);
Mat[] channels = new Mat[3]
{
new Mat(height, width, cvType), // B
new Mat(height, width, cvType), // G
new Mat(height, width, cvType) // R
};
unsafe
{
// 复制数据到各通道 (Halcon: R-G-B → OpenCV: B-G-R)
CopyChannel(ptrB, channels[0], width, height); // B
CopyChannel(ptrG, channels[1], width, height); // G
CopyChannel(ptrR, channels[2], width, height); // R
}
mImage = new Mat();
Cv2.Merge(channels, mImage);
foreach (var channel in channels)
channel.Dispose();
return mImage;
}
}
catch (Exception ex)
{
throw new Exception("HImage转Mat失败", ex);
}
}

That 's all . Thank you.