Python实现YUV420P转PNG的两种方案及帧拆分工具

栗子
栗子
发布时间:2026-10-14| 3人浏览过
原创

本文详细介绍利用Python将YUV420P格式视频帧转换为PNG图片的两种方法。第一种基于OpenCV手动解析YUV分量并重组图像,第二种通过调用FFmpeg命令行工具实现转换。此外,文章还附带了使用C语言将连续YUV文件拆分为单帧文件的代码示例,并提供相关测试视频资源链接。

第一种方案是利用Python结合OpenCV库,手动读取YUV420P格式的二进制数据,并将其解析为RGB格式后保存为PNG图片。具体实现时,需要明确视频的分辨率(例如352x288),然后按照YUV420P的存储结构,依次读取Y、U、V分量。Y分量占据前H*W个字节,U和V分量各占H*W/4个字节,且U、V的采样率为Y的一半。代码中通过嵌套循环逐像素读取Y值,再按4:2:0的采样规则填充U和V矩阵。最后,利用numpy将Y、U、V数组合并为三维数组,并通过OpenCV的cvtColor函数将其转换为RGB格式,最终使用cv.imwrite保存为PNG文件。


import os
import cv2 as cv
import numpy as np


# 读取yuv420p的一帧文件,并转化为png图片
if __name__ == '__main__':
  filepath = 'one_frame_of_highway.yuv'
  binfile = open(filepath, 'rb')
  size = os.path.getsize(filepath)
  image_width = 352
  image_hight = 288
  image_y = [[0] * image_width for i in range(image_hight)]
  image_u = [[0] * image_width for i in range(image_hight)]
  image_v = [[0] * image_width for i in range(image_hight)]
  for r in range(image_hight):
    for c in range(image_width):
      image_y[r][c] = binfile.read(1)[0]
  Image_Y = np.array(image_y)

  for r in range(int(image_hight / 2)):
    for c in range(int(image_width / 2)):
      pixel = binfile.read(1)[0]
      image_u[2 * r + 0][2 * c + 0] = pixel
      image_u[2 * r + 1][2 * c + 0] = pixel
      image_u[2 * r + 0][2 * c + 1] = pixel
      image_u[2 * r + 1][2 * c + 1] = pixel
  Image_U = np.array(image_u)

  for r in range(int(image_hight / 2)):
    for c in range(int(image_width / 2)):
      pixel = binfile.read(1)[0]
      image_v[2 * r + 0][2 * c + 0] = pixel
      image_v[2 * r + 0][2 * c + 1] = pixel
      image_v[2 * r + 1][2 * c + 0] = pixel
      image_v[2 * r + 1][2 * c + 1] = pixel
  Image_V = np.array(image_v)
  binfile.close()
  compose = np.array([Image_Y, Image_V, Image_U]).transpose([1, 2, 0]).astype(np.uint8)
  Image = cv.cvtColor(compose, cv.COLOR_YUV2RGB)
  cv.imwrite("one_frame_of_highway.yuv.png", Image)

第二种方案更为简洁,直接借助FFmpeg命令行工具进行格式转换。用户只需在终端执行包含分辨率参数(-s)的FFmpeg命令,指定输入文件为YUV格式,输出文件为PNG格式即可。例如,命令`ffmpeg -s 352x288 -i one_frame_of_highway.yuv one_frame_of_highway.png`即可将指定分辨率的单帧YUV文件直接转换为PNG图片。这种方法无需编写复杂的解析代码,适合快速处理或批量转换场景。


 ffmpeg -s 352x288 -i one_frame_of_highway.yuv one_frame_of_highway.png

如需测试视频素材,可访问highway视频网址:http://trace.eas.asu.edu/yuv/index.html获取标准的YUV序列文件。

附录:

除了转换为PNG图片外,有时需要将连续的YUV视频文件拆分为单独的单帧YUV文件。附录提供了一段C语言代码,用于实现这一功能。该程序首先通过fstat获取文件总大小,然后根据CIF格式(352x288)计算单帧大小(Y+U+V)。接着,程序遍历文件内容,按帧大小截取数据,并将每一帧写入以指定前缀命名的独立文件中。通过这种方式,可以将一个大的YUV文件分解为多个小的单帧YUV文件,便于后续逐帧处理或分析。


#include <stdio.h>
#include <fcntl.h>
#include <zconf.h>
#include <stdint.h>
#include <strings.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
int File_Size(int fd) {
  struct stat st;
  fstat(fd, &st);
  return st.st_size;
}

int Frame_Size_Of_Cif() {
  int width = 352;
  int heigh = 288;
  int Y_SIZE = width * heigh;
  int U_SIZE = Y_SIZE / 4;
  int V_SIZE = Y_SIZE / 4;
  int Frame_SIZE = Y_SIZE + U_SIZE + V_SIZE;
  return Frame_SIZE;
}

int Frames_Of_Cif_File(int fd) {
  if (fd < 0) {
    printf("Invalid FD!");
    return -1;
  }
  int Frame_SIZE = Frame_Size_Of_Cif();
  int fd_size = File_Size(fd);
  return fd_size / Frame_SIZE;
}

void Abstract_Frame_From_CIF_File(int fd,char *Path_And_Prefix_Img,int Len) {
  int Frame_SIZE = Frame_Size_Of_Cif();
  char file[128];
  memset(file,0,128);
  memcpy(file,Path_And_Prefix_Img,Len);
  uint8_t buf[Frame_SIZE];
  int ret = -1;
  int frames = 0;
  while ((ret = read(fd, buf, Frame_SIZE))) {
    frames += 1;
    uint64_t len = strlen(file);
    sprintf(file + len, "%d", frames);
    len = strlen(file);
    sprintf(file + len, "%s", ".yuv");
    int fdw = open(file, O_RDWR | O_CREAT, 0777);
    write(fdw, buf, ret);
    memset(file,0,128);
    memcpy(file,Path_And_Prefix_Img,Len);
    close(fdw);
  }
  printf("Abstract %d frames!\n", frames);
}


int main() {

  int fd = open("./yuv420p_352x288.yuv", O_RDONLY);
  Abstract_Frame_From_CIF_File(fd,"/home/liu/Frames/Frames_",strlen("/home/liu/Frames/Frames_"));
  close(fd);
  return 0;
}

以上就是python将YUV420P文件转PNG图片格式的两种方法的详细内容,更多关于python将YUV420P的资料请关注本站其它相关文章!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。