简体   繁体   English

glTexImage2D 数据未按预期填充

[英]glTexImage2D data not filled as expected

Willing to understand glTexImage2D, I wrote following test code in Python:为了了解glTexImage2D,我在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:如果将具有 3 个颜色通道的 RGB 图像加载到纹理 object 中, GL_UNPACK_ALIGNMENT必须设置为 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. GL_UNPACK_ALIGNMENT指定 memory 中每个像素行开始的 alignment 要求。 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.默认情况下GL_UNPACK_ALIGNMENT设置为 4。这意味着图像的每一行的开头都假定与 4 的倍数的地址对齐。由于图像数据被紧密打包并且每个像素大小为 3 个字节,因此alignment 必须更改。
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.如果图像的宽度可被 4 整除(更准确地说,如果3*width可被 4 整除),则错误不明显。

Since you are reading back the texture from the GPU, you also need to change GL_PACK_ALIGNMENT :由于您正在从 GPU 读回纹理,因此您还需要更改GL_PACK_ALIGNMENT

gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
p = gl.glGetTexImage(gl.GL_TEXTURE_2D, 0, iformat, gl.GL_UNSIGNED_BYTE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM