Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BytesIO object to image

I'm trying to use Pillow in my program to save a bytestring from my camera to a file. Here's an example with a small raw byte string from my camera which should represent a greyscale image of resolution 10x5 pixels, using LSB and 12bit:

import io
from PIL import Image

rawBytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
rawIO = io.BytesIO(rawBytes)
rawIO.seek(0)
byteImg = Image.open(rawIO)
byteImg.save('test.png', 'PNG')

However I get the following error in line 7 (with Image.open):

OSError: cannot identify image file <_io.BytesIO object at 0x00000000041FC9A8>

The docs from Pillow implied this was the way to go.

I tried to apply the solutions from

  • PIL open() method not working with BytesIO
  • PIL cannot identify image file for io.BytesIO object

but can't get it working. Why isn't this working?

like image 201
smiddy84 Avatar asked Aug 25 '15 15:08

smiddy84


1 Answers

I'm not sure what the resulting image should look like (do you have an example?), but if you want to unpack an packed image where each pixel has 12 bits into a 16-bit image, you could use this code:

import io
from PIL import Image

rawbytes = b'_\x00`\x00[\x00^\x00`\x00`\x00\\\x00\\\x00Z\x00\\\x00_\x00[\x00\\\x00\\\x00`\x00]\x00\\\x00^\x00_\x00\\\x00\\\x00]\x00]\x00_\x00]\x00]\x00Z\x00\\\x00^\x00\\\x00Z\x00^\x00_\x00]\x00^\x00Z\x00\\\x00Z\x00\\\x00]\x00_\x00]\x00^\x00Z\x00[\x00[\x00X\x00]\x00]\x00Z\x00'
im = Image.frombuffer("I;16", (5, 10), rawbytes, "raw", "I;12")
im.show()
like image 126
Michiel Overtoom Avatar answered Oct 14 '22 01:10

Michiel Overtoom