Reading an image in OpenCV using Python

Prerequisite : Basics of OpenCV

In this article we’ll try to open an image by using OpenCV (Open Source Computer Vision). Some external libraries such as numpy and matplotlib will also be used to get our task done.

Inorder to do this, some external libraries are required to install :



pip install opencv-python
pip install numpy
pip install matplotlib

 
Input Image :

 




Example #1 (Using Numpy) :

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to reading an image using OpenCV
import numpy as np
import cv2
  
# You can give path to the
# image as first argument
img = cv2.imread('cc.jpg', 0)
  
# will show the image in a window
cv2.imshow('image', img)
k = cv2.waitKey(0) & 0xFF
  
# wait for ESC key to exit
if k == 27
    cv2.destroyAllWindows()
      
# wait for 's' key to save and exit
elif k == ord('s'): 
    cv2.imwrite('messigray.png',img)
    cv2.destroyAllWindows()

chevron_right


Example #2 (Using Matplotlib):

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python code to reading an image using OpenCV
import cv2
import numpy as np
import matplotlib.pyplot as plt
  
img = cv2.imread('photo.jpg'
                  cv2.IMREAD_GRAYSCALE)
  
cv2.imshow('image', img)
cv2.waitKey(0)
cv2.destoryAllWindows()

chevron_right


Output :



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.