I’m trying to store pixel data by using glReadPixels, but so far I managed to only store it one pixel at a time. I’m not sure if this is the way to go. I currently have this:
unsigned char pixels[3];
glReadPixels(50,50, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixels);
What would be a good way to store it in an array, so that I can get the values like this:
pixels[20][50][0]; // x=20 y=50 -> R value
pixels[20][50][1]; // x=20 y=50 -> G value
pixels[20][50][2]; // x=20 y=50 -> B value
I guess I could simple put it in a loop:
for ( all pixels on Y axis )
{
for ( all pixels in X axis )
{
unsigned char pixels[width][height][3];
glReadPixels(x,y, 1, 1, GL_RGB, GL_UNSIGNED_BYTE, pixels[x][y]);
}
}
But I have the feeling that there must be a much better way to do this. But I do however need my array to be like I described above the code. So would the for loop idea be good, or is there a better way?
glReadPixelssimply returns bytes in the orderR, G, B, R, G, B, ...(based on your setting ofGL_RGB) from the bottom left of the screen going up to the top right. From the OpenGL documentation:The overhead of calling
glReadPixelsthousands of times will most likely take a noticeable amount of time (depends on the window size, I wouldn’t be surprised if the loop took 1-2 seconds).It is recommended that you only call
glReadPixelsonce and store it in a byte array of size(width - x) * (height - y) * 3. From there you can either reference a pixel’s component location withdata[(py * width + px) * 3 + component]wherepxandpyare the pixel locations you want to look up, andcomponentbeing the R, G, or B components of the pixel.If you absolutely must have it in a 3-dimensional array, you can write some code to rearrange the 1d array after the
glReadPixelscall.