Python Forum

Full Version: Invert Pillow image colours
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi guys!

I've been trying to invert the pixel colours of an image of Harry Potter for about 2 days now. I have a list of RGB tuples that make up each pixel of the image. I want to convert each of those tuples to a list so I can edit them. I've tried list comprehension and it didn't work. I've tried mapping and it didn't work either. I also tried this:

from PIL import Image
import PIL.ImageOps    

image = Image.open('your_image.png')

inverted_image = PIL.ImageOps.invert(image)

inverted_image.save('new_name.png')
And that didn't work.

This is my code:

from PIL import Image  
import numpy as np

im = Image.open('harrypotter.png')

pixels = list(im.getdata())
width, height = im.size
pixels = [pixels[i * width:(i + 1) * width] for i in range(height)]

pixels_list = list(pixels)

for i in range(0, len(pixels_list)):
    for k in range(0, len(pixels_list[i][i])):
        pixels_list[i][i][k] = pixels_list[i][i][k] - (pixels_list[i][i][k] * 2)

array = np.array(pixels_list, dtype = np.uint8)

new_image = Image.fromarray(array)
new_image.show()
I would be grateful if anyone could help
This appears to work
#! /usr/bin/env python3

# Do the imports
from PIL import Image
from PIL import ImageOps

image = Image.open('/home/johnny/Desktop/start.jpg')

if image.mode == 'RGBA':
    r,g,b,a = image.split()
    rgb_image = Image.merge('RGB', (r,g,b))

    inverted_image = ImageOps.invert(rgb_image)

    r2, g2, b2 = inverted_image.split()

    final_transparent_image = Image.merge('RGBA', (r2, g2, b2, a))

    final_transparent_image.save('/home/johnny/Desktop/new.png')
else:
    inverted_image = ImageOps.invert(image)
    inverted_image.save('/home/johnny/Desktop/new.png')
Before and After
[attachment=923][attachment=924]
Quote:
from PIL import Image
import PIL.ImageOps    

image = Image.open('your_image.png')

inverted_image = PIL.ImageOps.invert(image)

inverted_image.save('new_name.png')
And that didn't work.
What did not work?
If i use image from @menator01 the result will be just the same as he has posted.
from PIL import Image
import PIL.ImageOps

image = Image.open('start.jpg')
inverted_image = PIL.ImageOps.invert(image)
inverted_image.save('start_fin.png')
It didn't work for me. It said it doesn't work for this type of image. And I want it to work with all of them. PNG, JPG, you name it. So, I want to do it my way with the pixel tuples. How do I convert ta list of tuples to a list of lists without list comprehension or mapping?
I had a typo in the code I posted but corrected it. I know you said you want to use numpy but, it will convert both png and jpg

[attachment=925][attachment=926]
ok.......