Negative transformation of an image using Python and OpenCV
Last Updated :
03 Jan, 2023
Image is also known as a set of pixels. When we store an image in computers or digitally, it’s corresponding pixel values are stored. So, when we read an image to a variable using OpenCV in Python, the variable stores the pixel values of the image. When we try to negatively transform an image, the brightest areas are transformed into the darkest and the darkest areas are transformed into the brightest.
As we know, a color image stores 3 different channels. They are red, green and blue. That’s why color images are also known as RGB images. So, if we need a negative transformation of an image then we need to invert these 3 channels.
Let’s see 3 channels of a color image by plotting it in the histogram.
Input Image -
Python3 1==
# We need cv2 module for image
# reading and matplotlib module
# for plotting
import cv2
import matplotlib.pyplot as plt
img_bgr = cv2.imread('scenary.jpg', 1)
color = ('b', 'g', 'r')
for i, col in enumerate(color):
histr = cv2.calcHist([img_bgr], [i], None, [256], [0, 256])
plt.plot(histr, color = col)
plt.xlim([0, 256])
plt.show()
Output:

Here, the 3 channels (Red, Green, Blue) are overlapped and create a single histogram. If you have studied about pixels and RGB before, you may know that each color contains 256 values. If RGB value of a color is (255, 255, 255) then that color is shown as white and If RGB value of a color is (0, 0, 0) then that color is shown as black. Like that, the above 3 channels also contain 256 numbers of pixels.
So, X-axis shows a total of 256 values (0 - 255) and Y-axis shows the total frequencies of each channel. As you can see in the histogram, the blue channel has the highest frequency and you can easily mark the amount of blue color present in the image by looking at it.
Negative transformation of the image
Let’s create a negative transformation of the image. There 2 different ways to transform an image to negative using the OpenCV module. The first method explains negative transformation step by step and the second method explains negative transformation of an image in single line.
First method: Steps for negative transformation
- Read an image
- Get height and width of the image
- Each pixel contains 3 channels. So, take a pixel value and collect 3 channels in 3 different variables.
- Negate 3 pixels values from 255 and store them again in pixel used before.
- Do it for all pixel values present in image.
Python code for 1st method: -
Python3 1==
import cv2
import matplotlib.pyplot as plt
# Read an image
img_bgr = cv2.imread('scenary.jpg', 1)
plt.imshow(img_bgr)
plt.show()
# Histogram plotting of the image
color = ('b', 'g', 'r')
for i, col in enumerate(color):
histr = cv2.calcHist([img_bgr],
[i], None,
[256],
[0, 256])
plt.plot(histr, color = col)
# Limit X - axis to 256
plt.xlim([0, 256])
plt.show()
# get height and width of the image
height, width, _ = img_bgr.shape
for i in range(0, height - 1):
for j in range(0, width - 1):
# Get the pixel value
pixel = img_bgr[i, j]
# Negate each channel by
# subtracting it from 255
# 1st index contains red pixel
pixel[0] = 255 - pixel[0]
# 2nd index contains green pixel
pixel[1] = 255 - pixel[1]
# 3rd index contains blue pixel
pixel[2] = 255 - pixel[2]
# Store new values in the pixel
img_bgr[i, j] = pixel
# Display the negative transformed image
plt.imshow(img_bgr)
plt.show()
# Histogram plotting of the
# negative transformed image
color = ('b', 'g', 'r')
for i, col in enumerate(color):
histr = cv2.calcHist([img_bgr],
[i], None,
[256],
[0, 256])
plt.plot(histr, color = col)
plt.xlim([0, 256])
plt.show()
Output :

(Original image and it’s histogram)

(Negative image and it’s histogram)
2nd method: Steps for negative transformation
- Read an image and store it in a variable.
- Subtract the variable from 1 and store the value in another variable.
- All done. You successfully done the negative transformation.
Python code for 2nd method: -
Python3 1==
import cv2
import matplotlib.pyplot as plt
# Read an image
img_bgr = cv2.imread('scenary.jpg', 1)
plt.imshow(img_bgr)
plt.show()
# Histogram plotting of original image
color = ('b', 'g', 'r')
for i, col in enumerate(color):
histr = cv2.calcHist([img_bgr],
[i], None,
[256],
[0, 256])
plt.plot(histr, color = col)
# Limit X - axis to 256
plt.xlim([0, 256])
plt.show()
# Negate the original image
img_neg = 1 - img_bgr
plt.imshow(img_neg)
plt.show()
# Histogram plotting of
# negative transformed image
color = ('b', 'g', 'r')
for i, col in enumerate(color):
histr = cv2.calcHist([img_neg],
[i], None,
[256],
[0, 256])
plt.plot(histr, color = col)
plt.xlim([0, 256])
plt.show()
Output :

(Original image and it’s histogram)

(Negative image and it’s histogram)
Similar Reads
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read