In this post we will be creating a Python script that will invert the colours within an existing image, to do this we will be using the Python Imaging Library also known as PIL enabling us to image processing capabilities.
See the sample of Python code below where we utilise the PIL library to invert the colours within an existing image and save the image as a new file. To help us achieve this we utilise the ‘ImageOps’ module in particular the ‘ImageOps.invert()’ which inverts any given image.
from PIL import Image, ImageOps img=Image.open('image.png') img=ImageOps.invert(img) img.save('inverted_image.png')
See our example image below before being inverted.
See our image below with the colours inverted.
Take a look at some of our other content around the Python programming language by clicking here.