Home » Python

Read an image and save it as grayscale system using OpenCV python module

In this article, we will learn how to read an image and save it as grayscale image in your system using OpenCV python module?
Submitted by Ankit Rai, on June 11, 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 the 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 returns the newly converted image matrix.
  4. Imwrite() :
    It takes an absolute path/relative path (of the desired location where you want to save a modified image) and image matrix as an argument.

Python code to read an image and save it as grayscale system using OpenCV python module

# 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/pic6.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)

# save the image at specified location
cv2.imwrite(r"image\gray_img.jpg",gray_img)

Output

Read an image and save it as grayscale system using OpenCV python module







Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




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.