Read and Write Color Images in Grayscale with Python OpenCV

Python opencv cv2.imread() method can allow us to read a color image to gray. In this tutorial, we will show you how to read a color image and write it to a gray one.

Read and Write Color Images in Grayscale with Python OpenCV

1.Import library

import cv2

2.Read image with cv2.imread() in grayscale

im_gray = cv2.imread('test.png', cv2.IMREAD_GRAYSCALE)
# im_gray = cv2.imread('test.png', 0)

print(type(im_gray))
# <class 'numpy.ndarray'>

print(im_gray.shape)
# (225, 400)

print(im_gray.dtype)
# uint8

You should notice: v2.IMREAD_GRAYSCALE is the key point

3.Wrtie gray image to image file using cv2.imwrite()

cv2.imwrite('d.jpg', im_gray)

Moreover, you also can use cv2.cvtColor() to conver a color image to gray one. Here is an example:

Save a Gray Image in Python OpenCV