Python OpenCV: Read a Color Image to Grayscale Image Using cv2.imread()

In python opencv, we can use cv2.imread() to read an image. However, if you want to read a color image to grayscale, how to do? In this tutorial, we will introduce this topic.

Python OpenCV: Read a Color Image to Grayscale Image Using cv2.imread()

If you want to convert a color image to grayscale in python opencv, you can read:

Read and Write Color Images in Grayscale with Python OpenCV 

1.Read an image using cv2.IMREAD_GRAYSCALE

As to cv2.imread(), it is defined as:

cv2.imread(filename[, flags])

Here flags can be:

  • cv2.CV_LOAD_IMAGE_ANYDEPTH – If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
  • cv2.CV_LOAD_IMAGE_COLOR – If set, always convert image to the color one.
  • cv2.CV_LOAD_IMAGE_GRAYSCALE – If set, always convert image to the grayscale one.
  • cv2.IMREAD_UNCHANGED – If set, load image with alpha channel
  • >0 Return a 3-channel color image.
  • =0 Return a grayscale image.
  • <0 Return the loaded image as is (with alpha channel).

If you want to read a color image to be grayscale, you can do like this:

import cv2
import numpy as np

img_file = 'images/TriColor.png'
gray_img = cv2.imread(img_file, cv2.IMREAD_GRAYSCALE)  # grayscale

Here gray_img is grayscale image.

Python Pillow - Convert Color Image to Grayscale Image