5

When using opencv's resize

img = cv2.imread('fname.png', 0 )
res = cv2.resize(img,None,fx=2, fy=2, interpolation = cv2.INTER_CUBIC)
cv2.imwrite('scaled_cv2.png',res)

and matlab's imresize

I = imread('fname.png');
J = imresize(I,2, 'Antialiasing', false, 'Method', 'bicubic');
imwrite(J,'scaled_matlab.png')

and comparing with imagemagick's compare with

compare -metric PSNR fname.png scaled_cv2.png diff_cv2.png
compare -metric PSNR fname.png scaled_matlab.png diff_matlab.png

I get completely different PSNR values What are they doing different?

dodol
  • 1,073
  • 2
  • 16
  • 33
  • 1
    I refer readers to these discussions regarding difference between MATLAB's `imresize` and OpenCV `cv::resize` with the bicubic interpolation: http://stackoverflow.com/q/26812289/97160, http://stackoverflow.com/q/26823140/97160 . It turns out those two implementations use a different value for a free parameter involved in the cubic function... – Amro Nov 11 '14 at 04:56

2 Answers2

9

From Matlab's doc:

'bicubic'

Bicubic interpolation (the default); the output pixel value is a weighted average of pixels in the nearest 4-by-4 neighborhood

And from OpenCV's doc:

INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood

So the only explanation for this is that they use different weighting strategy to get the average value.

From Matlab imresize.m source, you can find that the kernel constant A (see Bicubic interpolation on Wikipedia) is set to -0.5, whereas it is set to -0.75 in OpenCV (see imgproc/src/imgwarp.cpp, function interpolateCubic() on github for instance).

This gives different kernel shapes for the convolution : difference between Matlab (a=-0.5) and OpenCV (a=-0.75) Kernels for bicubic interpolation

Therefore, you will end with slightly different results in the final interpolated image; typically more ringing artifacts and overshoot for OpenCV, but also sharper edges and a better PSNR compared with the "true" underlying high-resolution image.

Community
  • 1
  • 1
herohuyongtao
  • 49,413
  • 29
  • 133
  • 174
  • How those different weighting strategies differ? What does opencv use? I guess that one can perform cubic interpolation quite differently, but what's the catch? Why don't they use the same algorithm (imagemagick, opencv, matlab, pil, etc.)? – dodol Feb 28 '14 at 11:00
  • @Piclem Thanks for your editing to make it clear. :P – herohuyongtao Nov 15 '14 at 06:34
1

It is probably due to different affine transformations from the output pixels to the input pixels. Check this post on 'blinear' counter-intuition example. Besides, in another post, a hypothesis on the interpolation domain ([1,n] vs [0,n]) is verified on Mathematica, also with 'bilinear' method. So I guess it is the similar reason that causes such a difference between Matlab and OpenCV.

Community
  • 1
  • 1
lennon310
  • 12,503
  • 11
  • 43
  • 61