Saturday , September 18 2021
Home / Computer Vision / Reading Image as Color or GrayScale Image in Python using OpenCV

Reading Image as Color or GrayScale Image in Python using OpenCV

2 – Read Color and GrayScale Image

Reading Image as Color or GrayScale Image in Python using OpenCV

In this article, we’ll try to open an image by using OpenCV (Open Source Computer Vision). To use the OpenCV library in python, we need to install these libraries as a prerequisite:

  • Numpy Library (Necessary, because OpenCV uses it in the background).
  • OpenCV python

To install these libraries, we need to run these pip commands in cmd:

  • pip install opencv-python
  • pip install numpy
  • pip install matplotlib

Functions you need to understand

  • Read an image from file (using cv::imread)
  • Display an image in an OpenCV window (using cv::imshow)
  • Write an image to a file (using cv::imwrite)

Reading a GrayScale Image in Python using OpenCV

In [5]:
import cv2
img = cv2.imread('machinelearning.png',cv2.IMREAD_GRAYSCALE)
cv2.imshow('Machine Learning',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Note: Instead of writng cv2.IMREAD_GRAYSCALE, write 0 to read image as GrayScale image

In [2]:
import cv2
img = cv2.imread('machinelearning.png',0)
cv2.imshow('Machine Learning',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Reading a Color Image in Python using OpenCV

In [3]:
import cv2
img = cv2.imread('machinelearning.png',cv2.IMREAD_COLOR)
cv2.imshow('Machine Learning',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Note: Instead of writng cv2.IMREAD_COLOR, write 1 to read image as color image

In [4]:
import cv2
img = cv2.imread('machinelearning.png',1)
cv2.imshow('Machine Learning',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

About Machine Learning

Check Also

Record Video From a Webcam using OpenCV

12 Record Video using OpenCV Record Video From a Webcam using OpenCV¶ cv2.VideoWriter( filename, fourcc, …

Leave a Reply

Your email address will not be published. Required fields are marked *