当前位置: 首页 > 业余研究 > 正文

YUV格式学习:NV12和YUV420P格式互换

NV12和YUV420的转换是在相同采样空间的转换,只是个别分量位置的调整,只要明白了Y、U、V分量的布置,就很容易写出来。
代码如下:

/**
yyyy yyyy
uv    uv
->
yyyy yyyy
uu
vv
*/
void yuv420sp_to_yuv420p(unsigned char* yuv420sp, unsigned char* yuv420p, int width, int height)
{
    int i, j;
    int y_size = width * height;

    unsigned char* y = yuv420sp;
    unsigned char* uv = yuv420sp + y_size;

    unsigned char* y_tmp = yuv420p;
    unsigned char* u_tmp = yuv420p + y_size;
    unsigned char* v_tmp = yuv420p + y_size * 5 / 4;

    // y
    memcpy(y_tmp, y, y_size);

    // u
    for (j = 0, i = 0; j < y_size/2; j+=2, i++)
    {
        u_tmp[i] = uv[j];
        v_tmp[i] = uv[j+1];
    }
}

/**
yyyy yyyy
uu
vv
->
yyyy yyyy
uv    uv
*/
void yuv420p_to_yuv420sp(unsigned char* yuv420p, unsigned char* yuv420sp, int width, int height)
{
    int i, j;
    int y_size = width * height;

    unsigned char* y = yuv420p;
    unsigned char* u = yuv420p + y_size;
    unsigned char* v = yuv420p + y_size * 5 / 4;

    unsigned char* y_tmp = yuv420sp;
    unsigned char* uv_tmp = yuv420sp + y_size;

    // y
    memcpy(y_tmp, y, y_size);

    // u
    for (j = 0, i = 0; j < y_size/2; j+=2, i++)
    {
	// 此处可调整U、V的位置,变成NV12或NV21
#if 01
        uv_tmp[j] = u[i];
        uv_tmp[j+1] = v[i];
#else
        uv_tmp[j] = v[i];
        uv_tmp[j+1] = u[i];
#endif
    }
}

后记:
一口气把自己研究很久的东西写出来,好像都没写到点子上。以前也尝试过写技术性很强的文章,到处找资料,找出处,但后来发觉自己不是那块料,于是就直接贴代码,理论的东西反而不说——因为说不清,也怕说错。
关于YUV,初步听说是在6、7年前的大学,开始接触是在4、5年前,而真正了解其原理,却是近些年。学习进度不可谓不慢。写出来,也算有个交待。也为自己准备实现的YUV播放器做些准备。

迟 2015.8.5 晚上


本文固定链接: http://www.latelee.org/my-study/yuv-learning-nv12-to-yuv420p.html

如无特别说明,迟思堂工作室文章均为原创,转载请注明: YUV格式学习:NV12和YUV420P格式互换 | 迟思堂工作室

目前暂无评论

发表评论

*

快捷键:Ctrl+Enter