opengl 中的图像坐标表现得很奇怪

Image coordinates in opengl behaves strange

我正在尝试使用具有以下顶点和索引的 OpenGL 从 OpenCV 渲染视频:

static const GLint ImageIndices[] {
    0, 1, 2,
    0, 2, 3
};

static const GLfloat ImageVertices[] = {
    // positions   // texCoords
    -1.0f,  1.0f,  0.0f, 1.0f,
    -1.0f, -1.0f,  0.0f, 0.0f,
     1.0f, -1.0f,  1.0f, 0.0f,
     1.0f,  1.0f,  1.0f, 1.0f
};

以及以下顶点和片段着色器:

#version 330 core
layout(location = 0) in vec2 vert_pos;
layout(location = 1) in vec2 tex_pos;

uniform mat3 trans1;
uniform mat3 trans2;

out vec2 texPos;

void main()
{
    vec3 pos = vec3(-vert_pos.y, vert_pos.x, 0.0f);
    vec3 rst;
    if(pos.y < 0.0f)
    {
        rst = pos;
        texPos = tex_pos;
    }
    else if(pos.y > 0.0f)
    {
        rst = pos;
        texPos = tex_pos;
    }
    gl_Position = vec4(rst.x, rst.y, 0.0f, 1.0f);
    //texPos = tex_pos;
}
#version 330 core

in vec2 texPos;

out vec4 fragColor;

uniform sampler2D tex;

uniform float width;
uniform float height;

void main()
{
    fragColor = texture(tex, texPos);
}

一切正常:

但是,因为我想在顶部和底部使用不同的矩阵来旋转图像,所以我更改了顶点着色器来调试图像的坐标,其中 texPosvec2(1.0f, 1.0f)pos.y > 0.0f:

#version 330 core
layout(location = 0) in vec2 vert_pos;
layout(location = 1) in vec2 tex_pos;

uniform mat3 trans1;
uniform mat3 trans2;

out vec2 texPos;

void main()
{
    vec3 pos = vec3(-vert_pos.y, vert_pos.x, 0.0f);
    vec3 rst;
    if(pos.y < 0.0f)
    {
        rst = pos;
        texPos = tex_pos;
    }
    else if(pos.y > 0.0f)
    {
        rst = pos;
        texPos = vec2(1.0f, 1.0f);
    }
    gl_Position = vec4(rst.x, rst.y, 0.0f, 1.0f);
    //texPos = tex_pos;
}

而且视频的输出很奇怪:

为什么视频变成这样,我该如何解决?

顶点着色器是按顶点执行的,而不是按片段执行的。对 2 个三角形的 6 个顶点执行 6 次。您已经更改了 pos.y > 0.0f

的 3 个顶点的纹理坐标

因为 pos = vec3(-vert_pos.y, vert_pos.x, 0.0)) 你改变了顶点的纹理坐标,其中 x > 0.0:

 x  y   u  v          x  y   u  v
-1  1   0  1    ->   -1  1   0  1
-1 -1   0  0    ->   -1 -1   0  0
 1 -1   1  0    ->    1 -1   1  1
 1  1   1  1    ->    1  1   1  1

实际上只有索引为2的顶点属性的纹理坐标发生了变化。因此,只有第一个三角形受到影响: