imageimage-processingfile-typeunsigned-char

How to read an Unsigned Char image file to Python?


I have an text file called with the extension '.image', at the top of the file is the following:

Image Type: unsigned char
Dimension: 2
Image Size: 512 512
Image Spacing: 1 1
Image Increment: 1 1
Image Axis Labels: "" "" 
Image Intensity Label: ""
193

I believe this to be an unsigned char file, but i'm having a hard time opening it in python (and saving it as a jpg, png etc)

Have tried the standard PIL.Image.open(), saving as a string and reading with Image.fromstring('RGB', (512,512), string), and reading as byte-like object Image.open(io.BytesIO(filepath))

Any ideas? Thanks in advance


Solution

  • If we assume there is some arbitrary, unknown length header on the file, we can read the entire file and then rather than parsing the header, just take the final 512x512 bytes from the tail of the file:

    #!/usr/bin/env python3
    
    from PIL import Image
    import pathlib
    
    # Slurp the entire contents of the file
    f = pathlib.Path('image.raw').read_bytes()
    
    # Specify height and width
    h, w = 512, 512
    
    # Take final h*w bytes from the tail of the file and treat as greyscale values, i.e. mode='L'
    im = Image.frombuffer('L', (w,h), f[-(h*w):], "raw", 'L', 0, 1)
    
    # Save to disk
    im.save('result.png')
    

    Or, if you prefer Numpy to Pathlib:

    #!/usr/bin/env python3
    
    from PIL import Image
    import numpy as np
    
    # Specify height and width
    h, w = 512, 512
    
    # Slurp entire file into Numpy array, take final 512x512 bytes, and reshape to 512x512
    na = np.fromfile('image.raw', dtype=np.uint8)[-(h*w):].reshape((h,w))
    
    # Make Numpy array into PIL Image and save
    Image.fromarray(na).save('result.png')
    

    Or, if you don't really fancy writing any Python, just use tail in Terminal to slice the last 512x512 bytes off your file and tell ImageMagick to make an 8-bit PNG from the grayscale byte values:

    tail -c $((512*512)) image.raw | magick -depth 8 -size 512x512  gray:- result.png