我正在使用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页)最接近我正在做的事情,但我不明白如何使用通道将像素数据写入数组。我也不完全理解“写”和“存储在数组中”之间的区别。这是我正在讨论的引用中的一段代码:
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页。
发布于 2018-02-12 06:55:46
让我们假设您读取图像的代码如下所示(来自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,y位置的像素的RGB值,你可以这样做:
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个颜色通道的单独数组中。
但是如果你想把红色、绿色和蓝色的值存储在不同的数组中,那么你可以这样做:
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)。
https://stackoverflow.com/questions/48737027
复制相似问题