Omar Shehab Omar Shehab - 6 months ago 17
Python Question

Python Imaging Library makes an image reddish

I have opened a grayscale image using the Python Imaging Library, copied every pixel value into another image variable of same size and saved it. Now when I open the new image with an image viewer it looks reddish. I have used the Image.new() method with and without the "white" and "black" arguments got the same reddish output.

My code:

from PIL import Image
import math

def run():
im = Image.open("hrabowski.jpg")
pix = im.load()
print im.size
# print pix[0, 1]

im2 = Image.new("RGB", (2400, 2400))

for i in range(im.size[0]):
for j in range(im.size[0]):
im2.putpixel((i, j), pix[i, j])

im2.save("hrabowski-2400-2400.jpg")


Original image (scaled down to 500 x 500):

enter image description here

Python output of my code (scaled down to 500 x 500):

enter image description here

Could anyone please tell me what I am doing wrong?

tfv tfv
Answer

Your problem is that you want to create an RGB image which has three channels. Therefore one pixel value consists of three values and not only one (in your case use the gray value of the original image for each of the channels).

I have modified the code accordingly.

A side remark: I am almost sure that there is a better way to do what you want to achieve, there is usually no need to loop through single pixels, but I am not sure what you are after.

from PIL import Image
import math

def run():
    im = Image.open("ZHiG0.jpg")
    pix = im.load()
    print im.size
    # print pix[0, 1]

    im2 = Image.new("RGB", (2400, 2400))

    for i in range(im.size[0]):
        for j in range(im.size[0]):
            im2.putpixel((i, j), (pix[i, j],pix[i, j],pix[i, j]))

    im2.save("ZHiG0-2400-2400.jpg")
run()
Comments