![]() |
VOOZH | about |
Color Inversion (Image Negative) is the method of inverting pixel values of an image. Image inversion does not depend on the color mode of the image, i.e. inversion works on channel level. When inversion is used on a multi color image (RGB, CMYK etc) then each channel is treated separately, and the final result if formed by calibrating the results of all the channels.
We would be using pillow (PIL) library for obtaining negative of an image. To install the library, execute the following command in the command-line:-
pip install pillow
Note: Several Linux distributions tend to have Python and PIL preinstalled into them.
In this article, 2 methods have been described for inverting color space of an image. The first one is an inbuilt method using ImageChops.invert() function. In the second one we would be inverting the image by elementwise subtraction of pixel values.
Sample Image -
Method #1:
Using inbuilt method ImageChops.invert() for Negating color.
Output:
Explanation:
Firstly we import the ImageChops module for using invert() method. Then we open the test image (test.jpg), and save it's image object. Now we passed that image object to ImageDraw.invert() which returns the inverted image. At last, we displayed the color inverted image.
Things to keep in mind while using ImageChops.invert():
Method #2:
The method used for getting the inverse of an image is subtraction of the maximum value/intensity of a pixel by the value of current pixel. The resultant value is guided by the formula -
👁 formualt for inverting an image
Where INV is the resultant inverted pixel, I^MAX is the maximum intensity level in a given color mode and I(x, y) is the intensity (pixel value) of image/color channel at a particular pair of coordinates.
Output:
Explanation:
Firstly we import numpy into our code, as numpy allows fast elementwise operations on matrices and offers several arithmetic operations on arrays. Then we open the test image using Image.open(), and store the returned image object in the variable img. Then we create an array (img_arry) from the pixel values obtained from the opened image object (img). This is done so as to allow elementwise subtraction operation offered by the numpy library. Now we subtract 255 from each channel/pixel value, this results in all the pixel values being inverted. Now, we use this resultant matrix to create an new image (inverted_img). Finally we saved the image, under the name of Image_negative.jpg.