C#里Bitmap转Halocn的HObject

一般情况下,图像的width是4的倍数的话,用以下代码便可将彩色bitmap转出halcon里的HObject

public void Bitmap2HObject(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;}
        }

因为Bitmap4字节对齐,非4的整数倍宽度的图像,后面会补0来达到4的倍数。如图像width=810,每行810个字节,实际内存每行后面会补两个字节,宽度变为812个字节。如果按照上面的方法得到的图像如下图所示。

​​​​​C#里Bitmap转Halocn的HObject_第1张图片

要避免这种情况,得重新搞好对应关系,我写了以下方法,可以得到正确的图像

 public void Bitmap2HObjectS(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);
                
                byte[] r = new byte[srcBmpData.Height * srcBmpData.Width];
                byte[] g = new byte[srcBmpData.Height * srcBmpData.Width];
                byte[] b = new byte[srcBmpData.Height * srcBmpData.Width];

                IntPtr ptr1 = Marshal.UnsafeAddrOfPinnedArrayElement(r, 0);
                IntPtr ptr2 = Marshal.UnsafeAddrOfPinnedArrayElement(g, 0);
                IntPtr ptr3 = Marshal.UnsafeAddrOfPinnedArrayElement(b, 0);

                unsafe
                {                           
                    byte* pIn = (byte*)(srcBmpData.Scan0.ToPointer());
                    for (int y = 0; y < srcBmpData.Height; y++)  //列扫描
                    {
                        for (int x = 0; x < srcBmpData.Width; x++)   //行扫描
                        {
                            int index = y * srcBmpData.Width + x;
                            r[index] = pIn[0];
                            g[index] = pIn[1];
                            b[index] = pIn[2];
                            pIn += 3;
                        }
                        pIn += srcBmpData.Stride - srcBmpData.Width * 3;
                    }                    
                }
                HOperatorSet.GenImage3(out image, "byte", srcBmpData.Width, srcBmpData.Height, new HTuple(ptr3), new HTuple(ptr2), new HTuple(ptr1));                
                bmp.UnlockBits(srcBmpData);
            }
            catch (Exception ex)
            {
                image = null;
            }
        }

测试如下图所示C#里Bitmap转Halocn的HObject_第2张图片

你可能感兴趣的:(c#,halcon,bitmap,字节对齐)