6

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

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

Community
  • 1
  • 1
smiddy84
  • 285
  • 1
  • 4
  • 13

1 Answers1

5

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()
Michiel Overtoom
  • 1,609
  • 13
  • 14
  • Thanks for the tip! In my case, the output was a Windows WORD type (so 16-bit little endian unsigned integer). In the end, having a look at the [decoder description](http://pillow.readthedocs.org/en/latest/handbook/writing-your-own-file-decoder.html?highlight=unsigned#decoding-floating-point-data), I was able to decode my image correctly: `Image.frombuffer("F", (10, 5), rawbytes, "raw", "F;16")` – smiddy84 Aug 26 '15 at 08:34
  • I'm glad the frombuffer() function did for you what you required, and that my suggestion put you on the right track. I did have to delve into the pillow source code to find this solution, however ;-) – Michiel Overtoom Aug 26 '15 at 19:50