Anirban Dutta
Anirban Dutta

Reputation: 195

How to resize an image faster in python

I have an image i.e an array of pixel values, lets say 5000x5000 (this is the typical size). Now I want to expand it by 2 times to 10kx10k. The value of (0,0) pixel value goes to (0,0), (0,1), (1,0), (1,1) in the expanded image.

After that I am rotating the expanded image using scipy.interpolate.rotate (I believe there is no faster way than this given the size of my array)

Next I have to again resize this 10kx10k array to original size i.e. 5kx5k. To do this I have to take the average pixel values of (0,0), (0,1), (1,0), (1,1) in the expanded image and put them in (0,0) of the new image.

However it turns out that this whole thing is an expensive procedure an takes a lot of time given the size of my array. Is there a faster way to do it? I am using the following code to expand the original image

#Assume the original image is already given
largeImg=np.zeros((10000,10000), dtype=np.float32)
for j in range(5000):
    for k in range(5000):
          pixel_value=original_img[j][k]
          for x in range((2*k), (2*(k+1))):
                for y in range((2*j), (2*(j+1))):
                    largeImg[y][x] = pixel_value

A similar method is used to reduce the image to original size after rotation.

Upvotes: 1

Views: 2529

Answers (2)

Paul Panzer
Paul Panzer

Reputation: 53029

In numpy you can use repeat:

large_img = original_img.repeat(2, axis=1).repeat(2, axis=0)

and

final_img = 0.25 * rotated_img.reshape(5000,2,5000,2).sum(axis=(3,1))

or use scipy.ndimage.zoom. this can give you smoother results than the numpy methods.

Upvotes: 5

mistakeNot
mistakeNot

Reputation: 783

there is a nice library that probably has all the functions you need for handling images, including rotate:

http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.rotate

Upvotes: 0

Related Questions