aditya
aditya

Reputation: 165

Creating Image from Pixels stored in an array in Python

import os, sys
from PIL import Image


im = Image.open("result_bw.png")
l = []
print im.size
pix = im.load()
for x in range(im.size[0]):
    for y in range(im.size[1]):
        l.append(pix[x,y])

img = Image.new('L', (im.size[1],im.size[0] ))
img.putdata(l)
img.save('image.png')

The above code reads a black and white image and stores the pixel value in a list.

When I am creating a new image from the pixels stored in the list, I get the original image which is rotated anti-clockwise.

Why am I getting a rotated image?

How can I correct it?

Upvotes: 0

Views: 750

Answers (2)

fuenfundachtzig
fuenfundachtzig

Reputation: 8352

Where there is putdata, there is likely also getdata. Indeed, you could use

l = list(im.getdata())

instead of your for loops. This would also fix the rotation problem.

Upvotes: 0

Dagrooms
Dagrooms

Reputation: 1564

Flip the x and y values you read. Computers write images with an origin in the top-left of a screen, y positive axis pointing down, and x positive axis pointing right. Your implementation assumes an origin at the bottom-left corner.

Upvotes: 1

Related Questions