Home » Python

Coloured image to grayscale using OpenCV in Python

In this article, we will learn how to read a colourful image and display it as grayscale image using OpenCV python module?
Submitted by Ankit Rai, on April 24, 2019

In Python, we can use an OpenCV library named cv2. Python does not come with cv2, so we need to install it separately.

For Windows:

    pip install opencv-python

For Linux:

    sudo apt-get install python-opencv

In the below given program, we are using following three functions:

  1. imread():
    It takes an absolute path/relative path of your image file as an argument and returns its corresponding image matrix.
  2. imshow():
    It takes window name and image matrix as an argument in order to display an image in the display window with a specified window name.
  3. cv2.cvtcolor():
    It takes image matrix and a flag for changing color-space from one color space to another(in this case we are using BGR2GRAY color-space conversion) and return the newly converted image matrix.

Python code to convert a coloured image to grayscale image

# open-cv library is installed as cv2 in python
# import cv2 library into this program
import cv2

# read an image using imread() function of cv2
# we have to  pass only the path of the image
img = cv2.imread(r'C:/Users/user/Desktop/pic1.jpg')

# displaying the image using imshow() function of cv2
# In this : 1st argument is name of the frame
# 2nd argument is the image matrix
cv2.imshow('original image',img)

# converting the colourfull image into grayscale image
# using cv2.COLOR_BGR2GRAY argument of
# the cvtColor() function of cv2
# in this :
# ist argument is the image matrix
# 2nd argument is the attribute
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

# displaying the gray scale image
cv2.imshow('Gray scale image',gray_img)


Coloured image to grayscale using OpenCV in Python | output

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.