2

After reading pixel values from the image using the following code:

import os, sys
import Image

pngfile = Image.open('input.png')
raw = list (pngfile.getdata())

f = open ('output.data', 'w')
for q in raw:
    f.write (str (q) + '\n')
f.close ()

How one can display an image after reading the data stored in raw form? Is there any opposite function of getdata() to achieve this?

enter image description here

Shahzad
  • 1,999
  • 6
  • 35
  • 44

2 Answers2

2

I'm not exactly sure what you want to accomplish by doing this, but here's a working example of saving the raw image pixel data into a file, reading it back, and then creating anImageobject out of it again.

It's important to note that for compressed image file types, this conversion will expand the amount of memory required to hold the image data since it effectively decompresses it.

from PIL import Image

png_image = Image.open('input.png')
saved_mode = png_image.mode
saved_size = png_image.size

# write string containing pixel data to file
with open('output.data', 'wb') as outf:
    outf.write(png_image.tostring())

# read that pixel data string back in from the file
with open('output.data', 'rb') as inf:
    data = inf.read()

# convert string back into Image and display it
im = Image.fromstring(saved_mode, saved_size, data)
im.show()
martineau
  • 119,623
  • 25
  • 170
  • 301
  • I am getting the following error with the above code. Traceback (most recent call last): File "display_image.py", line 11, in raw = bytearray(itertools.chain.from_iterable(png_image.getdata())) TypeError: 'int' object is not iterable – Shahzad Nov 14 '13 at 05:59
  • The only thing I can think of is that perhaps the type of image is factor. The code in my answer worked for a 24-bit RGB .png image. Could you add the image (or a link to it) that you're using to your question? – martineau Nov 14 '13 at 09:31
  • I have added the image. – Shahzad Nov 14 '13 at 15:26
  • The problem you encountered was because your test image was gray-scale and mine was RGB color. I believe I figured-out a simpler technique using a different `image` module function that should also be able to handle different image file types and have updated my answer accordingly. – martineau Nov 14 '13 at 17:37
0

For this you need a GUI toolkit, or you need to use already existing image display applications.

This existing SO question has answers discussing using Image.show() and other methods.

To go from raw data to image, check out Image.frombuffer().

Community
  • 1
  • 1
phoebus
  • 14,673
  • 2
  • 33
  • 35
  • If you want to use Image.show(), then is it possible that we can create Image object from the raw data file? – Shahzad Nov 13 '13 at 23:33