使用glReadPixels结果的问题

时间:2014-03-22 16:06:49

标签: c++ opengl glreadpixels

对于家庭作业,我需要实施一个填充算法。我的代码已经结构化,但我似乎无法弄清楚为什么我的glReadPixels部分不起作用。我希望有人可以看看我在做什么,如果我的使用不正确,请告诉我。

// I fetch pixels like so:
    glReadPixels(100, 250, 150, 150, GL_RGB, GL_UNSIGNED_BYTE, clip_pixels);
// I index the result using:
    in_rect_pos = (in_rect_y * in_rect_w) + in_rect_x;
    // in_rect_* is a point w/ its origin at (100, 250)
    GLubyte *pixel_at_pos = clip_pixels + (in_rect_pos * GL_PACK_ALIGNMENT);

但我没有得到正确的价值,我甚至不知道如何调试这个。

2 个答案:

答案 0 :(得分:0)

const int X = 0;
const int Y = 0;
const int Width = 100;
const int Height = 100;

unsigned char Buffer[Width * Height * 3];
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(X, Y, Width, Height, GL_RGB, GL_UNSIGNED_BYTE, &Buffer[0]);

for (int i = 0; i < height; ++i)
{
    for (int j = 0; j < width; ++j)
    {
        unsigned char R = Buffer[(i * j + width) + 0];
        unsigned char G = Buffer[(i * j + width) + 1];
        unsigned char B = Buffer[(i * j + width) + 2];
    }
}

如果它在某个边界上对齐(并且您不做:glPixelStorei(GL_PACK_ALIGNMENT, 1)),则需要考虑填充...

示例:

unsigned char* ptr = &Buffer[0];

for (int i = 0; i < Height; ++i)
{
    for (int j = 0; j < Width; ++j)
    {
        int R = *(ptr++);
        int G = *(ptr++);
        int B = *(ptr++);
    }

    ptr += (4 - ((width * 3) % 4)) % 4; //DWORD boundary alignment.
}

答案 1 :(得分:0)

我可以在你的代码中发现一个非常重要的错误:

GLubyte *pixel_at_pos = clip_pixels + (in_rect_pos * GL_PACK_ALIGNMENT);

在这里使用GL_PACK_ALIGNMENT有两种不同的错误:

  1. 从根本上说,GL_PACK_ALIGNMENT是OpenGL中的枚举值。它碰巧被定义为0x0D05(十进制为3333),它不是GL_PACK_ALIGNMENT GL状态的,您可以通过glPixelStore设置并通过查询返回glGet。在这两种情况下,GL_PACK_ALIGNMENT仅用于引用要访问的GL状态变量。

  2. 您没有正确使用对齐方式。即使您使用了glGetIntegerv(GL_PACK_ALIGNMENT, &alignment)查询的值,您的公式仍然是错误的。 GL_PIXEL_PACK对齐引用像素数据的每个的地址。默认情况下,它设置为4,因此如果您的行不能从可被4整除的地址开始,则必须添加1到3个填充字节以使其可被4整除。