如何使用OpenGL将RGBA转换为NV12? [英] How to convert RGBA to NV12 using OpenGL?

查看:29
本文介绍了如何使用OpenGL将RGBA转换为NV12?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用OpenGL着色器作为编码器输入将RGBA转换为NV12。

已经渲染了两个不同的碎片着色器,两个纹理都来自一个摄影机。使用V4L2获取相机图像(YUV)。然后,将YUV转换为RGB,让OpenGL渲染。下一步,我需要将RGB转换为NV12作为编码器输入,因为编码器只接受NV12格式。

推荐答案

使用计算着色器将rgb转换为平面yuv,然后对UV平面进行二倍的缩减采样。

这是计算着色器:

#version 450 core
layout(local_size_x = 32, local_size_y = 32) in;
layout(binding = 0) uniform sampler2D src;
layout(binding = 0) uniform writeonly image2D dst_y;
layout(binding = 1) uniform writeonly image2D dst_uv;
void main() {
    ivec2 id = ivec2(gl_GlobalInvocationID.xy);
    vec3 yuv = rgb_to_yuv(texelFetch(src, id).rgb);
    imageStore(dst_y, id, vec4(yuv.x,0,0,0));
    imageStore(dst_uv, id, vec4(yuv.yz,0,0));
}

有很多不同的YUV约定,我不知道您的编码器需要哪一个。因此,请将上面的rgb_to_yuv替换为YUV->RGB转换的倒数。

然后按如下步骤操作:

GLuint in_rgb = ...; // rgb(a) input texture
int width = ..., height = ...; // the size of in_rgb

GLuint tex[2]; // output textures (Y plane, UV plane)

glCreateTextures(GL_TEXTURE_2D, tex, 2);
glTextureStorage2D(tex[0], 1, GL_R8, width, height); // Y plane

// UV plane -- TWO mipmap levels
glTextureStorage2D(tex[1], 2, GL_RG8, width, height);

// use this instead if you need signed UV planes:
//glTextureStorage2D(tex[1], 2, GL_RG8_SNORM, width, height);

glBindTextures(0, 1, &in_rgb);
glBindImageTextures(0, 2, tex);
glUseProgram(compute); // the above compute shader

int wgs[3];
glGetProgramiv(compute, GL_COMPUTE_WORK_GROUP_SIZE, wgs);
glDispatchCompute(width/wgs[0], height/wgs[1], 1);

glUseProgram(0);
glGenerateTextureMipmap(tex[1]); // downsamples tex[1] 

// copy data to the CPU memory:
uint8_t *data = (uint8_t*)malloc(width*height*3/2);
glGetTextureImage(tex[0], 0, GL_RED, GL_UNSIGNED_BYTE, width*height, data);
glGetTextureImage(tex[1], 1, GL_RG, GL_UNSIGNED_BYTE, width*height/2,
    data + width*height);

免责声明:

  • 此代码未经测试。
  • 它假定宽度和高度可被32整除。
  • 它可能在什么地方丢失了内存屏障。
  • 这不是从GPU读出数据的最有效方式--在计算下一帧时,您可能至少需要向后读取一帧。

这篇关于如何使用OpenGL将RGBA转换为NV12?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆