侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   199

注:本文所指的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 mathfrom functools import partialimport numpy as npimport 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 cv2import numpy as npimport 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通用就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    Python 中如何实现参数化测试的方法示例
    下一条:
    Python箱型图处理离群点的例子
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客