用ffmpeg可以方便的计算两个视频文件之间的psnr,命令格式如下
ffmpeg -i reference.ts -i encode.ts -lavfi psnr -f null -
YUV的对比命令如下:
ffmpeg -pix_fmt yuv420p -s 1920x1080 -i input.yuv -pix_fmt yuv420p -s 1920x1080 -i output.yuv -lavfi psnr -f null -
不过,ffmpeg计算的psnr与x264、x265得到的psnr值是不一致的(用x264编码YUV,得到编码后PSNR,然后用ffmpeg计算x264的重建yuv与原始yuv的PSNR,两者结果不同),这主要是两者计算psnr的方式有差别:
x264、x265是计算每一帧的psnr,最终对整个序列求平均psnr。
ffmpeg是计算每一帧的MSE(均方差),然后计算整个序列的平均MSE,最后计算psnr。即ffmpeg是将整个视频当做一个信号来分析,x264、x265将每一帧当做一个信号来分析,然后将所有信号的结果求平均。
具体代码在vf_psnr.c文件的函数do_psnr()和unint()中: do_psnr对每一帧计算MSE,并且将结果累加;在unint函数中,根据整个序列的MSE,计算得到最终的PSNR.
static AVFrame *do_psnr(AVFilterContext *ctx, AVFrame *main,
const AVFrame *ref)
{
PSNRContext *s = ctx->priv;
double comp_mse[4], mse = 0;
int j, c;
AVDictionary **metadata = avpriv_frame_get_metadatap(main);
compute_images_mse(s, (const uint8_t **)main->data, main->linesize,
(const uint8_t **)ref->data, ref->linesize,
main->width, main->height, comp_mse);
for (j = 0; j < s->nb_components; j++)
mse += comp_mse[j] * s->planeweight[j];
s->min_mse = FFMIN(s->min_mse, mse);
s->max_mse = FFMAX(s->max_mse, mse);
s->mse += mse; // 每一帧的总的MSE进行累加
for (j = 0; j < s->nb_components; j++)
s->mse_comp[j] += comp_mse[j]; // 每一帧Y、U、V分量的MSE分别进行累加
s->nb_frames++;
for (j = 0; j < s->nb_components; j++) {
c = s->is_rgb ? s->rgba_map[j] : j;
set_meta(metadata, "lavfi.psnr.mse.", s->comps[j], comp_mse[c]);
set_meta(metadata, "lavfi.psnr.psnr.", s->comps[j], get_psnr(comp_mse[c], 1, s->max[c]));
}
set_meta(metadata, "lavfi.psnr.mse_avg", 0, mse);
set_meta(metadata, "lavfi.psnr.psnr_avg", 0, get_psnr(mse, 1, s->average_max));
if (s->stats_file) {
fprintf(s->stats_file, "n:%"PRId64" mse_avg:%0.2f ", s->nb_frames, mse);
for (j = 0; j < s->nb_components; j++) {
c = s->is_rgb ? s->rgba_map[j] : j;
fprintf(s->stats_file, "mse_%c:%0.2f ", s->comps[j], comp_mse[c]);
}
fprintf(s->stats_file, "psnr_avg:%0.2f ", get_psnr(mse, 1, s->average_max));
for (j = 0; j < s->nb_components; j++) {
c = s->is_rgb ? s->rgba_map[j] : j;
fprintf(s->stats_file, "psnr_%c:%0.2f ", s->comps[j],
get_psnr(comp_mse[c], 1, s->max[c]));
}
fprintf(s->stats_file, "\n");
}
return main;
}
static av_cold void uninit(AVFilterContext *ctx)
{
PSNRContext *s = ctx->priv;
if (s->nb_frames > 0) {
int j;
char buf[256];
buf[0] = 0;
for (j = 0; j < s->nb_components; j++) {
int c = s->is_rgb ? s->rgba_map[j] : j;
av_strlcatf(buf, sizeof(buf), " %c:%f", s->comps[j],
get_psnr(s->mse_comp[c], s->nb_frames, s->max[c])); // 对整个序列计算Y、U、V分量的PSNR
}
av_log(ctx, AV_LOG_INFO, "PSNR%s average:%f min:%f max:%f\n",
buf,
get_psnr(s->mse, s->nb_frames, s->average_max), // 对整个序列计算整体PSNR
get_psnr(s->max_mse, 1, s->average_max),
get_psnr(s->min_mse, 1, s->average_max));
}
ff_dualinput_uninit(&s->dinput);
if (s->stats_file && s->stats_file != stdout)
fclose(s->stats_file);
}
修改了ffmpeg,可以输出每一帧PSNR值,同时在最后输出两种方式的psnr结果,方便对比,两者的结果还是有很明显的差别的,下载链接:
https://download.csdn.net/download/lrzkd/11998317
https://pan.baidu.com/s/1fhZtZEVU-dm1V9BteIPS1Q