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

 更新时间:2019年12月09日 16:51:32   作者:_沥川往事  
今天小编就为大家分享一篇利用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

以上这篇利用python读取YUV文件 转RGB 8bit/10bit通用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • scrapy头部修改的方法详解

    scrapy头部修改的方法详解

    这篇文章主要给大家介绍了关于scrapy头部修改的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-12-12
  • Python中class内置方法__init__与__new__作用与区别解析

    Python中class内置方法__init__与__new__作用与区别解析

    这篇文章主要介绍了Python中class内置方法__init__与__new__作用与区别探究,本文中涉及的类均为Python3中默认的新式类,对应Python2中则为显式继承了object的class,因为未继承object基类的旧式类并没有这些内置方法,需要的朋友可以参考下
    2022-09-09
  • Python 3.6 性能测试框架Locust安装及使用方法(详解)

    Python 3.6 性能测试框架Locust安装及使用方法(详解)

    下面小编就为大家带来一篇Python 3.6 性能测试框架Locust安装及使用方法(详解)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10
  • Django框架基础模板标签与filter使用方法详解

    Django框架基础模板标签与filter使用方法详解

    这篇文章主要介绍了Django框架基础模板标签与filter使用方法,简单分析了Django模板基本语法、函数与自定义filter相关使用技巧,需要的朋友可以参考下
    2019-07-07
  • pytorch查看通道数 维数 尺寸大小方式

    pytorch查看通道数 维数 尺寸大小方式

    这篇文章主要介绍了pytorch查看通道数 维数 尺寸大小方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-05-05
  • 基于python-opencv3实现图像显示和保存操作

    基于python-opencv3实现图像显示和保存操作

    这篇文章主要介绍了基于python opencv3的图像显示和保存操作方法,本文给大家介绍的非常详细,具有一定的参考借鉴价值 ,需要的朋友可以参考下
    2019-06-06
  • pyqt5蒙版遮罩mask,setmask的使用

    pyqt5蒙版遮罩mask,setmask的使用

    mask()和setmask()一般是在pyqt绘图时常见,本文就来介绍一下pyqt5蒙版遮罩mask,setmask的使用,具有一定的参考价值,感兴趣的可以了解一下
    2021-06-06
  • python 实现 redis 数据库的操作

    python 实现 redis 数据库的操作

    这篇文章主要介绍了python 包 redis 数据库的操作教程,redis 是一个 Key-Value 数据库,下文基于python的相关资料展开对redis 数据库操作的详细介绍,需要的小伙伴可以参考一下
    2022-04-04
  • Flask-Mail用法实例分析

    Flask-Mail用法实例分析

    这篇文章主要介绍了Flask-Mail用法,结合实例形式分析了Flask-Mail的安装、配置参数及简单使用技巧,需要的朋友可以参考下
    2018-07-07
  • Python实现求笛卡尔乘积的方法

    Python实现求笛卡尔乘积的方法

    这篇文章主要介绍了Python实现求笛卡尔乘积的方法,结合实例形式分析了Python计算笛卡尔乘积的原理与实现技巧,需要的朋友可以参考下
    2017-09-09

最新评论