python RGB图像到YUYV

问题描述 投票:0回答:1

我想将Bitmap转换为YUV422(YUYV)格式。我谷歌关于YUYV格式并尝试编写此代码。

path = "C:/Users/hogan/Desktop/red.bmp"
image = Image.open(path).convert("YCbCr")  # YUV
image = np.asarray(image)
width, height, YUYV = image.shape[1], image.shape[0], 4
array = np.empty((height * width * 3), dtype="uint8")
Y, U, V = 0, 1, 2
count = 0
for i in range(len(image)):
    for j in range(len(image[i])):
        for k in range(len(image[i][j])):
            if (count % 4 == 0):
                array[count] = image[i][j][Y]
            if (count % 4 == 1):
                array[count] = image[i][j][U]
            if (count % 4 == 2):
                array[count] = image[i][j][Y]
            if (count % 4 == 3):
                array[count] = image[i][j][V]
            count = count + 1
array.astype('uint8').tofile("C:/Users/hogan/Desktop/tmpdir/1.raw")

我读了这张图片,知道我的代码是错的,但不知道如何正确。 enter image description here例如:YUV中的红色(255,0,0)是(76,84,255),如果我有很多像素,我不知道应该丢弃哪个'U'和'V'。

如果使用我的代码转换480 * 640(W * H),它将是960 * 480。

python yuv
1个回答
0
投票

您可以在此处使用numpy高级索引和广播。

假设你有一张图片:

ycbcr = np.array([
    [['Y00', 'U00', 'V00'], ['Y01', 'U01', 'V01'], ['Y02', 'U02', 'V02']],
    [['Y10', 'U10', 'V10'], ['Y11', 'U11', 'V11'], ['Y12', 'U12', 'V12']],
    [['Y20', 'U20', 'V20'], ['Y21', 'U21', 'V21'], ['Y22', 'U22', 'V22']],
], dtype=str)

使用3D数组将变得难以处理,所以让我们将其转换为1D:

ycbcr = ycbcr.reshape(27)

然后,我将为YUYV流分配一个数组:

yuyv = np.array(['   ' for _ in range(18)])  # '   ' is basically because
# I use strings in this example. You'd probably want to use arrays of uint8

第一步是最简单的 - 我们采用ycbcr(Y分量)的每三个值并将它们放在yuyv的偶数位置:

yuyv[::2] = ycbcr[::3]

然后我们继续其他字节。 U00应该从位置1到位置1,V00从2到3,U01V01被省略,U02从7到5,V02从8到7,U03被省略等等:

yuyv[1::4] = ycbcr[1::6]  # Moving U, every sixth byte starting from position 1
yuyv[3::4] = ycbcr[2::6][:-1]  # Moving V, dropping last element of V

所以你得到以下yuyv,就像建议的图像:

array(['Y00', 'U00', 'Y01', 'V00', 'Y02', 'U02', 'Y10', 'V02', 'Y11',
       'U11', 'Y12', 'V11', 'Y20', 'U20', 'Y21', 'V20', 'Y22', 'U22'],
dtype='<U3')

如果你想关注@alkanen建议,这种方法也是可行的,你只需要在两个数组中采样U和V字节并取平均值。也许它看起来像这样:(未经测试)

u_even = ycbcr[1::6]
u_odd = ycbcr[4::6]
u = (u_even + u_odd) / 2
yuyv[1::4] = u

更复杂的边境案例也会遇到。

© www.soinside.com 2019 - 2024. All rights reserved.