来自 2D 数组的 C++ 16 位灰度梯度图像

2023-12-12

我目前正在尝试构建 16 位灰度“渐变”图像,但我的输出看起来很奇怪,所以我显然没有正确理解这一点。我希望有人能就我的问题提供一些知识。我认为我写的“位图”是错误的?但我不确定。

#include "CImg.h"
using namespace std;

unsigned short buffer[1250][1250];

void fill_buffer()
{
    unsigned short temp_data = 0;
    for (int i =0;i < 1250; i++)
    {
        for (int j =0 ;j < 1250;j++)
        {
            buffer[i][j] = temp_data;
        }
        temp_data += 20;
    }
}

int main()
{
    fill_buffer();
    auto hold_arr = (uint8_t *)&buffer[0][0];
    cimg_library::CImg<uint8_t> img(hold_arr, 1250, 1250);
    img.save_bmp("test.bmp");
    return 0;
}

Current Output: Current Output


您无法在 BMP 中存储 16 位灰度样本...请参阅维基百科.

BMP 中的每像素 16 位选项允许您存储 4 位红色、4 位绿色、4 位蓝色和 4 位 Alpha,但不能存储 16 位灰度。

24 位格式允许您存储 1 个字节的红色、1 个字节的绿色和 1 个字节的蓝色,但不能存储 16 位的灰度。

32 位 BMP 允许您存储 24 位 BMP 加 alpha。

您将需要使用PNG, or a NetPBMPGM 格式,或TIFF格式。PGM格式很棒,因为CImg可以在没有任何库的情况下编写,并且您可以随时使用图像魔术师将其转换为其他内容,例如:

convert image.pgm image.png

or

convert image.pgm image.jpg

这有效:

#define cimg_use_png
#define cimg_display 0
#include "CImg.h"

using namespace cimg_library;
using namespace std;

unsigned short buffer[1250][1250];

void fill_buffer()
{
    unsigned short temp_data = 0;
    for (int i =0;i < 1250; i++)
    {
        for (int j =0 ;j < 1250;j++)
        {
            buffer[i][j] = temp_data;
        }
        temp_data += 65535/1250;
    }
}

int main()
{
    fill_buffer();
    auto hold_arr = (unsigned short*)&buffer[0][0];
    cimg_library::CImg<unsigned short> img(hold_arr, 1250, 1250);
    img.save_png("test.png");
    return 0;
}

enter image description here

请注意,询问时CImg要编写 PNG 文件,您需要使用这样的命令(使用libpng and zlib) 编译:

g++-7 -std=c++11 -O3 -march=native -Dcimg_display=0 -Dcimg_use_png  -L /usr/local/lib -lm -lpthread -lpng -lz -o "main" "main.cpp"

仅作为解释:

  • -std=c++11只是设定了C++标准
  • -O3 -march=native只是为了加快速度,并不是严格要求的
  • -Dcimg_display=0意味着所有 X11 标头都不会被解析,因此编译速度更快 - 但这意味着您无法显示程序中的图像,因此这意味着您“无头”
  • -Dcimg_use_png意味着您可以使用以下方式读取/写入 PNG 图像libpng而不是需要安装 ImageMagick
  • -lz -lpng意味着生成的代码与 PNG 和 ZLIB 库链接。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

来自 2D 数组的 C++ 16 位灰度梯度图像 的相关文章

随机推荐