Willing to understand glTexImage2D, I wrote following test code in Python:
import numpy as np
import OpenGL.GL as gl
import glfw
# initiating context
glfw.init()
w = glfw.create_window(100, 100, 'dd', None, None)
glfw.make_context_current(w)
# prepare sample image
width, height = 3, 3
image = np.array([i for i in range(width * height * 3)], dtype='ubyte')
# prepare texture
t = gl.glGenTextures(1)
gl.glBindTexture(gl.GL_TEXTURE_2D, t)
iformat = gl.GL_RGB
# upload texture
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, iformat, width, height, 0, iformat, gl.GL_UNSIGNED_BYTE, image)
# read texture
p = gl.glGetTexImage(gl.GL_TEXTURE_2D, 0, iformat, gl.GL_UNSIGNED_BYTE)
# display pixel values
pixels = iter(p)
for x in range(width):
for y in range(height):
print([next(pixels), next(pixels), next(pixels)])
and unexpectedly, printed result was following:
[0, 1, 2]
[3, 4, 5]
[6, 7, 8]
[12, 13, 14]
[15, 16, 17]
[18, 19, 20]
[24, 25, 26]
[0, 0, 0]
[0, 0, 93]
Obviously some values are missing. Why is this happening? Am i missing something?
If an RGB image with 3 color channels is loaded into a texture object, GL_UNPACK_ALIGNMENT
must be set to 1:
gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, iformat, width, height, 0, iformat, gl.GL_UNSIGNED_BYTE, image)
GL_UNPACK_ALIGNMENT
specifies the alignment requirements for the start of each pixel row in memory. By default GL_UNPACK_ALIGNMENT
is set to 4. This means the start of each line of the image is assumed to be aligned to an address which is a multiple of 4. Since the image data is tightly packed and each pixel is 3 bytes in size, the alignment has to be changed.
If the width of the image is divisible by 4 (more exactly if 3*width
is divisible by 4) then the error is not noticeable.
Since you are reading back the texture from the GPU, you also need to change GL_PACK_ALIGNMENT
:
gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
p = gl.glGetTexImage(gl.GL_TEXTURE_2D, 0, iformat, gl.GL_UNSIGNED_BYTE)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.