Reading an image in OpenCV using Python

In this article, we will try to open an image using OpenCV (Open Source Computer Vision). Some external libraries like numpy and matplotlib will also be used to complete our task.

Some external libraries need to be installed to do this:

 pip install opencv-python pip install numpy pip install matplotlib 

Input image:

Example # 1 ( using Numpy):

# Python code to read an image using OpenCV

import numpy as np

import cv2

  
# You can specify the path to
# image as first argument

img = cv2.imread ( 'cc.jpg' , 0 )

 
# will show the image in the window

cv2.imshow ( 'image' , img)

k = cv2.waitKey ( 0 ) & amp;  0xFF

 
# wait for the ESC key to exit

if k = = 27

cv2.destroyAllWindows ()

 
# wait for the & # 39; s & # 39; to save and exit

elif k = = ord ( 's' ): 

  cv2.imwrite ( 'messigray.png' , img)

cv2.destroyAllWindows ()

Example # 2 (using Matplotlib):

# Python code to read images with OpenCV

import cv2

import numpy as np

< p> import matplotlib.pyplot as plt

 

img = cv2.imread ( 'photo.jpg'

  cv2.IMREAD_GRAYSCALE)

 

cv2.imshow ( ' image' , img)

cv2.waitKey ( 0 )

cv2.destoryAllWindows ()

Output:





Get Solution for free from DataCamp guru