Search code examples
pythonbinarypython-imaging-library

How can I read a binary file and turn that data into an rgb image?


I've got a .bin file. The data inside has has bit depth of 8, expecting RGB888 format, meaning 8 bits per channel. I'd like to reconstruct it as a.png file with its color intact.

I saw/tried working with this top answer: Link

When I tried running the above, my original image that was captured appears zoomed in. I can only ever get the full content of the original image captured when I multiply the count variable by 3 (count=w*h*3). Of course, I then have the width parameter multiplied by 3 too to match. Obviously, this is wrong in the sense that it results in a very large image. Furthermore, I still have my reconstructed image in grayscale.

As such, I want to know how I can take my .bin file and reconstruct it into a colored .png file.


Solution

  • Your code should look like this - be sure you have height and width set correctly:

    #!/usr/bin/env python3
    
    import numpy as np
    from PIL import Image
    
    # Define width and height
    w, h = 5496, 3672
    
    # Read file using numpy "fromfile()"
    d = np.fromfile("YOURFILE.BIN",dtype=np.uint8,count=w*h*3).reshape(h,w,3)
    
    # Make into PIL Image and save
    PILimage = Image.fromarray(d)
    PILimage.save('result.png')