使用pyopengl glTexImage2D时出现OSError

问题描述

Traceback (most recent call last):
  File "./x.py",line 132,in <module>
    texid = glutils.loadTexture("wall.png")
  File "C:\Users\6e25h\Desktop\Mess\py-opengl-error\glutils.py",line 31,in loadTexture
    glTexImage2D(GL_TEXTURE_2D,GL_RGBA,img.size[0],img.size[1],GL_UNSIGNED_BYTE,imgData)
  File "src/latebind.pyx",line 39,in OpenGL_accelerate.latebind.LateBind.__call__
  File "src/wrapper.pyx",line 311,in OpenGL_accelerate.wrapper.Wrapper.__call__
  File "C:\Users\6e25h\AppData\Local\Programs\Python\python37\lib\site-packages\OpenGL\platform\baseplatform.py",line 415,in __call__
    return self( *args,**named )
OSError: exception: access violation reading 0x0000020F6D752000

我无法解决错误... 我想我无法详细描述 我的代码

def loadTexture(filename):
    """load OpenGL 2D texture from given image file"""
    img = Image.open(filename) 
    imgData = numpy.array(list(img.getdata()),np.int8)
    texture = glGenTextures(1)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glBindTexture(GL_TEXTURE_2D,texture)
    glPixelStorei(GL_UNPACK_ALIGNMENT,1)
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE)
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_TEXTURE_MAG_FILTER,GL_LINEAR)
    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR)
    glTexImage2D(GL_TEXTURE_2D,imgData)
    glBindTexture(GL_TEXTURE_2D,0)
    return texture

我该如何解决此问题?谢谢

解决方法

图像似乎没有4个颜色通道。图像很可能只有3个颜色通道。您必须指定格式GL_RGB而不是glTexImage2D中的GL_RGBA。例如:

format = GL_RGB if imgData.shape[1] == 3 else GL_RGBA
glTexImage2D(GL_TEXTURE_2D,GL_RGBA,img.size[0],img.size[1],format,GL_UNSIGNED_BYTE,imgData)