Zoom in an Image using python-numpy

18,743

The clipped_zoom function you're using from my previous answer was written for single-channel images only.

At the moment it's applying the same zoom factor to the "color" dimension as well as the width and height dimensions of your input array. The ValueError occurs because the the out array is initialized to the same number of channels as the input, but the result of zoom has fewer channels because of the zoom factor.

To make it work for multichannel images you could either pass each color channel separately to clipped_zoom and concatenate the results, or you could pass a tuple rather than a scalar as the zoom_factor argument to scipy.ndimage.zoom.

I've updated my previous answer using the latter approach, so that it will now work for multichannel images as well as monochrome.

Share:
18,743
Abhi
Author by

Abhi

Software Development Engineer - R&D

Updated on June 04, 2022

Comments

  • Abhi
    Abhi almost 2 years

    I'm trying to zoom in an image.

     import numpy as np
     from scipy.ndimage.interpolation import zoom
     import Image 
     zoom_factor = 0.05 # 5% of the original image 
     img = Image.open(filename)
     image_array = misc.fromimage(img)
     zoomed_img = clipped_zoom(image_array, zoom_factor)
     misc.imsave('output.png', zoomed_img)
    

    Clipped Zoom Reference:
    Scipy rotate and zoom an image without changing its dimensions

    This doesn't works and throws this error: ValueError: could not broadcast input array from shape

    Any Help or Suggestions on this Is there a way to zoom an image given a zoom factor. And what's the problem ?

    Traceback:

    Traceback (most recent call last):
      File "/usr/local/lib/python2.7/dist-packages/tornado/web.py", line 1443, in _execute
        result = method(*self.path_args, **self.path_kwargs)
      File "title_apis_proxy.py", line 798, in get
        image, msg = resize_image(image_local_file, aspect_ratio, image_url, scheme, radius, sigma)
      File "title_apis_proxy.py", line 722, in resize_image
        z = clipped_zoom(face, 0.5, order=0)
      File "title_apis_proxy.py", line 745, in clipped_zoom
        out[top:top+zh, left:left+zw] = zoom(img, zoom_factor, **kwargs)
    ValueError: could not broadcast input array from shape (963,1291,2) into shape (963,1291,3)
    
  • Abhi
    Abhi over 7 years
    Great it works fine, but sometimes it shows a warning serWarning: From scipy 0.13.0, the output shape of zoom() is calculated with round() instead of int() - for these inputs the size of the returned array has changed. "the returned array has changed.", UserWarning) . Should I ignore this ?
  • ali_m
    ali_m over 7 years
    You should be fine, since my code also uses np.round to compute the dimensions of the output. By the way, scipy 0.13.0 came out ~3 years ago, so you might consider updating.