Cv2 Rgb To Gray

CvtColor function in OpenCV is very helpful in converting color channels from one to another such as BRG to HSV or BRG to RGB. The same method can be used to convert BRG to GRAY by using the cv2.cvtColor (img,cv2.BGR2GRAY). Consider a color image, given by its red, green, blue components R, G, B. The range of pixel values is often 0 to 255. Color images are represented as multi-dimensional arrays - a collection of three two-dimensional arrays, one each for red, green, and blue channels. Each one has one value per pixel and their ranges are identical. For grayscale images, the result is a two-dimensional array.

Introduction

Welcome, In this tutorial we are going to see how to read a image as grayscale as well as we will convert a color image into a grayscale image using opencv and python, if you do not know how to read a image in opencv, do check out this post here.

So to convert a color image to a grayscale image in opencv, we can have two solution

  • Convert image to grayscale with imread() function
  • Convert image to grayscale using cvtColor() function
Let's discover how to do it with above mentioned functions...

Method 1: Using imread() function

imread() function is used to read an image in OpenCV but there is one more parameter to be considerd, that is flag which decides the way image is read. There three flag defined in OpenCV..

  1. cv2.IMREAD_COLOR or 1
  2. cv2.IMREAD_GRAYSCALE or 0
  3. cv2.IMREAD_UNCHANGED or -1
So to convert the color image to grayscale we will be using cv2.imread('image-name.png',0) or you can also write cv2.IMREAD_GRAYSCALE in the place of 0 as it also denotes the same constant.
Cv2 Rgb To Gray
import cv2
# Reading color image as grayscale
gray = cv2.imread('color-img.png',0)
# Showing grayscale image
cv2.imshow('Grayscale Image', gray)
# waiting for key event
cv2.waitKey(0)
# destroying all windows
cv2.destroyAllWindows()

Opencv Convert Gray To Rgb

Method 2: Using cvtColor() function

cvtColor() function in OpenCV is very helpful in converting color channels from one to another such as BRG to HSV or BRG to RGB. The same method can be used to convert BRG to GRAY by using the cv2.cvtColor(img,cv2.BGR2GRAY)

import cv2
# Reading color image
img = cv2.imread('color-img.png')
# Converting color image to grayscale image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Showing the converted image
cv2.imshow('Converted Image',gray)
# waiting for key event
cv2.waitKey(0)
# destroying all windows
cv2.destroyAllWindows()

Output


Conclusion

In this post we came to know two ways in which we can convert a color image to a grayscale image and came across the function like cvtColor() and imread() flags used in opencv to perform that conversion. If you want to read more articles related to OpenCV click here

Dev-Akash

A Computer Vision Enthusiast

View Profile

Cv2 Convert Rgb To Grayscale

Back To Top