How to convert color image to grayscale in OpenCV

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

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

hello

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 usingcv2.imread("image-name.png",0)or you can also writecv2.IMREAD_GRAYSCALEin the place of 0 as it also denotes the same constant.

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()


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

output_img


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

Akash Srivastava
Software Engineer @ Seawoods Ventures Inc.
© 2019-2024 dev-akash.in