Search code examples
pythonnumpyimage-processingmatplotlibimagej

Opening raw images on Python resulting in a different image compared to ImageJ


I wrote this script to open a raw image and do some processing.

import numpy as np 
import matplotlib.pyplot as plt
PATH = "C:\Users\Documents\script_testing_folder\\"
IMAGE_PATH = PATH +"simulation01\\15x15_output_det_00001_raw_df_00000.bin"
raw_image = np.fromfile(IMAGE_PATH, dtype=np.uint64)
raw_image.shape = (15,15)
plt.imshow(raw_image,cmap = 'gray')
total_intensity = ndimage.sum(raw_image)
print total_intensity
plt.show()

Using this script I get an Image such as this: enter image description here

In contrast... when I open the same image on ImageJ(file>import>raw (64bit real, 15x15 length and width)) I have this:

enter image description here

I have tried looking around, but I am not sure where I am going wrong when trying to reproduce the same image on python. Any help would be greatly appreciated.

Additionally when I sum the intensity in the image using:

total_intensity = ndimage.sum(raw_image)
print total_intensity

y I get 4200794456581938015, whereas, on ImageJ I get 0.585.

I am not sure where I am going wrong on these steps...

Thanks !

Edit: The original file if anyone wants to reproduce the results I got https://www.dropbox.com/s/po82z4uf2ku7k0e/15x15_output_det_00001_raw_df_00000.bin?dl=0


Solution

  • The problem is the endianness of your data (the order of the single bytes of a 64bit float). Fortunately, numpy has the functionality to solve this issue:

    import numpy as np 
    import matplotlib.pyplot as plt
    
    # load the image
    raw_image = np.fromfile('15x15_output_det_00001_raw_df_00000.bin')
    raw_image = np.reshape(raw_image, (15, 15))
    
    # swap the byte order
    raw_image = raw_image.byteswap()
    
    # output the sum of the intensities to check
    total_intensity = np.sum(raw_image)
    print "total intensity:", total_intensity
    
    # plot the image
    plt.imshow(raw_image,cmap = 'gray', interpolation='nearest')
    plt.show()
    

    Output:

    total intensity: 0.585123878711

    Result: enter image description here