Shahzad
Shahzad

Reputation: 2049

Displaying image from image raw data

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

Upvotes: 2

Views: 4366

Answers (2)

martineau
martineau

Reputation: 123541

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()

Upvotes: 2

phoebus
phoebus

Reputation: 14941

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().

Upvotes: 0

Related Questions