用C/C++读取图像文件

sky*_*ulz 21 c c++ jpeg

我需要用C/C++读取一个图像文件.如果有人可以为我发布代码,那将是非常好的.

我处理灰度图像,图像是JPEG.我想把图像读成2D数组,这将使我的工作变得简单.

GMa*_*ckG 14

您可以通过查看JPEG格式编写自己的内容.

也就是说,尝试预先存在的库,如CImgBoost的GIL.或严格的JPEG,libjpeg.CodeProject上还有CxImage类.

这是一个很重要的清单.

  • Boost.GIL 不起作用,也没有得到维护。 (2认同)
  • 由于允许使用 C,因此我将 libjpeg 作为最轻量级的解决方案。CImg 和 GIL 在语法上绝对更容易——但也需要 libjpeg。您可以轻松地将 CImg 对象中的数据复制到某个 STL 容器或数组中。 (2认同)

Jai*_*tes 11

如果你决定采用最小的方法,没有libpng/libjpeg依赖,我建议使用stb_imagestb_image_write,在这里找到.

这是因为它得到一样简单,你只需要放置头文件stb_image.hstb_image_write.h你的文件夹中.

这是您阅读图像所需的代码:

#include <stdint.h>

#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"

int main() {
    int width, height, bpp;

    uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);

    stbi_image_free(rgb_image);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是编写图像的代码:

#include <stdint.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

#define CHANNEL_NUM 3

int main() {
    int width = 800; 
    int height = 800;

    uint8_t* rgb_image;
    rgb_image = malloc(width*height*CHANNEL_NUM);

    // Write your code to populate rgb_image here

    stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

您可以编译没有标志或依赖项:

g++ main.cpp
Run Code Online (Sandbox Code Playgroud)

其他轻量级选择包括:

  • 我必须包含math.h库并在编译时链接它(http://stackoverflow.com/questions/8671366/undefined-reference-to-pow-and-floor)或者我会得到一个未定义的参考文献图像库. (2认同)
  • 我知道这只是一个示例,但您能澄清一下代码中神奇数字 3 的含义吗? (2认同)
  • @mattshu 这是通道的数量(红色,绿色,蓝色),也许我应该在我的代码中澄清这一点,我会进行编辑。 (2认同)

mwc*_*wcz 3

尝试一下CImg库。本教程将帮助您熟悉。一旦您拥有 CImg 对象,data()函数将允许您访问 2D 像素缓冲区数组。