使用libjpeg C ++ Library从JPEG图像中提取RGB

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用libjpeg C ++ Library从JPEG图像中提取RGB相关的知识,希望对你有一定的参考价值。

我正在使用libjpeg库来读取和复制jpeg到我用C ++编写的编辑程序中

我有一个显示缓冲区,它是一个名为ColorData的数据类型的向量

所有ColorData都包含3个浮点数(RGB)

这是我打开jpeg文件的代码

PixelBuffer * IOManager::load_jpg_to_pixel_buffer(const char *file_name){
  struct jpeg_decompress_struct cinfo;

  FILE * infile;

  JSAMPARRAY buffer;

  if ((infile = fopen(file_name, "rb")) == NULL) {
    std::cout << "Could not open the jpg file: " << file_name << std::endl;
    return nullptr;
  }

  struct jpeg_error_mgr jerr; 

  cinfo.err = jpeg_std_error(&jerr);

  jpeg_create_decompress(&cinfo);

  jpeg_stdio_src(&cinfo, infile);
  jpeg_read_header(&cinfo, TRUE);
  jpeg_start_decompress(&cinfo);

  int width = static_cast<int>(cinfo.output_width);

  int height = static_cast<int>(cinfo.output_height);

  std::cout << typeid(cinfo.colormap).name() << std::endl;

  std::cout << "Width: " << width << "Height: " << height << std::endl;

  PixelBuffer * image_buffer = new PixelBuffer(width, height, ColorData());

  std::cout << cinfo.output_components << std::endl;

   buffer = (*cinfo.mem->alloc_sarray)
    ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width * cinfo.output_components, 1);

  /* Step 6: while (scan lines remain to be read) */
  /*           jpeg_read_scanlines(...); */

  /* Here we use the library's state variable cinfo.output_scanline as the
   * loop counter, so that we don't have to keep track ourselves.
   */
  while (cinfo.output_scanline < cinfo.output_height) {
    /* jpeg_read_scanlines expects an array of pointers to scanlines.
     * Here the array is only one element long, but you could ask for
     * more than one scanline at a time if that's more convenient.
     */
    (void) jpeg_read_scanlines(&cinfo, buffer, 1);
    /* Assume put_scanline_someplace wants a pointer and sample count. */

  }

  return nullptr;


}

如何使用libjpeg从jpeg中获取RGB值?

答案

RGB值在buffer中。它实际上是一个数组数组,所以你必须索引buffer[0]

像这样的东西:

while (cinfo.output_scanline < cinfo.output_height)
{
    (void) jpeg_read_scanlines(&cinfo, buffer, 1);

    // get the pointer to the row:
    unsigned char* pixel_row = (unsigned char*)(buffer[0]);
    // iterate over the pixels:
    for(int i = 0; i < cinfo.output_width; i++)
    {
        // convert the RGB values to a float in the range 0 - 1
        float red = (float)(*pixel_row++) / 255.0f;
        float green = (float)(*pixel_row++) / 255.0f;
        float blue = (float)(*pixel_row++) / 255.0f;
    }
}

这是假设cinfo.output_components是3。

以上是关于使用libjpeg C ++ Library从JPEG图像中提取RGB的主要内容,如果未能解决你的问题,请参考以下文章

Mac和Linux报错: dyld: Library not loaded: /usr/local/opt/jpeg/lib/libjpeg.8.dylib的解决办法

Libjpeg 错误 - 状态 205 中的不正确调用

解决使用 libjpeg 保存图片时因磁盘写入失败导致程序退出的问题

从libjpeg中的yuv中提取灰度

使用 libexif 和 libjpeg 在现有 JPEG 上设置 exif 标签

Linux应用开发-libjpeg库交叉编译与使用