How to invert or negate the colors in an image using Python

Color inversion (also known as negation) is a great way to spice up your image editing options, providing a nicely stylized look. Perfect for making bad memes, for example. We have a couple ways to approach this task. We can try to mess around with color values to make it from scratch, probably taking a few hours. Or we can use an API function that is already designed for just this task.

Let’s use pip installer for our client setup, as seen here:

pip install cloudmersive-image-api-client

Now we can call edit_invert:

from __future__ import print_functionimport timeimport cloudmersive_image_api_clientfrom cloudmersive_image_api_client.rest import ApiExceptionfrom pprint import pprint# Configure API key authorization: Apikeyconfiguration = cloudmersive_image_api_client.Configuration()configuration.api_key['Apikey'] = 'YOUR_API_KEY'# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed# configuration.api_key_prefix['Apikey'] = 'Bearer'# create an instance of the API classapi_instance = cloudmersive_image_api_client.EditApi(cloudmersive_image_api_client.ApiClient(configuration))image_file = '/path/to/file' # file | Image file to perform the operation on.  Common file formats such as PNG, JPEG are supported.try:# Invert, negate the colors in the imageapi_response = api_instance.edit_invert(image_file)pprint(api_response)except ApiException as e:print("Exception when calling EditApi->edit_invert: %s\n" % e)

So now we can just input our file and then wait around leisurely while our negated image is created. Usually just takes a few seconds for our returned image URL for convenient download. Done!

Image for post
Image for post

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store