How to get texture data using textureID's in openGL
Asked Answered
Z

3

29

I'm writing some code where all I have access to is a textureID to get access to the required texture. Is there any way that I can get access to the RGB values of this texture so I can perform some computations on it?

EDIT: I am looking for the inverse of glTexSubImage2D. I want to get the texture data rather than replace it.

Zulmazulu answered 25/2, 2011 at 13:13 Comment(0)
G
45

You are probably looking for glGetTexImage

Before using glGetTexImage, don't forget to use glBindTexture with your texture ID.

Gerber answered 25/2, 2011 at 13:29 Comment(2)
How do you get a piece of a texture (i.e. rectangle)?Suomi
I think you will have to render it to an FBO and then read from that with glReadPixels.Hube
I
1

In OpneGL a texture can be read by glGetTexImage/glGetnTexImage respectively the DSA version of the function glGetTextureImage.

Another possibility is to attach the texture to a framebuffer and to read the pixel by glReadPixels. OpenGL ES does not offer a glGetTexImage, so this is the way to OpenGL ES.
See opengl es 2.0 android c++ glGetTexImage alternative


If you transfer the texture image to a Pixel Buffer Object, then you can even access the data via Buffer object mapping. See also OpenGL Pixel Buffer Object (PBO).
You've to bind a buffer with the proper size to the target GL_PIXEL_PACK_BUFFER:

// create buffer
GLuint pbo;
glGenBuffers(1, &pbo);
glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
glBufferData(GL_PIXEL_PACK_BUFFER, size_in_bytes, 0, GL_STATIC_READ);

// get texture image
glBindTexture(GL_TEXTURE_2D, texture_obj);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, (void*)(0));

// map pixel buffer
void * data_ptr = glMapBuffer(GL_PIXEL_PACK_BUFFER, GL_READ_ONLY);

// access the data
// [...]

glUnmapBuffer(GL_PIXEL_PACK_BUFFER);
Inconsiderate answered 18/7, 2020 at 7:9 Comment(0)
B
0

I'm writing this here just in case anyone needs this.

In 4.5+ OpenGL, one can access a textures' data by giving a texture ID by using the glGetTextureImage() function.

For example in order to get a GL_RGB texture data, we have 3 floats R,G,B each one of each is 4 bytes so:

float* data = new float[texture_height * texture_width * 3];
glGetTextureImage(textureID, 0, GL_RGB, GL_FLOAT, texture_height * texture_width * 3 * 4, data);
Basinet answered 27/4, 2021 at 18:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.