Introduction
In this tutorial, we will discuss how the color image is converted to grayscale image using two OpenCV functions: imread() and cvtColor().
Method 1: Using imread() function
imread() function is used to read an image from the disk but while loading the image, it can be directly converted to grayscale image. The imread function is already discussed in Python OpenCV: Read/Display/Write Image
Python Code
# import the library
import cv2 as cv
# Load the image as grayscale
img = cv.imread("lena.jpg", cv.IMREAD_GRAYSCALE)
# Display the image
cv.imshow("Grayscale", img)
cv.waitKey(0)
Output
Method 1: Using cvtColor() function
cvtColor() is one the functions used to convert color channels from one to other format to other. It is also used to convert the image to grayscale.Python Code
# import the library
import cv2 as cv
# Load the image as grayscale
img = cv.imread("lena.jpg")
# Convert to grayscale
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# Display the image
cv.imshow("Original Lena", img)
# Display the grayscale image
cv.imshow("Grayscale", gray)
cv.waitKey(0)
Output


No comments:
Post a Comment