微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决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 举报,一经查实,本站将立刻删除。