14

I'm transferring a MATLAB code into python and trying to downscale an image using OpenCV function cv2.resize, But I get a different results from what MATLAB outputs.

To make sure that my code is not doing anything wrong before the resize, I used a small example on both functions and compared the output.

I first created the following array in both Python and MATLAB and upsampled it:

Python - NumPy and OpenCV

    x = cv2.resize(np.array([[1.,2],[3,4]]),(4,4), interpolation=cv2.INTER_LINEAR)
    print x

    [[ 1.    1.25  1.75  2.  ]
     [ 1.5   1.75  2.25  2.5 ]
     [ 2.5   2.75  3.25  3.5 ]
     [ 3.    3.25  3.75  4.  ]]

MATLAB

    x = imresize([1,2;3,4],[4,4],'bilinear')

    ans =

    1.0000    1.2500    1.7500    2.0000
    1.5000    1.7500    2.2500    2.5000
    2.5000    2.7500    3.2500    3.5000
    3.0000    3.2500    3.7500    4.0000

Then I took the answers and resized them back to the original 2x2 size.

Python:

    cv2.resize(x,(2,2), interpolation=cv2.INTER_LINEAR)

    ans = 

     [[ 1.375,  2.125],
      [ 2.875,  3.625]]

MATLAB:

    imresize(x,[2,2],'bilinear')

    ans =

      1.5625    2.1875
      2.8125    3.4375

They are clearly not the same, and when numbers are larger, the answers are a lot more different.

Any explanation or resources would be appreciated.

1 Answer 1

15

MATLAB's imresize has anti-aliasing enabled by default:

>> imresize(x,[2,2],'bilinear')
ans =
    1.5625    2.1875
    2.8125    3.4375
>> imresize(x,[2,2],'bilinear','AntiAliasing',false)
ans =
    1.3750    2.1250
    2.8750    3.6250

This has tripped me up in the past, while trying to reproduce the results of imresize using just interp2.

2
  • 1
    +1 Thank you! That is exactly what i was looking for. I have been using this function for many years, and never thought about turning off the anti-aliasing. Do you know if there is a way to do such down-sampling in python that does have anti-aliasing instead of implementing it?
    – mxy
    Feb 24, 2014 at 23:04
  • 1
    @mxy I'm afraid not. Perhaps you can first convolve with a Gaussian or other low pass filter prior to resize/resample.
    – chappjc
    Feb 24, 2014 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.