2

我目前正在使用 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, 0, width, 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, 0, 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, Index);
    }
    bitmap->Palette = palette;
    bitmap->Save("D:\\bitmap_test.bmp");
    return bitmap;

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

在此处输入图像描述

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

在此处输入图像描述

4

0 回答 0