jarrettHoltz
jarrettHoltz

Reputation: 21

Converting a byte file to an image in python

So I have a byte file output by another program. That byte file contains a single frame of data from a camera output at 640x480 resolution. I want to read that file into python and convert it into an image.

I've been working with pil, but when I try to do this...

   def readimage(path):
      with open(path, "Ur") as f:
        return f.read()

   def main():
    bytes = readimage("color725.txt")
    image = Image.fromstring('RGB', (640,480), bytes)
    image.save("test.bmp")

I get an image that is not the image I'm starting with at all. (looks like nonsense)

When I try to do this...

def readimage(path):
    with open(path, "rb") as f:
        return bytearray(f.read())

def main():
    bytes = readimage("color725.txt")
    image = Image.open(io.BytesIO(bytes))
    image.save("test.bmp")

I get an error "IO Error: cannot identify image file". This isn't a problem with the file being there or not, because it's the image command that throws the error, not trying to open the file.

Those two attempts basically sum up what I've seen from documentation. Anything else I've seen hasn't exactly been applicable. Is there something simple I'm missing, or a better way somehow? Any help in finding an answer to the problem would be appreciated.

First few Lines of the byte file as hex:

1010 1100 1010 1100 1111 1000 1211 1000 1413 1000 1212 1100 1013 1100 0f11 1200 0f11 1200 0f10 1300 0f10 1200 0f10 1200 1013 1300 1011 1400 1014 1500 0f12 1600 0f15 1500 1115 1500 1315 1400 1211 1300 1110 1100 100e 0f00 0f0c 0e00 0f0d 0d00 0f0d 0c00 0e0c 0c00 0e0c 0b00 0d0c 0b00 0c0d 0d00 0e0f 0f00 1010 1100 0e0e 1300 0c0c 0f00 0d0b 0b00 0e0a 0900 0c0a 0800 0b0a 0900 0909 0b00 0808 0900 0707 0800

Upvotes: 2

Views: 6823

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 148870

So it appears that the image should be raw pivel values in a format that could be bgr32. But PIL only know to load images in RGB format. If that's true, you could try to do simple byte manipulation to convert your initial string to RGB

If byte order is really Blue, Green, Red, 0, you could try (starting from your initial code)

bytes = readimage("color725.txt")
RGBbytes = ''.join([ bytes[i+2:i+3] + bytes[i+1:i+2] + bytes[i:i+1]
                   for i in range(0, len(bytes) -1, 4)])
image = Image.fromstring('RGB', (640,480), RGBbytes)

re-ordering bytes to correct RGB order and removing the fourth one.

Upvotes: 3

Related Questions