YUV格式转换

Posted by zz on January 9, 2020

YUV格式转换

NV21 to RGB888

  • 各种YUV格式详解: https://www.jianshu.com/p/e67f79f10c65
  • NV21是420sp的一种,先V后U,YYYYYYYYVUVU

python的直白版本

性能很差,转换1280*720的图片要1.2s

def clamp2byte(v):
    if v < 0:
        return chr(0)
    elif v > 255:
        return chr(255)
    else:
        return chr(int(v))

def convert(src, width, height):
    dst = ''
    for y in range(height):
        for x in range(width):
            Y = src[y * width + x]
            V = src[width * height + (y / 2) * width + (x / 2) * 2]
            U = src[width * height + (y / 2) * width + (x / 2) * 2 + 1]

            Y = ord(Y)
            U = ord(U)
            V = ord(V)

            R = Y + 1.402 * (V - 128);
            G = Y - 0.34413 * (U - 128) - 0.71414 * (V - 128);
            B = Y + 1.772 * (U - 128)

            R = clamp2byte(R)
            G = clamp2byte(G)
            B = clamp2byte(B)

            dst += R
            dst += G
            dst += B
    return dst