注:本文所指的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)