C++/CLI 和 Halcon:将 HImage 转换为位图时图像失真

问题描述

我目前正在使用 Halcon 开发基于视觉的系统。处理成功后,我希望将裁剪出的 HImage-Format 中的灰度值图像转换为位图。我拥有的功能(在“托管”区域中)实现了这一点,但位图结果被扭曲了。我该如何解决这个问题?

    HImage image_temp;
    HRegion ROI;
    HTuple pointer,type,width,height;
    ROI.GenRectangle1(row1,col1,row2,col2);
    image_temp = sourceImg->ReduceDomain(ROI);
    image_temp = image_temp.CropDomain();
    GetimagePointer1(image_temp,&pointer,&type,&width,&height);

    if (image_temp.CountObj() < 1)
    {
        throw gcnew Exception("ERROR: Failed attempt at HImage2Bitmap");
    }

    Imaging::ColorPalette^ palette;
    Bitmap^ curBitmap = gcnew Bitmap((Int32)width,(Int32)height,Imaging::PixelFormat::Format8bppIndexed);
    Drawing::Rectangle^ rect = gcnew Drawing::Rectangle(0,height);
    Imaging::BitmapData^ imageData = curBitmap->LockBits(*rect,Imaging::ImageLockMode::ReadOnly,curBitmap->PixelFormat);
    int PixelSize = Drawing::Bitmap::GetPixelFormatSize(imageData->PixelFormat) / 8;

    //Define the Buffer used to store image data
    auto buffer = gcnew cli::array<byte>(curBitmap->Width * curBitmap->Height);
    //copy image data into Buffer
    Runtime::InteropServices::Marshal::copy((IntPtr)&pointer,buffer,buffer->Length);

    //byte* ImgBuf = (byte*)&buffer;
    pin_ptr<byte> ImgBuf = (byte*)&buffer;
    IntPtr^ ptr = gcnew IntPtr(ImgBuf);
    Bitmap^ bitmap = gcnew Drawing::Bitmap(curBitmap->Width,curBitmap->Height,curBitmap->Width,Imaging::PixelFormat::Format8bppIndexed,*ptr);

    palette = bitmap->Palette;
    for (int Index = 0; Index <= byte::MaxValue; Index++)
    {
        palette->Entries[Index] = Drawing::Color::FromArgb(byte::MaxValue,Index,Index);
    }
    bitmap->Palette = palette;
    bitmap->Save("D:\\bitmap_test.bmp");
    return bitmap;

在 C# 中测试的代码(通过使用不安全块并修复字节指针)和 Halcon 的 write_image() 函数提供了以下 Bitmap,它应该是这样的:

enter image description here

而在 C++/CLI 中由相同函数创建的位图如下所示:

enter image description here

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)