利用利用python读取读取YUV文件文件 转转RGB 8bit/10bit通用通用
今天小编就为大家分享一篇利用python读取YUV文件 转RGB 8bit/10bit通用,具有很好的参考价值,希望对大家
有所帮助。一起跟随小编过来看看吧
注:本文所指的注:本文所指的YUV均为均为YUV420中的中的I420格式(最常见的一种),其他格式不能用以下的代码。格式(最常见的一种),其他格式不能用以下的代码。
位深为8bit时,每个像素占用1字节,对应文件指针的fp.read(1);
位深为10bit时,每个像素占用2字节,对应文件指针的fp.read(2);
然后使用 int.from_bytes() 方法将二进制转换为int型数字。
以下程序可以读8bit或10bit位深的YUV,需要指定从第几帧开始读、一共读多少帧。
它返回三个数组,其shape分别为:Y [frame,W,H] U [frame,W/2,H/2] V [frame,W/2,H/2]
当只读1帧时它返回:Y [W,H] U [W/2,H/2] V [W/2,H/2]
# -*- coding: utf-8 -*-
import math
from functools import partial
import numpy as np
import matplotlib.pyplot as plt
def readyuv420(filename, bitdepth, W, H, startframe, totalframe, show=False):
# 从第startframe(含)开始读(0-based),共读totalframe帧
uv_H = H // 2
uv_W = W // 2
if bitdepth == 8:
Y = np.zeros((totalframe, H, W), np.uint8)
U = np.zeros((totalframe, uv_H, uv_W), np.uint8)
V = np.zeros((totalframe, uv_H, uv_W), np.uint8)
elif bitdepth == 10:
Y = np.zeros((totalframe, H, W), np.uint16)
U = np.zeros((totalframe, uv_H, uv_W), np.uint16)
V = np.zeros((totalframe, uv_H, uv_W), np.uint16)
plt.ion()
bytes2num = partial(int.from_bytes, byteorder='little', signed=False)
bytesPerPixel = math.ceil(bitdepth / 8)
seekPixels = startframe * H * W * 3 // 2
fp = open(filename, 'rb')
fp.seek(bytesPerPixel * seekPixels)
for i in range(totalframe):
for m in range(H):
for n in range(W):
if bitdepth == 8:
pel = bytes2num(fp.read(1))
Y[i, m, n] = np.uint8(pel)
elif bitdepth == 10:
pel = bytes2num(fp.read(2))
Y[i, m, n] = np.uint16(pel)
for m in range(uv_H):
for n in range(uv_W):
if bitdepth == 8:
pel = bytes2num(fp.read(1))
U[i, m, n] = np.uint8(pel)
elif bitdepth == 10:
pel = bytes2num(fp.read(2))
U[i, m, n] = np.uint16(pel)
for m in range(uv_H):
for n in range(uv_W):
if bitdepth == 8:
pel = bytes2num(fp.read(1))
V[i, m, n] = np.uint8(pel)
elif bitdepth == 10:
评论0