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