PSNR值在matlab实现和python中有所不同

时间:2017-07-06 09:07:05

标签: matlab opencv numpy octave mse

我已经实现了一个python代码,用于计算YCrCb通道中Y通道的PSNR值。 我得到的PSNR值大约为35.7dB(对于一对图像)

import cv2, main
import sys

i1 = cv2.imread(sys.argv[1])
i2 = cv2.imread(sys.argv[2])

i1= cv2.cvtColor(i1, cv2.COLOR_BGR2YCrCb)
i2= cv2.cvtColor(i2, cv2.COLOR_BGR2YCrCb)

print(main.psnr(i1[:,:,0], i2[:,:,0]))

在主psnr中定义为:

def psnr(target, ref):
    import cv2
    target_data = numpy.array(target, dtype=numpy.float64)
    ref_data = numpy.array(ref,dtype=numpy.float64)

    diff = ref_data - target_data
    print(diff.shape)
    diff = diff.flatten('C')

    rmse = math.sqrt(numpy.mean(diff ** 2.))

    return 20 * math.log10(255 / rmse)

我在matlab中获得了一个在线实现(来自我所指的论文) 我得到的PSNR值约为37.06dB(对于同一对图像)

function psnr=compute_psnr(im1,im2)
if size(im1, 3) == 3,
    im1 = rgb2ycbcr(im1);
    im1 = im1(:, :, 1);
end

if size(im2, 3) == 3,
    im2 = rgb2ycbcr(im2);
    im2 = im2(:, :, 1);
end

imdff = double(im1) - double(im2);
imdff = imdff(:);

rmse = sqrt(mean(imdff.^2));
psnr = 20*log10(255/rmse)

这个错误可能是由numpy或精确numpy引入的错误导致的吗?

1 个答案:

答案 0 :(得分:2)

您的两个转换函数似乎会产生截然不同的结果:

  

Python输出:   enter image description here

  

八度输出:   enter image description here

解释了这种差异。

Octave确实提到了几种YCbCr标准:

 The formula used for the conversion is dependent on two constants,
 KB and KR which can be specified individually, or according to
 existing standards:

 "601" (default)
      According to the ITU-R BT.601 (formerly CCIR 601) standard.
      Its values of KB and KR are 0.114 and 0.299 respectively.
 "709" (default)
      According to the ITU-R BT.709 standard.  Its values of KB and
      KR are 0.0722 and 0.2116 respectively.

也许python版本使用不同的标准? (或者它可能是BGR与RGB问题?)。在任何情况下,差异所在的地方,它似乎都不是精确的问题(当这些函数分别使用相同的输入进行测试时,它们会产生相同的结果)。

修改

根据这些:

python(或者更确切地说,opencv库)似乎正在输出'模拟' (未缩放的)版本,而matlab / octave正在输出数字' (缩放版)。

这已得到确认:

# Python
RGB = numpy.concatenate(
  ( numpy.array([[[0], [255], [255], [0],   [0],   [0],   [255]]], dtype=numpy.uint8),
    numpy.array([[[0], [0],   [255], [255], [255], [0],   [255]]], dtype=numpy.uint8),
    numpy.array([[[0], [0],   [0],   [0],   [255], [255], [255]]], dtype=numpy.uint8)),
  axis=2)

RGB2Y = cv2.cvtColor(RGB, cv2.COLOR_BGR2YCrCb)
print(RGB2Y)
[[[  0 128 128]
  [ 29 107 255]
  [179   0 171]
  [150  21  43]
  [226 149   1]
  [ 76 255  85]
  [255 128 128]]]
% Octave
pkg load image;
RGB = uint8 (cat (3, [0, 255, 255, 0,   0,   0,   255], ...
                     [0, 0,   255, 255, 255, 0,   255], ...
                     [0, 0,   0,   0,   255, 255, 255]));
RGB2Y = rgb2ycbcr(RGB)
RGB2Y =
 ans(:,:,1) =
   16   81  210  145  170   41  235
 ans(:,:,2) =
   128   90   16   54  166  240  128
 ans(:,:,3) =
   128  240  146   34   16  110  128

因此,如果它是实现一致性的问题,我会使用上面的维基百科页面中提到的从模拟到数字的转换公式来缩放python结果,即:

如果问题是"哪个版本最适合计算PSNR",我不知道,但是我从中读到的是上面的链接,我的钱将在matlab / octave实现。