RGB和YUV互转
python
class Color:
# BT601 数字Full range
def __init__(self):
pass
def YUV2RGB(self, Y, U, V):
# R,G,B (0~255)
R= Y + ((360 * (V - 128))>>8)
G= Y - (( ( 88 * (U - 128) + 184 * (V - 128)) )>>8)
B= Y +((455 * (U - 128))>>8)
return R,G,B
def RGB2YUV(self, R, G, B):
# Y(0~255), U,V(-128~128)
Y = (77*R + 150*G + 29*B)>>8
U = ((-44*R - 87*G + 131*B)>>8) + 128
V = ((131*R - 110*G - 21*B)>>8) + 128
return Y,U,V
def YUV2RGBF(self, Y, U, V):
# R,G,B (0.0~255.0)
R = Y+1.4075*(V-128)
G = Y-0.3455*(U-128)-0.7169*(V-128)
B = Y+1.779*(U-128)
return R,G,B
def RGB2YUVF(self, R, G, B):
# Y(0.0~255.0), U,V(-128.0~128.0)
Y = 0.299*R + 0.587*G + 0.114*B
U = -0.169*R - 0.331*G + 0.5*B + 128
V = 0.5*R - 0.419*G - 0.081*B + 128
return Y,U,V
# 测试代码:
color = Color()
y,u,v = color.RGB2YUV(255, 255, 255)
print("Y:{:.02f}, U:{:.02f}, V:{:.02f}".format(y, u, v))
r,g,b = color.YUV2RGB(y,u,v)
print("R:{:.02f}, G:{:.02f}, B:{:.02f}".format(r, g, b))