用python读取YUV文件 转RGB 8bit/10bit通用

本文介绍了一种读取和处理YUV视频的方法,包括读取8bit或10bit位深的YUV视频,以及将YUV视频转换为RGB格式。提供了Python代码示例,演示如何使用numpy和matplotlib进行数据处理和可视化。

注:本文所指的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:
                    pel = bytes2num(fp.read(2))
                    V[i, m, n] = np.uint16(pel)

        if show:
            print(i)
            plt.subplot(131)
            plt.imshow(Y[i, :, :], cmap='gray')
            plt.subplot(132)
            plt.imshow(U[i, :, :], cmap='gray')
            plt.subplot(133)
            plt.imshow(V[i, :, :], cmap='gray')
            plt.show()
            plt.pause(1)
            #plt.pause(0.001)

    if totalframe==1:
        return Y[0], U[0], V[0]
    else:
        return Y,U,V


if __name__ == '__main__':
    #y, u, v = readyuv420(r'F:\_commondata\video\176x144 qcif\football_qcif.yuv', 8, 176, 144, 1, 5, True)
    y, u, v = readyuv420(r'F:\_commondata\video\1920x1080 B\RitualDance_1920x1080_60fps_10bit_420.yuv', 10, 1920, 1080, 0, 5, True)
    print(y.shape,u.shape,v.shape)

 

以下程序将YUV转为RGB(只能读8bit位深的YUV),返回1个数组,其shape为: [frame,W,H,3]

# -*- coding: utf-8 -*-
import cv2
import numpy as np
import matplotlib.pyplot as plt
 
 
def yuv2rgb(yuvfilename, W, H, startframe, totalframe, show=False, out=False):
    # 从第startframe(含)开始读(0-based),共读totalframe帧
    arr = np.zeros((totalframe,H,W,3), np.uint8)
    
    plt.ion()
    with open(yuvfilename, 'rb') as fp:
        seekPixels = startframe * H * W * 3 // 2
        fp.seek(8 * seekPixels) #跳过前startframe帧
        for i in range(totalframe):
            print(i)
            oneframe_I420 = np.zeros((H*3//2,W),np.uint8)
            for j in range(H*3//2):
                for k in range(W):
                    oneframe_I420[j,k] = int.from_bytes(fp.read(1), byteorder='little', signed=False)
            oneframe_RGB = cv2.cvtColor(oneframe_I420,cv2.COLOR_YUV2RGB_I420)
            if show:
                plt.imshow(oneframe_RGB)
                plt.show()
                plt.pause(0.001)
            if out:
                outname = yuvfilename[:-4]+'_'+str(startframe+i)+'.png'
                cv2.imwrite(outname,oneframe_RGB[:,:,::-1])
            arr[i] = oneframe_RGB
    return arr
 
if __name__ == '__main__':
    video = yuv2rgb(r'D:\_workspace\akiyo_qcif.yuv', 176, 144, 0, 10, False, True)

 

用ffmpeg也可以,比如你需要将yuv的第8帧输出成一个png:

ffmpeg -s 176x144 -i akiyo_qcif.yuv -filter:v select="between(n\,8\,8)" out.png

 

### 如何检查 YUV 文件是否为 10bit 格式 要确认一个 YUV 文件是否为 10bit 格式,可以通过以下几个方法实现: #### 方法一:通过文件大小计算位深 对于给定分辨率的 YUV 文件,可以根据其文件大小推断出它的位深。假设分辨率为 \(W \times H\) 像素,YUV 数据采用的是常见的 4:2:0 子采样模式,则每帧的数据量可以用以下公式表示: \[ \text{Frame Size (Bytes)} = W \times H \times (\frac{\text{Bit Depth}}{8} \times 1.5) \] 如果已知文件总大小以及帧数,可以反推出单帧大小并进一步判断位深。例如,对于分辨率为 \(240 \times 120\) 的图像,如果是 8bit YUV420P,则单帧大小应为: \[ 240 \times 120 \times 1.5 = 43,200 \text{ Bytes} \] 而如果是 10bit YUV420P,则单帧大小应为: \[ 240 \times 120 \times 1.5 \times \frac{10}{8} = 54,000 \text{ Bytes} \][^1] 因此,比较实际文件大小与理论值即可初步判断。 --- #### 方法二:使用 FFmpeg 工具分析像素格式 FFmpeg 是一种强大的多媒体处理工具,可以直接查看或YUV 文件的像素格式。运行以下命令来检测输入文件的像素格式: ```bash ffprobe -i input.yuv -show_streams -select_streams v ``` 此命令会返回关于视频流的信息,其中包括 `pix_fmt` 字段。如果该字段显示为 `yuv420p10le` 或其他带有 `10` 后缀的格式,则说明这是 10bit YUV 文件[^2]。 --- #### 方法三:手动解析文件头信息(适用于特定容器) 某些情况下,YUV 数据可能被封装到特定容器中(如 `.mkv`, `.mp4`),此时可通过解码器提取元数据。然而,裸 YUV 文件通常不带头部信息,需依赖外部参数指定尺寸和格式。在这种场景下,可尝试加载文件并通过编程手段逐字节读取数据以验证范围。 以下是 Python 实现的一个简单脚本用于统计亮度分量的最大最小值: ```python import numpy as np def check_yuv_bitdepth(file_path, width, height, frames=1): frame_size = int(width * height * 1.5) with open(file_path, 'rb') as f: data = f.read(frame_size) y_data = np.frombuffer(data[:width*height], dtype=np.uint16).astype(np.int32) min_val = np.min(y_data >> 6) # Shift to match 10-bit range max_val = np.max(y_data >> 6) return min_val, max_val min_value, max_value = check_yuv_bitdepth('test10.yuv', 240, 120) print(f"Min Value: {min_value}, Max Value: {max_value}") ``` 上述代码假定 Y 分量按 16-bit 整型存储,并右移 6 位还原至有效范围 [0..1023]。若最大值超过 255 则表明可能是高比特率编码[^3]。 --- #### 方法四:借助第三方库可视化检验 除了直接操作原始数据外,还可以调用 OpenCV 库将 YUV 图像渲染出来观察效果差异。注意设置正确的色彩空间映射关系以便正确呈现画面颜色分布情况。 ```python import cv2 import numpy as np def read_10bit_yuv(filename, size=(3840, 2160)): w, h = size uv_h = h // 2 uv_w = w // 2 with open(filename,'rb')as fp: y_bytes =fp.read(w*h*2)# Read Y plane(assuming little endian uint16) u_bytes =fp.read(uv_w*uv_h*2)# U Plane v_bytes =fp.read(uv_w*uv_h*2)# V Plane # Convert bytes into arrays & reshape them accordingly. y_array =np.ndarray((h,w),dtype='uint16', buffer=y_bytes ) u_array =np.ndarray((uv_h ,uv_w ),dtype='uint16', buffer=u_bytes ).repeat(2,axis=0).repeat(2,axis=1) v_array =np.ndarray((uv_h ,uv_w ),dtype='uint16', buffer=v_bytes ).repeat(2,axis=0).repeat(2,axis=1) img=cv.merge([cv.convertScaleAbs(x>>2)for x in[y,u,v]])# Scale down from 10->8 bits per channel before merging. return img image=read_10bit_yuv('outfile.yuv',(3840,2160)) cv.imshow('Image', image); cv.waitKey(); cv.destroyAllWindows() ``` 这里需要注意调整缩放因子确保最终输出符合标准 RGB 表达形式[^4]。 ---
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值