Reputation: 2339
def desaturate_image(self, image):
desatimage = Image.new(image.mode, image.size)
pixellist = []
print(len(pixellist))
for x in range(image.size[0]):
for y in range(image.size[1]):
r, g, b = image.getpixel((x, y))
greyvalue = (r+g+b)/3
greypixel = (int(round(greyvalue)), int(round(greyvalue)), int(round(greyvalue)))
pixellist.append(greypixel)
print(pixellist)
desatimage.putdata(pixellist)
return desatimage
I'm writing a python method to convert the image passed as parameter to greyscale. The result I get is though, not right. Here's the input and output. Where is it wrong?
Upvotes: 1
Views: 130
Reputation: 29690
You are iterating over the pixels with the wrong dimension first - Pillow images are column-major order. So you want
...
for y in range(image.size[1]):
for x in range(image.size[0]):
...
such that your pixel list stores the pixels column-wise.
This gives you
Of course, you could just use the .convert
method to get a greyscale representation more easily, which uses the transform mentioned in the docs.
image.convert('L')
As abarnert mentioned below, this gives you an image actually in greyscale mode ('L'
) as opposed to your current answer that keeps the image in RGB mode ('RGB'
) with triply repeated data.
Upvotes: 2