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)

Output

Coloured image to grayscale using OpenCV in Python | output






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.