将Alpha蒙版应用于OpenGL中的视频

时间:2020-06-18 02:48:45

标签: android opengl-es glsl fragment-shader vertex-shader

我想对视频应用Alpha蒙版。视频的每一帧在顶部都有颜色信息,在底部有alpha信息。像这样:

enter image description here

就我而言,我希望Alpha图像中的白色像素在主图像中透明。我还有另一种纹理可以填充这些透明像素。

我只能生成彩色图像或仅生成Alpha图像,但无法将Alpha应用于图像。我在android中使用GLES20。

这是我的代码显示黑屏:

private val vidVertexShaderCode =
        """
    precision highp float;
    attribute vec3 vertexPosition;
    attribute vec4 uvs;
    varying vec2 varUvs;
    varying vec2 varMaskUvs;
    uniform mat4 texMatrix;
    uniform mat4 mvp;

    void main()
    {
        varUvs = (texMatrix * vec4(uvs.x, uvs.y, 0, 1.0)).xy;
        varMaskUvs = (texMatrix * vec4(uvs.x, uvs.y * 0.5, 0.1, 1.0)).xy;
        gl_Position = mvp * vec4(vertexPosition, 1.0);
    }
    """

private val vidFragmentShaderCode =
        """
    #extension GL_OES_EGL_image_external : require
    precision mediump float;

    varying vec2 varUvs;
    varying vec2 varMaskUvs;
    uniform samplerExternalOES texSampler;

    void main()
    {
        vec2 m_uv  = vec2(varMaskUvs.x, varMaskUvs.y); 
        vec4 mask = texture2D(texSampler, m_uv);  

        vec2 c_uv  = vec2(varUvs.x, varUvs.y * 0.5); 
        vec4 color = texture2D(texSampler, c_uv);  
        gl_FragColor = vec4(color.rgb, color.a * mask.r)
    }
    """

我在做什么错了?

P.S。我是opengl的新手。

1 个答案:

答案 0 :(得分:3)

计算顶点着色器中图像(uvs.y * 0.5 + 0.5)和蒙版(uvs.y * 0.5)的 v 坐标:

precision highp float;
attribute vec3 vertexPosition;
attribute vec4 uvs;
varying vec2 varUvs;
varying vec2 varMaskUvs;
uniform mat4 texMatrix;
uniform mat4 mvp;

void main()
{
    varUvs      = (texMatrix * vec4(uvs.x, uvs.y * 0.5 + 0.5, 0, 1.0)).xy;
    varMaskUvs  = (texMatrix * vec4(uvs.x, uvs.y * 0.5, 0.0, 1.0)).xy;
    gl_Position = mvp * vec4(vertexPosition, 1.0);
}

您不需要在片段着色器中进行任何进一步的转换:

#extension GL_OES_EGL_image_external : require
precision mediump float;

varying vec2 varUvs;
varying vec2 varMaskUvs;
uniform samplerExternalOES texSampler;

void main()
{
    vec4 mask    = texture2D(texSampler, varMaskUvs);  
    vec4 color   = texture2D(texSampler, varUvs);  
    gl_FragColor = vec4(color.rgb, color.a * mask.r)
}