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

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

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

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

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

这是一个很重要的清单 。

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

这很简单,你只需要将头文件stb_image.hstb_image_write.h放在你的文件夹中。

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

 #include  #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  #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 

其他轻量级选择包括:

  • lodepng读写png文件
  • jpeg-compressor读写jpeg文件

查看英特尔Open CV库

日冕很好。 从教程:

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

像素将是一维数组,但您可以轻松地将给定的x和y位置转换为1D数组中的位置。 像pos =(y * width)+ x之类的东西

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

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

试试CImg库。 本教程将帮助您熟悉。 一旦有了CImg对象, data()函数就可以访问2D像素缓冲区数组。

查看Magick ++ API到ImageMagick 。