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
Let's discover how to do it with above mentioned functions
hello
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..
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()
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()
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