c++ - 如何使用 openimageIO 将 RGB 值存储在数组中? (使用 C++、OpenGL)

标签 c++ arrays image opengl rgb

我正在使用 openimageIO 读取和显示 JPG 文件中的图像,现在我需要将 RGB 值存储在数组中,以便以后可以操作和重新显示它们。

我想做这样的事情:

         for (int i=0; i<picturesize;i++) 
        { 
          Rarray[i]=pixelredvalue; 
          Garray[i]=pixelgreenvalue; 
          Barray[i]=pixelbluevalue;
        } 

这是我在网上找到的 openimageIO 源:https://people.cs.clemson.edu/~dhouse/courses/404/papers/openimageio.pdf

“第 3.2 节:高级图像输出”(第 35 页)与我正在做的最接近,但我不明白如何使用 channel 将像素数据写入数组。我也不完全理解“写入”和“存储在数组中”之间的区别。这是我正在谈论的引用资料中的一段代码:

        int channels = 4;
        ImageSpec spec (width, length, channels, TypeDesc::UINT8);
        spec.channelnames.clear ();
        spec.channelnames.push_back ("R");
        spec.channelnames.push_back ("G");
        spec.channelnames.push_back ("B");
        spec.channelnames.push_back ("A");

我设法读取图像并使用引用中的代码显示它,但现在我需要将所有像素值存储在我的数组中。

这是链接中的另一段有用的代码,但同样,我不明白如何检索各个 RGB 值并将它们放入数组中:

#include <OpenImageIO/imageio.h>
OIIO_NAMESPACE_USING
...
const char *filename = "foo.jpg";
const int xres = 640, yres = 480;
const int channels = 3; // RGB
unsigned char pixels[xres*yres*channels];
ImageOutput *out = ImageOutput::create (filename);
if (! out)
return;
ImageSpec spec (xres, yres, channels, TypeDesc::UINT8);
out->open (filename, spec);
out->write_image (TypeDesc::UINT8, pixels);
out->close ();
ImageOutput::destroy (out);

但是这是写文件,还是没有解决我的问题。这是第 35 页。

最佳答案

假设您读取图像的代码如下所示(来自 OpenImageIO 1.7 Programmer Documentation, Chapter 4.1 Image Input Made Simple, page 55 的片段):

ImageInput *in = ImageInput::open (filename);

const ImageSpec &spec = in->spec();
int xres = spec.width;
int yres = spec.height;
int channels = spec.nchannels;
std::vector<unsigned char> pixels (xres*yres*channels);
in->read_image (TypeDesc::UINT8, &pixels[0]);
in->close();
ImageInput::destroy (in);

现在图像的所有字节都包含在std::vector<unsigned char> pixels中了.

如果你想访问x位置像素的RGB值, y ,你可以这样做:

int pixel_addr = (y * yres + x) * channels;

unsigned char red   = pixels[pixel_addr]; 
unsigned char green = pixels[pixel_addr + 1]; 
unsigned char blue  = pixels[pixel_addr + 2]; 

由于所有像素都存储在pixels中,没有理由为 3 个颜色 channel 将它们存储在单独的数组中。
但是如果你想将红色、绿色和蓝色值存储在单独的数组中,那么你可以这样做:

std::vector<unsigned char> Rarray(x_res*yres);
std::vector<unsigned char> Garray(x_res*yres);
std::vector<unsigned char> Barray(x_res*yres);

for (int i=0; i<x_res*yres; i++) 
{ 
    Rarray[i] = pixels[i*channels]; 
    Garray[i] = pixels[i*channels + 1]; 
    Barray[i] = pixels[i*channels + 2];
} 

当然像素必须被紧密地打包到pixels (1 的行对齐)。

关于c++ - 如何使用 openimageIO 将 RGB 值存储在数组中? (使用 C++、OpenGL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48737027/

相关文章:

c++在 bool 模式下搜索文本

c++ - 可变参数模板在以下情况下如何工作?

java - Android:使用数组项填充 ListView

C - sprintf() 影响数组声明

c++ - 在 C++ 中同时从 Kinect 版本 2 获取颜色和深度帧

c++ - Tesseract 3.04.01 可以用 VS2010 编译吗?

c++ - 为什么 auto 不能用于重载函数?

指向对象的指针数组的 C++ 复制构造函数

c# - 如何将图像转换为字符流

python - 查找多幅图像之间的差异图像