c# - 从 C++ 返回到 C# 层时的位图可视化问题

标签 c# c++ opencv bitmap

我正在尝试在 C# 应用程序层中创建位图,使用 OpenCV 在 C++ 层上填充它,然后在 C# 中显示它。

这会导致可视化问题。我写了一个简化的代码来演示这个问题。

结果

enter image description here

我的代码

C# 应用:

int width = 640, height = 480;
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
BitmapData bmpData = bitmap.LockBits(new Rectangle(0, 0, width, height), System.Drawing.Imaging.ImageLockMode.ReadWrite,
     System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

CppWrapper.fillImage((byte*)bmpData.Scan0.ToPointer(), width, height, bmpData.Stride);
bitmap.Save("filledBitmap.bmp", ImageFormat.Bmp);

C# 包装器:

[DllImport("CppWrapperLib.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
    public static unsafe extern void fillImage(byte* im, int width, int height, int stride);

C++ 层:

void __stdcall fillImage(byte* im, int width, int height, int stride)
{
    cv::Mat mat(cv::Size(width, height), CV_8UC1, im, stride);

    mat.setTo(0);
    cv::circle(mat, cv::Point(width / 2, height / 2), 50, 255,-1);
    cv::circle(mat, cv::Point(width / 2, height / 2), 40, 180, -1);
    cv::circle(mat, cv::Point(width / 2, height / 2), 30, 150, -1);
    cv::circle(mat, cv::Point(width / 2, height / 2), 20, 120, -1);
    cv::circle(mat, cv::Point(width / 2, height / 2), 10, 80, -1);
}

谢谢!

最佳答案

更新:我找不到任何与您的数字相对应的默认调色板,因为此时我没有时间自己生成图像,我将发布更新默认调色板编号稍后。不过,您似乎面临调色板问题。

看起来你使用的是 8 位灰度。

在这种情况下,您需要覆盖默认调色板。

//C# part 
ColorPalette palette = bitmap.Palette;
for (int c = 0; c <= 255; c++)
    palette .Entries[c] = Color.FromArgb(255, c, c, c);

bitmap.Palette = palette;

注意 由于您正在保存位图,我不确定默认情况下调色板是否与位图一起保存。

默认情况下,8 位调色板设置为旧的 VGA 色彩空间:

enter image description here

MAC和windows的一些区别:

http://www.columbia.edu/itc/visualarts/r4110/f2000/week06/06_03_Color_palettes.pdf

关于c# - 从 C++ 返回到 C# 层时的位图可视化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44671840/

相关文章:

ubuntu - 在 Ubuntu 上安装 OpenCV-2.4.3 时出错

c# - 从 SQLite 数据库填充 DataGridView (C#)

python - 如何使用 Boost.Python 在 Python 中调用内置函数

c# - "DOCTYPE NEWFILE SYSTEM"是什么意思?

c++ - 需要帮助通过引用类传递 Windows 事件句柄

c++ - glm 平移矩阵不平移 vector

c++ - OpenCV - 在 Vector<Mat> 中保存 Mat

c++ - 版本高于0x240的OpenCV程序编译

c# - 使用 .NET 进行 JSON 和 Base64 编码

c# - 使用不同类型重载函数