Search code examples
pythonimagegdal

How to read .img files in python?


I have an image in format .img and I want to open it in python. How can I do it?

I have an interference pattern in *.img format and I need to process it. I tried to open it using GDAL, but I have an error:

ERROR 4: `frame_064_0000.img' not recognized as a supported file format.

Solution

  • If your image is 1,024 x 1,024 pixels, that would make 1048576 bytes, if the data are 8-bit. But your file is 2097268 bytes, which is just a bit more than double the expected size, so I guessed your data are 16-bit, i.e. 2 bytes per pixel. That means there are 2097268-(2*1024*1024), i.e. 116 bytes of other junk in the file. Folks normally store that extra stuff at the start of the file. So, I just took the last 2097152 bytes of your file and assumed that was a 16-bit greyscale image at 1024x1024.

    You can do it at the command-line in Terminal with ImageMagick like this:

    magick -depth 16 -size 1024x1024+116 gray:frame_064_0000.img -auto-level result.png
    

    enter image description here

    In Python, you could open the file, seek backwards 2097152 bytes from the end of the file and read that into a 1024x1024 np.array of uint16.

    That will look something like this:

    import numpy as np
    from PIL import Image
    
    filename = 'frame_064_0000.img' 
    
    # set width and height 
    w, h = 1024, 1024 
    
    with open(filename, 'rb') as f: 
        # Seek backwards from end of file by 2 bytes per pixel 
        f.seek(-w*h*2, 2) 
        img = np.fromfile(f, dtype=np.uint16).reshape((h,w)) 
    
    # Save as PNG, and retain 16-bit resolution
    Image.fromarray(img).save('result.png')
    
    # Alternative to line above - save as JPEG, but lose 16-bit resolution
    Image.fromarray((img>>8).astype(np.uint8)).save('result.jpg')