C/C++操作YUV视频

1.读取YUV视频

#include
using namespace std;

void readYUV()
{
	FILE* pfImgRaw = NULL;
	if (!(pfImgRaw = fopen("E:/path/to/your/nv12.yuv", "rb")))
	{
		printf("open input file failure!\n");
	}
	printf("load yuv file is OK!\n");
}

2.获取YUV视频帧数

#include
using namespace std;

void countYUVFrame()
{
	int imgWidth = 1280;
	int imgHeight = 720;
	int nums_frame;

	FILE* pfImgRaw = NULL;
	if (!(pfImgRaw = fopen("E:/path/to/your/nv12.yuv", "rb")))
	{
		printf("open input file failure!\n");
	}
	printf("load yuv file is OK!\n");

	fseek(pfImgRaw, 0, SEEK_END);  //将文件的指针指到文件末尾
	long frame_size = ftell(pfImgRaw);  //该函数返回位置标识符的当前值。如果发生错误,则返回 -1L.
	long persize = imgWidth * imgHeight * 3 / 2;  //默认YUV格式为nv12,所以每帧的大小为w*h*3/2
	nums_frame = (int)(frame_size / persize);  //总帧数=文件总大小/每帧大小
	rewind(pfImgRaw);  //防止稍后还需要操作文件,重新将文件的指针指向开头
}

3.将读取的YUV数据用opencv显示出来

#include
#include 
#include 
#include "opencv2/imgproc/imgproc_c.h"
using namespace std;
using namespace cv;
void countYUVFrame()
{
	int imgWidth = 1280;
	int imgHeight = 720;
	int nums_frame;
	unsigned char* pu8ImgCur;
	int l32BufLen = imgWidth * imgHeight * 1.5;

	FILE* pfImgRaw = NULL;
	if (!(pfImgRaw = fopen("E:/path/to/your/nv12.yuv", "rb")))
	{
		printf("open input file failure!\n");
	}
	printf("load yuv file is OK!\n");
	if (!(pu8ImgCur = (unsigned char*)malloc(l32BufLen)))
	{
		printf("malloc error!\n");
	}
	memset(pu8ImgCur, 0, l32BufLen);

	fseek(pfImgRaw, 0, SEEK_END);  //文件的指针指到文件末尾
	long frame_size = ftell(pfImgRaw);  //该函数返回位置标识符的当前值。如果发生错误,则返回 -1L.
	long persize = imgWidth * imgHeight * 3 / 2;  //默认YUV格式为nv12,所以每帧的大小为w*h*3/2
	nums_frame = (int)(frame_size / persize);  //总帧数=文件总大小/每帧大小
	rewind(pfImgRaw);  //防止稍后还需要操作文件,重新将文件的指针指向开头

	fread(pu8ImgCur, sizeof(unsigned char), l32BufLen, pfImgRaw);
	cv::Mat cv_img;
	cv::Mat cv_yuv(imgHeight + imgHeight / 2, imgWidth, CV_8UC1, pu8ImgCur);//pFrame为YUV数据地址,另外这里就是用 CV_8UC1非 CV_8UC3.
	cv_img = cv::Mat(imgHeight, imgWidth, CV_8UC3);
	cv::cvtColor(cv_yuv, cv_img, COLOR_YUV2BGR_NV12);  //这里的Mat应该是BGR顺序的,但是显示的又是RGB顺序,我不太明白
	imshow("result", cv_img);
	waitKey(0);
	fclose(pfImgRaw);
}

你可能感兴趣的:(C/C++,深度学习,c++,c语言,音视频)