FFMPEG 实现 YUV,RGB各种图像原始数据之间的转换(swscale)

本文介绍如何使用FFMPEG库进行视频解码并将解码后的数据转换为YUV420、YUV422、RGB24等不同格式的原始数据文件。关键步骤包括设置转换格式、初始化转换上下文以及根据目标格式保存数据。通过理解FFMPEG中的planar和packed数据布局,可以正确地写入和保存不同格式的图像数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FFMPEG中的swscale提供了视频原始数据(YUV420,YUV422,YUV444,RGB24...)之间的转换,分辨率变换等操作,使用起来十分方便,在这里记录一下它的用法。
swscale主要用于在2个AVFrame之间进行转换。

下面来看一个视频解码的简单例子,并将解码后的数据保存为原始数据文件(例如YUV420,YUV422,RGB24等等)。

/**
*  使用FFmpeg解析出H264、YUV数据
*/

#include <stdio.h>

extern "C"
{
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
#include "libswscale/swscale.h"
#include "libavutil/imgutils.h"
};

#pragma comment(lib, "avcodec.lib")
#pragma comment(lib, "avformat.lib")
#pragma comment(lib, "swscale.lib")
#pragma comment(lib, "avutil.lib")

int main(int argc, char* argv[])
{
	AVFormatContext		*pFormatCtx = NULL;
	AVCodecContext		*pCodecCtx = NULL;
	AVCodec				*pCodec = NULL;
	AVFrame				*pFrame = NULL, *pFrameYUV = NULL;
	unsigned char		*out_buffer = NULL;
	AVPacket			packet;
	struct SwsContext	*img_convert_ctx = NULL;
	int					got_picture;
	int					videoIndex;
	int					frame_cnt = 1;

	char filepath[] = "Titanic.ts";
	//char filepath[] = "Forrest_Gump_IMAX.mp4";

	FILE *fp_yuv = fopen("film.yuv", "wb+");
	FILE *fp_h264 = fopen("film.h264", "wb+");
	if (fp_yuv == NULL || fp_h264 == NULL)
	{
		printf("FILE open error");
		return -1;
	}

	av_register_all();

	if (avformat_open_input(&pFormatCtx, filepath, NULL, NULL) != 0){
		printf("Couldn't open an input stream.\n");
		return -1;
	}
	if (avformat_find_stream_info(pFormatCtx, NULL) < 0){
		printf("Couldn't find stream information.\n");
		return -1;
	}
	videoIndex = -1;
	for (int i = 0; i < pFormatCtx->nb_streams; i++)
		if (pFormatCtx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO){
			videoIndex = i;
			break;
		}

	if (videoIndex == -1){
		printf("Couldn't find a video stream.\n");
		return -1;
	}

	pCodecCtx = pFormatCtx->streams[videoIndex]->codec;
	pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
	if (pCodec == NULL){
		printf("Codec not found.\n");
		return -1;
	}
	if (avcodec_open2(pCodecCtx, pCodec, NULL) < 0){
		printf("Could not open codec.\n");
		return -1;
	}



	pFrame = av_frame_alloc();
	pFrameYUV = av_frame_alloc();
	if (pFrame == NULL || pFrameYUV == NULL)
	{
		printf("memory allocation error\n");
		return -1;
	}

	/**
	*  RGB--------->AV_PIX_FMT_RGB24
	*  YUV420P----->AV_PIX_FMT_YUV420P
	*  UYVY422----->AV_PIX_FMT_UYVY422
	*  YUV422P----->AV_PIX_FMT_YUV422P
	*/
	out_buffer = (unsigned char *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1));
	av_image_fill_arrays(pFrameYUV->data, pFrameYUV->linesize, out_buffer,
		AV_PIX_FMT_YUV420P, pCodecCtx->width, pCodecCtx->height, 1);
	img_convert_ctx = sws_getContext(pCodecCtx->width, pCodecCtx->height, pCodecCtx->pix_fmt,
		pCodecCtx->width, pCodecCtx->height, AV_PIX_FMT_YUV420P, SWS_BICUBIC, NULL, NULL, NULL);




	/*
	//针对H.264码流
	unsigned char *dummy = NULL;   //输入的指针  
	int dummy_len;
	const char nal_start[] = { 0, 0, 0, 1 };
	AVBitStreamFilterContext* bsfc = av_bitstream_filter_init("h264_mp4toannexb");
	av_bitstream_filter_filter(bsfc, pCodecCtx, NULL, &dummy, &dummy_len, NULL, 0, 0);
	fwrite(pCodecCtx->extradata, pCodecCtx->extradata_size, 1, fp_h264);
	av_bitstream_filter_close(bsfc);
	free(dummy);
	*/
	while (av_read_frame(pFormatCtx, &packet) >= 0)
	{
		if (packet.stream_index == videoIndex)
		{
			//输出出h.264数据
			fwrite(packet.data, 1, packet.size, fp_h264);
			
			//针对H.264码流
			//fwrite(nal_start, 4, 1, fp_h264);
			//fwrite(packet.data + 4, packet.size - 4, 1, fp_h264);

			if (avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, &packet) < 0)
			{
				printf("Decode Error.\n");
				return -1;
			}
			if (got_picture)
			{
				sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
					pFrameYUV->data, pFrameYUV->linesize);

				//输出出YUV数据
				int y_size = pCodecCtx->width * pCodecCtx->height;
				fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv);		//Y 
				fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv);	//U
				fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv);	//V

				/**
				*  输出RGB数据
				*  fwrite(pFrameYUV->data[0], (pCodecCtx->width) * (pCodecCtx->height) * 3, 1, fp);
				*  输出UYVY数据
				*  fwrite(pFrameYUV->data[0], (pCodecCtx->width) * (pCodecCtx->height), 2, fp);
				*/
				
				printf("Succeed to decode %d frame!\n", frame_cnt);
				frame_cnt++;
			}
		}
		av_free_packet(&packet);
	}

	//flush decoder
	//FIX: Flush Frames remained in Codec
	while (true)
	{
		if (avcodec_decode_video2(pCodecCtx, pFrame, &got_picture, &packet) < 0)
		{
			break;
		}
		if (!got_picture)
		{
			break; 
		}
			
		sws_scale(img_convert_ctx, (const unsigned char* const*)pFrame->data, pFrame->linesize, 0, pCodecCtx->height,
			pFrameYUV->data, pFrameYUV->linesize);

		int y_size = pCodecCtx->width * pCodecCtx->height;
		fwrite(pFrameYUV->data[0], 1, y_size, fp_yuv);		//Y 
		fwrite(pFrameYUV->data[1], 1, y_size / 4, fp_yuv);	//U
		fwrite(pFrameYUV->data[2], 1, y_size / 4, fp_yuv);	//V

		printf("Flush Decoder: Succeed to decode %d frame!\n", frame_cnt);
		frame_cnt++;
	}


	fclose(fp_yuv);
	fclose(fp_h264);
	sws_freeContext(img_convert_ctx);
	av_free(out_buffer);
	av_frame_free(&pFrameYUV);
	av_frame_free(&pFrame);
	avcodec_close(pCodecCtx);
	avformat_close_input(&pFormatCtx);

	return 0;
}

从代码中可以看出,解码后的视频帧数据保存在pFrame变量中,然后经过swscale函数转换后,将视频帧数据保存在pFrameYUV变量中。最后将pFrameYUV中的数据写入成文件。

在本代码中,将数据保存成了RGB24的格式。如果想保存成其他格式,比如YUV420,YUV422等,需要做2个步骤:

1.初始化pFrameYUV的时候,设定想要转换的格式:

  1. AVFrame*pFrame,*pFrameYUV;
  2. pFrame=avcodec_alloc_frame();
  3. pFrameYUV=avcodec_alloc_frame();
  4. uint8_t*out_buffer;
  5. out_buffer=newuint8_t[avpicture_get_size(PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height)];
  6. avpicture_fill((AVPicture*)pFrameYUV,out_buffer,PIX_FMT_RGB24,pCodecCtx->width,pCodecCtx->height);
只需要把PIX_FMT_***改了就可以了

2.在sws_getContext()中更改想要转换的格式:

<think>我们正在使用FFmpegYUV格式文件转换为JPG图片。根据引用内容,我们可以参考一些已有的代码片段,但需要整合并解释步骤。 步骤: 1. 设置FFmpeg的环境(包括注册编解码器等)。 2. 打开输入文件(YUV文件)并设置解码器。 3. 读取YUV数据,解码为AVFrame。 4. 设置图像转换上下文(将YUV转换RGB,因为JPG通常是RGB格式)。 5. 设置编码器(JPG编码器)并创建输出流。 6. 将转换后的RGB帧编码为JPG图片并写入文件。 但是,注意引用[1]中提到了将YUV420转换RGB24的代码,而引用[2]中有一个将MP4YUV成JPG的示例(但未给出完整代码)。因此,我们将结合这些信息。 由于YUV文件是原始视频数据,我们需要知道其宽度、高度和像素格式(例如YUV420P)。 下面是一个大致的步骤和代码框架(使用C语言和FFmpeg库): 步骤: 1. 初始化FFmpeg:注册所有的编解码器和格式。 2. 打开输入YUV文件(作为原始视频文件)。 3. 设置解码器(对于原始视频,通常使用rawvideo解码器)并设置参数(宽、高、像素格式)。 4. 创建图像转换上下文(sws_context)用于将YUV转换RGB。 5. 创建编码器(JPEG编码器)并设置编码参数。 6. 分配帧和包。 7. 循环读取YUV数据(因为YUV文件可能包含多帧),每帧进行转换和编码。 8. 将编码后的数据写入JPG文件(每帧一个文件)。 注意:由于YUV原始文件没有封装格式,我们需要指定其参数(宽、高、像素格式)。 代码示例(基于引用[2]和[1]的思路): 注意:以下代码需要包含相应的FFmpeg头文件,并链接FFmpeg库。 由于问题只要求转换一帧(或者多帧)为JPG,我们假设用户想要将每一帧保存为一个JPG文件。 以下是一个简化的示例代码,将YUV420P文件的一帧转换为JPG图片。如果需要多帧,则循环读取即可。 注意:由于YUV文件没有头部信息,我们必须事先知道宽度、高度和帧数(或者直到文件结束)。 步骤详解: 1. 初始化 2. 打开输入文件 3. 设置解码器上下文(codec context)为rawvideo 4. 设置图像转换上下文(SwsContext)将AV_PIX_FMT_YUV420P转换为AV_PIX_FMT_RGB24(因为JPEG编码器通常使用RGB) 5. 设置JPEG编码器 6. 分配AVFrame用于存储YUV数据和RGB数据 7. 读取一帧YUV数据(一帧YUV420P的大小为 width*height*3/2 字节) 8. 转换YUVRGB 9. 编码RGB帧为JPEG 10. 写入文件 代码示例(注意:错误处理已简化,实际使用中应加强):</think>### 使用FFmpegYUV转换为JPG格式图片 以下是使用FFmpegYUV格式文件转换为JPG图片的完整步骤和代码实现: #### 核心步骤 1. **设置YUV参数** 需明确YUV文件的宽度、高度、像素格式(如`yuv420p`)和帧数 2. **创建转换上下文** 使用`sws_getContext()`初始化图像格式转换器 3. **分配帧内存** 为输入(YUV)和输出(RGB)分别分配`AVFrame` 4. **格式转换** 用`sws_scale()`将YUVRGB24格式 5. **编码保存** 将RGB数据通过JPEG编码器写入JPG文件 #### C语言实现代码 ```c #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswscale/swscale.h> #include <stdio.h> int main() { // 初始化参数 const int width = 640; // YUV图像宽度 const int height = 480; // YUV图像高度 const char* pix_fmt = "yuv420p"; const char* input_file = "input.yuv"; const char* output_file = "output.jpg"; // 注册FFmpeg组件 av_register_all(); // 分配帧内存 AVFrame* yuv_frame = av_frame_alloc(); AVFrame* rgb_frame = av_frame_alloc(); uint8_t* buffer = (uint8_t*)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB24, width, height, 1)); av_image_fill_arrays(rgb_frame->data, rgb_frame->linesize, buffer, AV_PIX_FMT_RGB24, width, height, 1); // 创建格式转换上下文 struct SwsContext* sws_ctx = sws_getContext( width, height, AV_PIX_FMT_YUV420P, width, height, AV_PIX_FMT_RGB24, SWS_BILINEAR, NULL, NULL, NULL ); // 打开YUV文件 FILE* f_yuv = fopen(input_file, "rb"); fread(yuv_frame->data[0], 1, width * height, f_yuv); // Y分量 fread(yuv_frame->data[1], 1, width * height / 4, f_yuv); // U分量 fread(yuv_frame->data[2], 1, width * height / 4, f_yuv); // V分量 // 执行格式转换 sws_scale(sws_ctx, (const uint8_t* const*)yuv_frame->data, yuv_frame->linesize, 0, height, rgb_frame->data, rgb_frame->linesize); // 保存为JPG FILE* f_jpg = fopen(output_file, "wb"); fwrite(rgb_frame->data[0], 1, width * height * 3, f_jpg); // 清理资源 fclose(f_yuv); fclose(f_jpg); sws_freeContext(sws_ctx); av_frame_free(&yuv_frame); av_frame_free(&rgb_frame); av_free(buffer); return 0; } ``` #### 命令行直接转换 ```bash ffmpeg -s 640x480 -pix_fmt yuv420p -i input.yuv -frames:v 1 output.jpg ``` 参数说明: - `-s 640x480`:设置分辨率 - `-pix_fmt yuv420p`:指定像素格式 - `-frames:v 1`:转换第1帧 #### 关键注意事项 1. **内存对齐** YUV420P每帧数据大小 = 宽度×高度 × 1.5 (Y占1份,UV各占0.25份) 2. **像素格式** 常见格式有`yuv420p`/`yuv422p`/`yuv444p`,需与实际文件匹配 3. **多帧处理** 循环读取帧数据可实现批量转换 4. **性能优化** 大分辨率文件建议使用硬件加速(如添加`-hwaccel cuda`参数) > 注意:编译时需链接FFmpeg库 `-lavcodec -lavutil -lswscale`[^1][^2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值