Reading an image using Python OpenCv module


In OpenCv module,we can use the function cv2.imread() to read an image. When inputting the image path, the image should be in the working directory or a full path of image should be given.

cv2.IMREAD_COLOR − This function loads a color image and any transparency of image will be neglected. It is the default flag.

cv2.IMREAD_GRAYSCALE − This function loads image in grayscale mode

cv2.IMREAD_UNCHANGED − This function loads image as such including alpha channel

Source Image

Source Image

Example

import numpy as np
import cv2
my_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg', 0)
cv2.imshow('image', my_img)
k = cv2.waitKey(0) & 0xFF
# wait for ESC key to exit
if k == 27:
   cv2.destroyAllWindows()
elif k == ord('s'):
   cv2.imwrite('C:/Users/TP/Desktop/poor/poverty_india_gray.jpg',my_img)
   cv2.destroyAllWindows()

import cv2
import numpy as np
import matplotlib.pyplot as plt
my_img = cv2.imread('C:/Users/TP/Desktop/poor/poverty_india.jpg',cv2.IMREAD_GRAYSCALE)
cv2.imshow('image', my_img)
cv2.waitKey(0)
cv2.destoryAllWindows()

Output

Poverty

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements