首页 > 解决方案 > opengl中的图像坐标表现奇怪

问题描述

我正在尝试使用具有以下顶点和索引的 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);
}

一切正常:

正常图像

但是,由于我想在顶部和底部使用不同的矩阵来旋转图像,所以我更改了顶点着色器以调试图像的texPos坐标vec2(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;
}

视频的输出很奇怪:

奇怪的图像

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

标签: openglglslshader

解决方案


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

由于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 的顶点属性的纹理坐标发生了变化。因此,仅影响第一个三角形:


推荐阅读