Halcon 与 bitmap 互转:
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; } } public void HObject2Bpp24(HObject ho_image, out Bitmap res24) { HTuple width0, height0, type, width, height; //获取图像尺寸 HOperatorSet.GetImageSize(ho_image, out width0, out height0); //创建交错格式图像 HOperatorSet.InterleaveChannels(ho_image, out HObject InterImage, "argb", "match", 255); //"rgb", 4 * width0, 0 "argb", "match", 255 //获取交错格式图像指针 HOperatorSet.GetImagePointer1(InterImage, out HTuple Pointer, out type, out width, out height); IntPtr ptr = Pointer; //构建新Bitmap图像 Bitmap res32 = new Bitmap(width / 4, height, width, PixelFormat.Format32bppArgb, ptr); // Format32bppArgb Format24bppRgb //32位Bitmap转24位 res24 = new Bitmap(res32.Width, res32.Height, PixelFormat.Format24bppRgb); Graphics graphics = Graphics.FromImage(res24); graphics.DrawImage(res32, new Rectangle(0, 0, res32.Width, res32.Height)); res32.Dispose(); } public void HObject2Bpp8_(HObject image, out Bitmap res) { HTuple hpoint, type, width, height; const int Alpha = 255; HOperatorSet.GetImagePointer1(image, out hpoint, out type, out width, out height); res = new Bitmap(width, height, PixelFormat.Format8bppIndexed); ColorPalette pal = res.Palette; for (int i = 0; i <= 255; i++) { pal.Entries[i] = Color.FromArgb(Alpha, i, i, i); } res.Palette = pal; Rectangle rect = new Rectangle(0, 0, width, height); BitmapData bitmapData = res.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8; IntPtr ptr1 = bitmapData.Scan0; IntPtr ptr2 = hpoint; int bytes = width * height; byte[] rgbvalues = new byte[bytes]; System.Runtime.InteropServices.Marshal.Copy(ptr2, rgbvalues, 0, bytes); System.Runtime.InteropServices.Marshal.Copy(rgbvalues, 0, ptr1, bytes); res.UnlockBits(bitmapData); }
标签:image,Halcon,res32,width,bmp,Bitmap,互转,bitmap,out From: https://www.cnblogs.com/forblueskies/p/17865518.html