C# 中Bitmap和Halcon中HObject資料型別的相互轉換
C# 中Bitmap和Halcon中HObject資料型別的相互轉換
public void Bitmap2HObjectBpp24(Bitmap bmp, out HObject image)
{
try
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
bmp.UnlockBits(srcBmpData);
}
catch (Exception ex)
{
image = null;
}
}
public void Bitmap2HObjectBpp8(Bitmap bmp, out HObject image)
{
try
{
Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
HOperatorSet.GenImage1(out image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0);
bmp.UnlockBits(srcBmpData);
}
catch (Exception ex)
{
image = null;
}
}
實際使用時,假如原圖8位灰度圖,那麼BitmapToHObjectBpp8 和BitmapToHObjectBpp24的結果是一樣的。而為24位彩色圖時,只能用BitmapToHObjectBpp24。
可先得到Bitmap 圖的PixelFormat ,而後再進行轉換。
以下HObject to Bitmap部分參考:http://blog.csdn.net/miehuo/article/details/48751353
int lengh = width * height;
for (int i = 0; i <lengh ; i++)
{
bptr[i * 4] = (b)[i];
bptr[i * 4 + 1] = (g)[i];
bptr[i * 4 + 2] = (r)[i];
bptr[i * 4 + 3] = 255;
}
}
res.UnlockBits(bitmapData);
}