Halcon对象Hobject转换为.net对象Bitmap

本文介绍如何在Halcon与C#交互中,将Halcon的Hobject对象转换为.NET的Bitmap图像。经过两天研究,作者在周末成功解决此问题,分享转换代码。

好多年不写了,这几天做项目遇到个烦死的问题,大周末的终于解决了。

用Halcon转换成C#时 Hobject对象如何转换成我们认识的Bitmap呢,搞了两天终于好了。

上代码。麻麻再也不用担心我的转换问题了。

private void GenertateGrayBitmap(HObject image, out Bitmap res)
 {
            HTuple hpoint, type, width, height;

            const int Alpha = 255;
            int[] ptr = new int[2];
            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;
            ptr[0] = bitmapData.Scan0.ToInt32();
            ptr[1] = hpoint.I;
            if (width % 4 == 0)
                CopyMemory(ptr[0], ptr[1], width * height * PixelSize);
            else
            {
                for (int i = 0; i < height - 1; i++)
                {
                    ptr[1] += width;
                    CopyMemory(ptr[0], ptr[1], width * PixelSize);
                    ptr[0] += bitmapData.Stride;
                }
            }
            res.UnlockBits(bitmapData);

}

        private void GenertateRGBBitmap(HObject image, out Bitmap res)
        {
            HTuple hred, hgreen, hblue, type, width, height;

            HOperatorSet.GetImagePointer3(image, out hred, out hgreen, out hblue, out type, out width, out height);

            res = new Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppRgb);

            Rectangle rect = new Rectangle(0, 0, width, height);
            BitmapData bitmapData = res.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppRgb);
            unsafe
            {
                byte* bptr = (byte*)bitmapData.Scan0;
                byte* r = ((byte*)hred.I);
                byte* g = ((byte*)hgreen.I);
                byte* b = ((byte*)hblue.I);
                for (int i = 0; i < width * height; 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);

        }
    public static class BitmapExtension
    {
       
        public static HImage ToHImage(this Bitmap bitmap)
        {
            HImage h_img = new HImage();
            try
            {
                Bitmap image = (Bitmap)bitmap.Clone();
                BitmapData bmData = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
                unsafe
                {
                    // Create HALCON image from the pointer.
                    h_img.GenImageInterleaved(bmData.Scan0, "bgrx", image.Width, image.Height, -1, "byte", image.Width, image.Height, 0, 0, -1, 0);
                    //tmp = h_img;
                }


                // Don't forget to unlock the bits again. <img class="wp-smiley" alt=";-)" src="http://www.mavis.com.tr/blog/wp-includes/images/smilies/icon_wink.gif">
                image.UnlockBits(bmData);
                image.Dispose();
            }
            catch
            {
                //h_img = tmp;
            }
            return h_img;
        }


        public static void SaveImage(this Bitmap _currentImage, string savepath, long photoIndex, string res = "")
        {
            if (_currentImage != null)
            {
                try
                {
                    Bitmap saveimg = (Bitmap)_currentImage.Clone();


                    new Thread(() =>
                    {
                        long cameranumber = photoIndex;
                        string path = savepath;
                        try
                        {
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }


                            DriveInfo driveinfo = new DriveInfo(savepath);
                            long data = driveinfo.AvailableFreeSpace / (1024 * 1024 * 1024);


                            if (data > 1)//1G空间以下时删除图片
                            {
                                //saveimg.ToSave(path + "\\" + cameranumber + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + ".tiff");
                                saveimg.Save(path + "\\" + cameranumber + "_" + DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss") + res + ".bmp", ImageFormat.Bmp);
                            }
                            else
                            {
                                Directory.Delete(path, true);
                                new Thread(new ThreadStart(delegate()
                                {
                                    MessageBox.Show("磁盘空间有限,删除已保存的图片");


                                })) { IsBackground = false }.Start();
                            }
                        }
                        catch (Exception ex)
                        {


                        }


                    }) { IsBackground = true }.Start();
                }
                catch (Exception ex)
                {


                }
            }
        }
    }


Halcon中,将HObject图像转换Bitmap有不同的实现方法,以下为几种不同情况的转换示例: ### 灰度图HObjectBitmap 以下是一个将灰度图HObject转换BitmapC#代码示例: ```csharp public static Bitmap HObject2Bitmap(HObject ho) { try { HTuple type, width, height, pointer; //HOperatorSet.AccessChannel(ho, out ho, 1); HOperatorSet.GetImagePointer1(ho, out pointer, out type, out width, out height); //himg.GetImagePointer1(out type, out width, out height); Bitmap bmp = new Bitmap(width.I, height.I, PixelFormat.Format8bppIndexed); ColorPalette pal = bmp.Palette; for (int i = 0; i <= 255; i++) { pal.Entries[i] = Color.FromArgb(255, i, i, i); } bmp.Palette = pal; BitmapData bitmapData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); int PixelSize = Bitmap.GetPixelFormatSize(bitmapData.PixelFormat) / 8; int stride = bitmapData.Stride; int ptr = bitmapData.Scan0.ToInt32(); for (int i = 0; i < height; i++) { CopyMemory(ptr, pointer, width * PixelSize); pointer += width; ptr += bitmapData.Stride; } bmp.UnlockBits(bitmapData); return bmp; } catch (Exception exc) { return null; } } ``` 此代码通过`HOperatorSet.GetImagePointer1`获取HObject图像的指针、类型、宽度和高度信息,创建一个8位索引格式的Bitmap对象,设置调色板,锁定Bitmap数据,将HObject的数据逐行复制到Bitmap中,最后解锁Bitmap数据并返回结果 [^3]。 ### RGB模式的HobjectBitmap24位 对于将RGB模式的Hobject直接转换Bitmap24位,需考虑Halcon图像格式与Bitmap格式的不同以及Bitmap存储方式的特性。Halcon的RGB三通道图各个通道是独立排布,而Bitmap使用的是交错图像格式,且Bitmap每行字节数需能被4整除,不满足时需进行padding。具体实现可参考相关的转换逻辑,以兼顾耗时要求 [^2]。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值