PSNR是最基本的視頻質量評價方法。本程序中的函數可以對比兩張YUV圖片中亮度分量Y的PSNR。函數的代碼如下所示。
- /**
- * Calculate PSNR between 2 YUV420P file
- * @param url1 Location of first Input YUV file.
- * @param url2 Location of another Input YUV file.
- * @param w Width of Input YUV file.
- * @param h Height of Input YUV file.
- * @param num Number of frames to process.
- */
- int simplest_yuv420_psnr(char *url1,char *url2,int w,int h,int num){
- FILE *fp1=fopen(url1,"rb+");
- FILE *fp2=fopen(url2,"rb+");
- unsigned char *pic1=(unsigned char *)malloc(w*h);
- unsigned char *pic2=(unsigned char *)malloc(w*h);
- for(int i=0;i<num;i++){
- fread(pic1,1,w*h,fp1);
- fread(pic2,1,w*h,fp2);
- double mse_sum=0,mse=0,psnr=0;
- for(int j=0;j<w*h;j++){
- mse_sum+=pow((double)(pic1[j]-pic2[j]),2);
- }
- mse=mse_sum/(w*h);
- psnr=10*log10(255.0*255.0/mse);
- printf("%5.3f\n",psnr);
- fseek(fp1,w*h/2,SEEK_CUR);
- fseek(fp2,w*h/2,SEEK_CUR);
- }
- free(pic1);
- free(pic2);
- fclose(fp1);
- fclose(fp2);
- return 0;
- }
調用上面函數的方法如下所示。
- simplest_yuv420_psnr("lena_256x256_yuv420p.yuv","lena_distort_256x256_yuv420p.yuv",256,256,1);
對於8bit量化的像素數據來說,PSNR的計算公式如下所示。
上述公式中mse的計算公式如下所示。

其中M,N分別為圖像的寬高,xij和yij分別為兩張圖像的每一個像素值。PSNR通常用於質量評價,就是計算受損圖像與原始圖像之間的差別,以此來評價受損圖像的質量。本程序輸入的兩張圖像的對比圖如下圖所示。其中左邊的圖像為原始圖像,右邊的圖像為受損圖像。

經過程序計算后得到的PSNR取值為26.693。PSNR取值通常情況下都在20-50的范圍內,取值越高,代表兩張圖像越接近,反映出受損圖像質量越好。
