Search code examples
python-3.xnumpyimage-processingpython-imaging-libraryscikit-image

Resize grayscale image by summing pixel intensities for every 2x2 grid


I have a dataset of 36,000 tif images (grayscale, 16-bit) each of size 2048 x 2048 pixels. I want to resize them to 1024 x 1024 pixels by adding the intensities at each 2x2 grid to generate the intensity at each pixel in the resized image. I need to do this in Python. I have been doing this using ImageJ with Image>Transform>Bin, method = Sum. I cannot find a Python library which does this. Any help is appreciated. Thank you.


Solution

  • block_reduce from skimage_measure worked for me. Here's the code snippet:

    import numpy as np
    from skimage.measure import block_reduce
    import skimage.io as tiffio
    
    #read original 2k x 2k image
    original_image = tiffio.imread(read_path+"/RawImage_00000.tif", plugin = 'tifffile')
    #bin image by factor of 2 along both axes, summing pixel values in 2x2 blocks
    sum2bin_image = block_reduce(original_image, block_size=(2, 2), func=np.sum)
    #Numpy arrays are 64-bit float variables, so the following step restores the original unsigned 16-bit format
    sum2bin_image = np.round(sum2bin_image).astype(np.uint16)
    #save generated image
    tiffio.imsave(save_path+'/'+'sum2bin_00000.tif', sum2bin_image, plugin='tifffile')