Search code examples
pythongisrasterio

How to resize a large array and store it as a grayscale image?


For the beginning, may I provide a little bit of context. Having a large NDVI array, I would like to save it as jpg image in order to set a pydeck bitmap layer.

The source array, visualized using rasterio looks as follows:

import rasterio
fp = 'data/ndvi/index_ndvi.tif'
img = rasterio.open(fp)
show(img)

enter image description here

vals = img.read(1)
# normalize values
vals = ((vals - np.min(vals))/(np.max(vals) - np.min(vals)) * 255).astype('uint8')
vals.shape
>> (19204, 21063)

I tried to resize the array as follows:

from skimage.transform import resize
img_target_width = 1024
img_target_height = int((img_target_width/vals.shape[0]) * vals.shape[1]
img_resized = resize(np.expand_dims(vals, axis=0), (img_target_width, img_target_height)

The code above however causes the computer to freeze.

I would be thankful if anyone suggested a feasible way to resize a large array of values and store it as an image.


Solution

  • Using opencv you can do this efficiently.

    import cv2
    img_resized = cv2.resize(vals, (img_target_width, img_target_height))
    cv2.imwrite('resized.jpg', img_resized) #save as jpg
    
    >>> Original size: (13345, 17262)
    >>> Resized size: (1324, 1024)
    >>> Elapsed time: 3.97 seconds