3

The Image array

[[2, 2, 2, 2],
[2, 3, 3, 3],  
[2, 4, 4, 4],              
[5, 5, 5, 5]]

h = 4, w = 4 use cv2.resize(img,(h//2,w//2)), the result is

[[2, 3],
[4, 5]]

The reduction factor is 2, when I calculate manually,

newImage(0,0) -> oldImage(2*0,2*0) = oldImage(0,0) = 2 
newImage(0,1) -> oldImage(2*0,2*1) = oldImage(0,2) = 2
newImage(1,0) -> oldImage(2*1,2*0) = oldImage(2,0) = 2
newImage(1,1) -> oldImage(2*1,2*1) = oldImage(2,2) = 4

The result of my manual calculation should be:

[[2, 2],
[2, 4]]

I think my logic is not wrong ah, why would there be a difference with the opencv calculation it

1 Answers1

3

When resizing an image there are several interpolation methods. You select it with the interpolation parameter of cv2.resize. This method determine how to calculate value for the new pixels based on the old ones.

The method which behaves similarly to the one you implemented manually is cv.INTER_NEAREST. For each destination pixel, it will select the source pixel closest to it and simply copy it's value, and the result will be like in your "manual" resize:

img2 = cv2.resize(img, (h//2, w//2), interpolation=cv2.INTER_NEAREST)

Other interpolation methods like cv2.INTER_LINEAR, cv.INTER_CUBIC etc. perform a more sophisticated calculation, possibly taking into account several source pixels in the neighborhood of the destination pixel.

The default method in case you don't specify the interpolation parameter (like in your code above) is cv2.INTER_LINEAR (not cv2.INTER_NEAREST). This explains your result. You can set the interpolation parameter to different values and experiment.

See the documentation for cv2.resize: cv.resize, and the list of interpolation methods:InterpolationFlags.

There are some rules of thumb which interpolation method performs the best for different scenarios. See here: Which kind of interpolation best for resizing image?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39