将C/C++中的图像文件读取到数组中[关闭]

问题描述 投票:0回答:7

如何将 C/C++ 中的灰度 JPEG 图像文件读取到 2D 数组中?

c++ c jpeg
7个回答
26
投票

如果您决定采用最小方法,没有 libpng/libjpeg 依赖项,我建议使用

stb_image
stb_image_write
,可在 here 找到。

就这么简单,您只需将头文件

stb_image.h
stb_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;
}

这是写入图像的代码:

#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;
}

您可以在没有标志或依赖项的情况下进行编译:

g++ main.cpp

其他轻量级替代品包括:


15
投票

您可以通过查看 JPEG 格式来编写自己的格式。

也就是说,尝试使用预先存在的库,例如 CImgBoost 的 GIL。或者对于严格的 JPEG,libjpeg。 CodeProject 上还有 CxImage 类。

这是一个大清单


4
投票

查看 Intel Open CV 库 ...


4
投票

检查此线程:读取和写入图像文件

另外,请查看 Stackoverflow 上的另一个问题


3
投票

电晕很好。来自教程:

corona::Image* image = corona::OpenImage("img.jpg", corona::PF_R8G8B8A8);
if (!image) {
  // error!
}

int width  = image->getWidth();
int height = image->getHeight();
void* pixels = image->getPixels();

// we're guaranteed that the first eight bits of every pixel is red,
// the next eight bits is green, and so on...
typedef unsigned char byte;
byte* p = (byte*)pixels;
for (int i = 0; i < width * height; ++i) {
  byte red   = *p++;
  byte green = *p++;
  byte blue  = *p++;
  byte alpha = *p++;
}

pixels 将是一维数组,但您可以轻松地将给定的 x 和 y 位置转换为一维数组中的位置。类似 pos = (y * width) + x


2
投票

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


1
投票

查看 Magick++ APIImageMagick

© www.soinside.com 2019 - 2024. All rights reserved.