2021-03-07

.net 中Bitmap和Halcon中HObject的相互转换

实际使用时,假如原图8位灰度图,那么BitmapToHObjectBpp8 和BitmapToHObjectBpp24的结果是一样的。而为24位彩色图时,只能用BitmapToHObjectBpp24。
可先得到Bitmap 图的PixelFormat ,而后再进行转换。



以下HObject to Bitmap部分参考:http://blog.csdn.net/miehuo/article/details/48751353


 
 
  1. private void HObject2Bpp8(HObject image, out Bitmap res)
  2. {
  3. HTuple hpoint, type, width, height;
  4. const int Alpha = 255;
  5. int[] ptr = new int[ 2];
  6. HOperatorSet.GetImagePointer1(image, out hpoint, out type, out width, out height);
  7. res = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
  8. ColorPalette pal = res.Palette;
  9. for ( int i = 0; i <= 255; i++)
  10. {
  11. pal.Entries[i] = Color.FromArgb(Alpha, i, i, i);
  12. }
  13. res.Palette = pal;
  14. Rectangle rect = new Rectangle( 0, 0, width, height);
  15. BitmapData bitmapData = res.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
  16. int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8;
  17. ptr[ 0] = bitmapData.Scan0.ToInt32();
  18. ptr[ 1] = hpoint.I;
  19. if (width % 4 == 0)
  20. CopyMemory(ptr[ 0], ptr[ 1], width * height * PixelSize);
  21. else
  22. {
  23. for ( int i = 0; i < height - 1; i++)
  24. {
  25. ptr[ 1] += width;
  26. CopyMemory(ptr[ 0], ptr[ 1], width * PixelSize);
  27. ptr[ 0] += bitmapData.Stride;
  28. }
  29. }
  30. res.UnlockBits(bitmapData);
  31. }
  32. private void HObject2Bpp24(HObject image, out Bitmap res)
  33. {
  34. HTuple hred, hgreen, hblue, type, width, height;
  35. HOperatorSet.GetImagePointer3(image, out hred, out hgreen, out hblue, out type, out width, out height);
  36. res = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);
  37. Rectangle rect = new Rectangle( 0, 0, width, height);
  38. BitmapData bitmapData = res.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
  39. unsafe
  40. {
  41. byte* bptr = ( byte*)bitmapData.Scan0;
  42. byte* r = (( byte*)hred.I);
  43. byte* g = (( byte*)hgreen.I);
  44. byte* b = (( byte*)hblue.I);
  45. for ( int i = 0; i < width * height; i++)
  46. {
  47. bptr[i * 4] = (b)[i];
  48. bptr[i * 4 + 1] = (g)[i];
  49. bptr[i * 4 + 2] = (r)[i];
  50. bptr[i * 4 + 3] = 255;
  51. }
  52. }
  53. res.UnlockBits(bitmapData);
  54. }




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值