【发布时间】:2011-01-05 19:07:10
【问题描述】:
我需要读取 C/C++ 中的图像文件。如果有人可以为我发布代码,那就太好了。
我处理灰度图像,图像是 JPEG。我想将图像读入二维数组,这将使我的工作变得容易。
【问题讨论】:
-
libjpeg (ijg.org) 的文档或您没有的任何本机 API 是否不足?
-
别忘了为您提出的三个问题选择一个正确答案。
我需要读取 C/C++ 中的图像文件。如果有人可以为我发布代码,那就太好了。
我处理灰度图像,图像是 JPEG。我想将图像读入二维数组,这将使我的工作变得容易。
【问题讨论】:
如果您决定采用最小的方法,不依赖 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
其他轻量级替代方案包括:
【讨论】:
【讨论】:
查看 英特尔 Open CV 库 ...
【讨论】:
corona 很好。来自教程:
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
【讨论】:
【讨论】:
您可以通过查看 JPEG format 来编写自己的代码。
也就是说,尝试使用预先存在的库,例如 CImg 或 Boost's GIL。或者对于严格的 JPEG,libjpeg。 CodeProject 上还有CxImage 类。
这是big list。
【讨论】: