The Wayback Machine - https://web.archive.org/web/20240731061639/https://www.geeksforgeeks.org/python-grayscaling-of-images-using-opencv/
Open In App

Python | Grayscaling of Images using OpenCV

Last Updated : 30 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Grayscaling is the process of converting an image from other color spaces e.g. RGB, CMYK, HSV, etc. to shades of gray. It varies between complete black and complete white.

Importance of grayscaling 

  • Dimension reduction: For example, In RGB images there are three color channels and three dimensions while grayscale images are single-dimensional.
  • Reduces model complexity: Consider training neural articles on RGB images of 10x10x3 pixels. The input layer will have 300 input nodes. On the other hand, the same neural network will need only 100 input nodes for grayscale images.
  • For other algorithms to work: Many algorithms are customized to work only on grayscale images e.g. Canny edge detection function pre-implemented in the OpenCV library works on Grayscale images only.

Let’s learn the different image processing methods to convert a colored image into a grayscale image.

Method 1: Using the cv2.cvtColor() function

Import the OpenCV and read the original image using imread() than convert to grayscale using cv2.cvtcolor() function. destroyAllWindows() function allows users to destroy or close all windows at any time after exiting the script.

Python3
# import opencv
import cv2

# Load the input image
image = cv2.imread('C:\\Documents\\full_path\\tomatoes.jpg')
cv2.imshow('Original', image)
cv2.waitKey(0)

# Use the cvtColor() function to grayscale the image
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cv2.imshow('Grayscale', gray_image)
cv2.waitKey(0)  

# Window shown waits for any key pressing event
cv2.destroyAllWindows()

Input image: 

 


Output Image: 

Grayscaling of Images using OpenCV

 


Method 2: Using the cv2.imread() function with flag=zero

Import the OpenCV and read the original image using imread() than convert to grayscale using cv2.cvtcolor() function. 

Python
# Import opencv
import cv2

# Use the second argument or (flag value) zero
# that specifies the image is to be read in grayscale mode
img = cv2.imread('C:\\Documents\\full_path\\tomatoes.jpg', 0)

cv2.imshow('Grayscale Image', img)
cv2.waitKey(0)

# Window shown waits for any key pressing event
cv2.destroyAllWindows()

Output Image:

Grayscaling of Images using OpenCV

 

Method 3: Using the pixel manipulation (Average method)

Python
# Import opencv
import cv2

# Load the input image
img = cv2.imread('C:\\Documents\\full_path\\tomatoes.jpg')

# Obtain the dimensions of the image array
# using the shape method
(row, col) = img.shape[0:2]

# Take the average of pixel values of the BGR Channels
# to convert the colored image to grayscale image
for i in range(row):
    for j in range(col):
        # Find the average of the BGR pixel values
        img[i, j] = sum(img[i, j]) * 0.33

cv2.imshow('Grayscale Image', img)
cv2.waitKey(0)

# Window shown waits for any key pressing event
cv2.destroyAllWindows()

Output Image:

Grayscaling of Images using OpenCV

 

Hope you have understood the above-discussed image processing techniques to convert a colored image into a grayscale image in Python!



Previous Article
Next Article

Similar Reads

Arithmetic Operations on Images using OpenCV | Set-2 (Bitwise Operations on Binary Images)
Prerequisite: Arithmetic Operations on Images | Set-1Bitwise operations are used in image manipulation and used for extracting essential parts in the image. In this article, Bitwise operations used are : ANDORXORNOT Also, Bitwise operations helps in image masking. Image creation can be enabled with the help of these operations. These operations can
4 min read
Python | Create video using multiple images using OpenCV
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let's see how to create video using multiple images using OpenCV. Install the following libraries: PIL cv2 Also, check the path before running the code otherwise you will be full with errors. How it works ? Using PIL library we are opening
3 min read
Addition and Blending of images using OpenCV in Python
When we talk about images, we know its all about the matrix either binary image(0, 1), gray scale image(0-255) or RGB image(255 255 255). So additions of the image is adding the numbers of two matrices. In OpenCV, we have a command cv2.add() to add the images. Below is code for Addition of two images using OpenCV : # Python program for adding # ima
2 min read
Python | Denoising of colored images using opencv
Denoising of an image refers to the process of reconstruction of a signal from noisy images. Denoising is done to remove unwanted noise from image to analyze it in better form. It refers to one of the major pre-processing steps. There are four functions in opencv which is used for denoising of different images. Syntax: cv2.fastNlMeansDenoisingColor
1 min read
How to Detect Shapes in Images in Python using OpenCV?
Prerequisites: OpenCV OpenCV is an open source library used mainly for processing images and videos to identify shapes, objects, text etc. It is mostly used with python. In this article we are going to see how to detect shapes in image. For this we need cv2.findContours() function of OpenCV, and also we are going to use cv2.drawContours() function
3 min read
How to subtract two images using Python-OpenCV ?
In this article, we are going to see how to subtract two images using OpenCV in Python. Now, before getting into the topic we shall discuss some of the use cases of Arithmetic operations. Arithmetic operations like addition and subtraction can help us to make images brighter or darker. Specifically, subtraction of two images has a lot of purposes i
3 min read
Drawing with Mouse on Images using Python-OpenCV
OpenCV is a huge open-source library for computer vision, machine learning, and image processing. OpenCV supports a wide variety of programming languages like Python, C++, Java, etc. It can process images and videos to identify objects, faces, or even the handwriting of a human. In this article, we will try to draw on images with the help of the mo
3 min read
Measure similarity between images using Python-OpenCV
Prerequisites: Python OpenCVSuppose we have two data images and a test image. Let's find out which data image is more similar to the test image using python and OpenCV library in Python.Let's first load the image and find out the histogram of images.Importing library import cv2 Importing image data image = cv2.imread('test.jpg') Converting to gray
2 min read
How to Display Multiple Images in One Window using OpenCV Python?
Prerequisites: Opencv In this article, we will show how to display Multiple Images In One window using OpenCV in Python. Approach Import moduleLoad the Multiple images using cv2.imread()Concatenate the images using concatenate(), with axis value provided as per orientation requirementDisplay all the images using cv2.imshow()Wait for keyboard button
1 min read
Concatenate images using OpenCV in Python
To concatenate images vertically and horizontally with Python, cv2 library comes with two functions as: hconcat(): It is used as cv2.hconcat() to concatenate images horizontally. Here h means horizontal.vconcat(): It is used as cv2.vconcat() to concatenate images vertically. Here v means vertical.Implementation using hconcat() and vconcat() on Arra
3 min read
Practice Tags :
three90RightbarBannerImg