如何将 C/C++ 中的灰度 JPEG 图像文件读取到 2D 数组中?
如果您决定采用最小方法,没有 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
其他轻量级替代品包括:
查看 Intel Open CV 库 ...
检查此线程:读取和写入图像文件。
另外,请查看 Stackoverflow 上的另一个问题。
电晕很好。来自教程:
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
查看 Magick++ API 到 ImageMagick。