27

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.

Sonoman
  • 3,159
  • 9
  • 42
  • 59

3 Answers3

41

You are probably looking for glGetTexImage

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

genpfault
  • 47,669
  • 9
  • 68
  • 119
Greg S
  • 11,275
  • 2
  • 35
  • 48
0

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);
Rabbid76
  • 142,694
  • 23
  • 71
  • 112
-1

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);
gtsopus
  • 1
  • 3