Open In App

Python | Grayscaling of Images using OpenCV

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 

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.




# 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: 

 

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. 




# 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:

 

Method 3: Using the pixel manipulation (Average method)




# 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:

 

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


Article Tags :