YUY2ToNV12 的使用demo
时间: 2023-07-11 20:29:57 浏览: 45
以下是使用 YUY2ToNV12 进行图像转换的示例代码:
```cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
extern "C" {
#include "libavutil/imgutils.h"
#include "libavutil/opt.h"
#include "libavutil/pixdesc.h"
#include "libswscale/swscale.h"
}
int main(int argc, char* argv[]) {
const char* src_filename = "input.yuy2";
const char* dst_filename = "output.nv12";
const int src_width = 640;
const int src_height = 480;
// 打开输入文件
FILE* src_file = fopen(src_filename, "rb");
if (!src_file) {
std::cerr << "Could not open source file: " << src_filename << std::endl;
return -1;
}
// 打开输出文件
FILE* dst_file = fopen(dst_filename, "wb");
if (!dst_file) {
std::cerr << "Could not open destination file: " << dst_filename << std::endl;
return -1;
}
// 准备输入帧
uint8_t* src_data[4];
int src_linesize[4];
src_data[0] = (uint8_t*)malloc(src_width * src_height * 2);
src_linesize[0] = src_width * 2;
// 准备输出帧
uint8_t* dst_data[4];
int dst_linesize[4];
dst_data[0] = (uint8_t*)malloc(src_width * src_height * 3 / 2);
dst_linesize[0] = src_width;
// 读取输入帧
if (fread(src_data[0], 1, src_width * src_height * 2, src_file) != src_width * src_height * 2) {
std::cerr << "Could not read input frame" << std::endl;
return -1;
}
// 创建图像转换上下文
SwsContext* sws_ctx = sws_getContext(src_width, src_height, AV_PIX_FMT_YUYV422, src_width, src_height, AV_PIX_FMT_NV12, 0, 0, 0, 0);
if (!sws_ctx) {
std::cerr << "Could not create sws context" << std::endl;
return -1;
}
// 进行图像转换
sws_scale(sws_ctx, src_data, src_linesize, 0, src_height, dst_data, dst_linesize);
// 写入输出帧
if (fwrite(dst_data[0], 1, src_width * src_height * 3 / 2, dst_file) != src_width * src_height * 3 / 2) {
std::cerr << "Could not write output frame" << std::endl;
return -1;
}
// 释放资源
sws_freeContext(sws_ctx);
fclose(src_file);
fclose(dst_file);
free(src_data[0]);
free(dst_data[0]);
return 0;
}
```
代码中的 YUY2ToNV12 图像转换使用了 FFmpeg 的 libswscale 库进行实现。在代码中,我们首先打开输入文件和输出文件,并准备输入帧和输出帧的内存空间。然后,我们读取输入帧,创建图像转换上下文,进行图像转换,最后将输出帧写入输出文件。最后,我们释放资源并返回。