Search code examples
pythonpython-3.ximagescipyzooming

Why scipy.ndimage zoom add new channel?


I was surprised when i found that python scipy.ndimage.zoom automatically add new channel when the zoom is performed:

from scipy.misc import imread
from scipy.ndimage import zoom
img = imread('lena.jpg')
img=imread('lena.jpg')
img.shape
(468, 792, 3)
x = zoom(img, 1.0)
x.shape
(468, 792, 3)
x = zoom(img, 1.5)
x.shape
(702, 1188, 4)
x = zoom(img, 2)
x.shape
(936, 1584, 6)

The width, height dimension are correct, i was not able to understand from where came from the other dimensions.

This strange behavior manifests only for colored image:

x = zoom(img[:, :, 0], 2)
x.shape
(936, 1584)

Solution

  • ndimage.zoom knows nothing about channels (or images). It operates with an n-dimensional array. If you give an array with shape (9, 5, 3) and ask to zoom it with the factor of 2, it will produce an array with shape (9*2, 5*2, 3*2) which is (18, 10, 6).

    Of course this is not what you want when the third axis is the color channel. Use per-axis zoom, setting the zoom for the last axis to 1:

    zoom(img, (2, 2, 1))