简体   繁体   English

获取gif文件中每个像素的RGB值

[英]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. 我正在尝试学习Magick ++,尤其是学习为图像的每个像素输出RGB值的方法。 Here I have a gif file and the following C++ code to achieve the task. 在这里,我有一个gif文件和以下C ++代码来完成任务。 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. 由于某种原因,它产生的三元组大部分为0,并且很少出现一些垃圾值,这些垃圾值不能代表图像的实际颜色。 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 . 看来问题出在j*nx + i
You are looping through the columns in the i for loop, then through the rows in the j for loop. 您正在遍历i for循环中的列,然后遍历j for循环中的行。 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. 但是,无论如何,除非将图像以列顺序存储在内存中(我不知道Magick ++,但我认为这种可能性很小),否则j * nx实际上通常指向实际图像之外的存储位置-因此,垃圾数据。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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