PyOpenGL 在着色器中显示纹理

PyOpenGL show texture in shader

我是 PyOpenGL 的新手,正在尝试将着色器添加到实时摄像机镜头中。

素材显示正确,着色器(已注释掉,因为其中还没有任何内容)也在工作。

问题是我不知道如何在片段着色器中显示相机纹理。有人可以帮忙吗?

初始化:

def init():
    #glclearcolor (r, g, b, alpha)
    glClearColor(0.0, 0.0, 0.0, 1.0)
    glutDisplayFunc(display)
    glutReshapeFunc(reshape)
    glutKeyboardFunc(keyboard)
    glutIdleFunc(idle)

    fragmentShader = compileShader(getFileContent("shader.frag"), GL_FRAGMENT_SHADER)
    global shaderProgram
    shaderProgram = glCreateProgram()
    glAttachShader(shaderProgram, fragmentShader)
    glLinkProgram(shaderProgram)

    #glUseProgram(shaderProgram) SHADER HAS NOTHING IN IT

每帧重复

def idle():
    # capture next frame
    global capture
    _, image = capture.read()
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    image = cv2.flip(image, -1)

    glTexImage2D(GL_TEXTURE_2D,
                 0,
                 GL_RGB,
                 1280, 720,
                 0,
                 GL_RGB,
                 GL_UNSIGNED_BYTE,
                 image)
    cv2.imshow('frame', image)
    glutPostRedisplay()
def display():
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glEnable(GL_TEXTURE_2D)
    
    # this one is necessary with texture2d for some reason
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
    # Set Projection Matrix
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluOrtho2D(0, width, 0, height)
    # Switch to Model View Matrix
    glMatrixMode(GL_MODELVIEW)
    glLoadIdentity()
    # Draw textured Quads
    glBegin(GL_QUADS)
    glTexCoord2f(0.0, 0.0)
    glVertex2f(0.0, 0.0)
    glTexCoord2f(1.0, 0.0)
    glVertex2f(width, 0.0)
    glTexCoord2f(1.0, 1.0)
    glVertex2f(width, height)
    glTexCoord2f(0.0, 1.0)
    glVertex2f(0.0, height)
    glEnd()
    glFlush()
    glutSwapBuffers()

请首先注意,您使用的是已弃用的 OpenGL 和 GLSL 版本以及过时的技术。阅读教程(例如 LearnOpenGL)以获得最先进的实现。


添加纹理Sampler Uniform variable to the shader. The binding via the texture object and the sampler takes place via the texture unit. Since the texture object is bound to texture unit 0 (glActiveTexture), you don't need to set the sampler at all, as its default value is 0. However you can set it with glUniform1f
使用 texture2d function to texels from a texture (see also Combine Texture + Fragment)

顶点着色器

void main()
{
    // [...]

    gl_TexCoord[0] = gl_MultiTexCoord0;

    // [...]
}

片段着色器

uniform sampler2D u_texture;

void main()
{
    // [...]

    gl_FragColor = texture2D(u_texture, gl_TexCoord[0].st);
}

片段着色器