【问题标题】:Extract RGB from JPEG image, using libjpeg C++ Library使用 libjpeg C++ 库从 JPEG 图像中提取 RGB
【发布时间】:2016-11-05 01:05:23
【问题描述】:

我正在使用 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 值?

【问题讨论】:

  • JPEG 文件是YCbCr encoded,可能是chroma subsampling。您必须编写必要的颜色转换代码,或者使用可以为您完成的库。
  • @Cornstalks,libjpeg 内置了现成的转换,你只需要指定适当的'out_color_space'
  • @Dmitry:感谢指正!

标签: c++ c++11 libjpeg


【解决方案1】:

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。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多