利用python读取YUV文件 转RGB 8bit/10bit通用
作者:_沥川往事 发布时间:2023-09-05 08:33:19
标签: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:
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
来源:https://blog.csdn.net/yuejisuo1948/article/details/83574237


猜你喜欢
- 引言在负责咨询工作的过去 6 年中,我曾多次听说关于数据访问和操作方面的问题,它时刻困扰着用户:“如何编写应用程序,以便
- 1. 信号与槽(Signals and slots)信号与槽机制是 PyQt 的核心机制,用于对象之间的通信,也就是实现函数之间的自动调用。
- 保存时代码如下:figure_corp = figure.crop( (32*rate/2, 32*rate/2, 32-32*rate/2
- write()方法把字符串str写入文件。没有返回值。由于缓冲,字符串可能不实际显示文件,直到flush()或close()方法
- 导语哈喽!我是木木子,又到了今日更新时刻!我们来看看写什么呢?小编有个好兄弟最近在追妹子,跟妹子打得火热!就差临门一脚了,这一jio我帮忙补
- 简介:fixture区别于unnitest的传统单元测试(setup/teardown)有显著改进:1.有独立的命名,并通过声明它们从测试函
- 代码如下: Function closeHTML(strContent) Dim arrTags, i, OpenPos, ClosePos
- 一、hashlib模块什么是哈希模块:hashlib模块是一种加密模块,内部存有多种加密类型加密的作用:可将明文数据进行加密,转换成一串密文
- 一、赋值不会开辟新的内存空间,只是复制了新对象的引用。所以当一个数据发生变化时,另外一个数据也会随之改变。二、浅拷贝创建新对象,其内容是对原
- 题目1、 请输入一个整数 , 若该数是偶数 , 输出 “ 是偶数” ”
- 本文主要介绍了详解python实现可视化的MD5、sha256哈希加密小工具,分享给大家,具体如下:效果图:刚启动的状态输入文本、触发加密按
- torchvision.datasetsDatasets 拥有以下API:__getitem____len__Datasets都是 torc
- JWT(JSON Web Token)是一种基于JSON的安全令牌,可以用于在不同系统之间传输认证信息。在Go中实现JWT验证,可以通过标准
- 快速入门模块提供三个类来处理一对一映射类型的一些操作'bidict', 'inverted', 'n
- 切换按钮是QPushButton的特殊模式。它是一个具有两种状态的按钮:按压和未按压。我们通过这两种状态之间的切换来修改其它内容。#!/us
- 前言本文通过使用 cpu 版本的 tensorflow 2.4 ,介绍三种方式进行加载和预处理图片数据。这里我们要确保 tensorflow
- 需求描述在利用numpy进行数据分析时,常有的一个需求是:根据已知的数组生成新数组。这个问题又可以分为两类:根据筛选条件生成子数组;根据变换
- 介绍本文主要介绍Python中set的基本知识和使用。Python中什么是setdict的作用是建立一组 key 和一组 value 的映射
- QWidget基本介绍基础窗口控件QWidget类是所有用户界面对象的基类,所有的窗口或者控件都直接或者间接的继承自QWidget类。窗口坐
- 我们在做接口测试时,除了常见的http接口,还有一种比较多见,就是socket接口,今天讲解下怎么用Python进行websocket接口测