1.libswscale实现YUV转RGB
libswscale里面实现了各种图像像素格式的转换。
libswscale使用起来很方便,最主要的函数只有3个:
(1) sws_getContext():使用参数初始化SwsContext结构体。
(2) sws_scale():转换一帧图像。
(3) sws_freeContext():释放SwsContext结构体。
其中sws_getContext()也可以用另一个接口函数sws_getCachedContext()取代。
初始化方法
初始化SwsContext除了调用sws_getContext()之外还有另一种方法,更加灵活,可以配置更多的参数。该方法调用的函数如下所示。
(1) sws_alloc_context():为SwsContext结构体分配内存。
(2) av_opt_set_XXX():通过av_opt_set_int(),av_opt_set()…等等一系列方法设置SwsContext结构体的值。在这里需要注意,SwsContext结构体的定义看不到,所以不能对其中的成员变量直接进行赋值,必须通过av_opt_set()这类的API才能对其进行赋值。
(3) sws_init_context():初始化SwsContext结构体。
这种复杂的方法可以配置一些sws_getContext()配置不了的参数。比如说设置图像的YUV像素的取值范围是JPEG标准(Y、U、V取值范围都是0-255)还是MPEG标准(Y取值范围是16-235,U、V的取值范围是16-240)。
通过av_pix_fmt_desc_get()可以获得指定像素格式的AVPixFmtDescriptor结构体。
通过AVPixFmtDescriptor结构体可以获得不同像素格式的一些信息。例如av_get_bits_per_pixel(),通过该函数可以获得指定像素格式每个像素占用的比特数(Bit Per Pixel)。
图像拉伸
SWS_BICUBIC性能比较好;SWS_FAST_BILINEAR在性能和速度之间有一个比好好的平衡。
下面看一下运行效果图:
源代码:
#include <stdio.h>
#define __STDC_CONSTANT_MACROS
#ifdef _WIN32
//Windows
extern "C"
{
#include "libswscale/swscale.h"
#include "libavutil/opt.h"
#include "libavutil/imgutils.h"
};
#else
//Linux...
#ifdef __cplusplus
extern "C"
{
#endif
#include <libswscale/swscale.h>
#include <libavutil/opt.h>
#include <libavutil/imgutils.h>
#ifdef __cplusplus
};
#endif
#endif
int main(int argc, char* argv[])
{
//Parameters
FILE *src_file =fopen("ws.yuv", "rb");
const int src_w=1920,src_h=1080;
AVPixelFormat src_pixfmt=AV_PIX_FMT_YUV420P;
//该函数可以获得指定像素格式每个像素占用的比特数(Bit Per Pixel),av_pix_fmt_desc_get()可以获得指定像素格式的AVPixFmtDescriptor结构体。
int src_bpp=av_get_bits_per_pixel(av_pix_fmt_desc_get(src_pixfmt));
FILE *dst_file = fopen("ws.rgb", "wb");
const int dst_w=1280,dst_h=720;
AVPixelFormat dst_pixfmt=AV_PIX_FMT_RGB24;
int dst_bpp=av_get_bits_per_pixel(av_pix_fmt_desc_get(dst_pixfmt));//av_pix_fmt_desc_get()可以获得指定像素格式的AVPixFmtDescriptor结构体。
//Structures
uint8_t *src_data[4];
int src_linesize[4];
uint8_t *dst_data[4];
int dst_linesize[4];
int rescale_method=SWS_BICUBIC;
struct SwsContext *img_convert_ctx;
uint8_t *temp_buffer=(uint8_t *)malloc(src_w*src_h*src_bpp/8);
int frame_idx=0;
int ret=0;
ret= av_image_alloc(src_data, src_linesize,src_w, src_h, src_pixfmt, 1);//分配资源控件
if (ret< 0) {
printf( "Could not allocate source image\n");
return -1;
}
ret = av_image_alloc(dst_data, dst_linesize,dst_w, dst_h, dst_pixfmt, 1);
if (ret< 0) {
printf( "Could not allocate destination image\n");
return -1;
}
//-----------------------------
img_convert_ctx =sws_alloc_context();//为SwsContext结构体分配内存。
//Show AVOption
av_opt_show2(img_convert_ctx,stdout,AV_OPT_FLAG_VIDEO_PARAM,0);
//Set Value
av_opt_set_int(img_convert_ctx,"sws_flags",SWS_BICUBIC|SWS_PRINT_INFO,