简体   繁体   中英

Getting RGB values of every pixel in a gif file

I am trying to learn Magick++ and specifically the way to output RGB values for every pixel of an image. Here I have a gif file and the following C++ code to achieve the task. For some reason it produces mostly triplets of 0 with rare instances of some junk values that do not represent the actual colors of an image. What am I doing wrong?

Link to an image

#include <Magick++.h>
#include <iostream>

using std::cout;
using std::endl;
using namespace Magick;

int main()
{
    Image image("forest.gif");
    image.modifyImage();
    image.type(TrueColorType);
    int nx = image.columns();
    int ny = image.rows();

    PixelPacket *pixel_cache = image.getPixels(0,0,nx,ny);
    for (int i = 0; i < nx; ++i)
    {
        for (int j = 0; j < ny; ++j)
        {
            PixelPacket* pix = pixel_cache + j*nx + i;
            cout << pix->red << " " << pix->green << " " << pix->blue << endl;
        }
    }

    return 0;
}

It looks like the problem is in j*nx + i .
You are looping through the columns in the i for loop, then through the rows in the j for loop. I would expect that the values in memory are stored in row-order, so I highly recommend swapping the loops so you iterate through rows in the outer loop and columns in the inner loop.
In any case, however, unless the image is stored in column-order in the memory (I don't know Magick++ but I think it is highly unlikely), j*nx is actually usually pointing to a memory location outside the actual image - thus the garbage data.

Just swap your variables around to

for (int i = 0; i < ny; ++i)
{
    for (int j = 0; j < nx; ++j)
    {
        PixelPacket* pix = pixel_cache + i*ny + j;
        cout << pix->red << " " << pix->green << " " << pix->blue << endl;
    }
}

you can try writing the image to a simple buffer, after that you can access the data easily

char buffer[image.columns()*image.rows()*3]; 
image.write(0, 0, image.columns(), image.rows(), "RGB", Magick::CharPixel, buffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM