OpenCV(Open source computer vision) is an open source programming library basically developed for machine learning and computer vision. It provides common infrastructure to work on computer vision applications and to fasten the use of machine learning in commercial products.
With more than 2.5 thousand optimized algorithms for both computer vision and machine learning are both classic and state-of-the-art algorithms. With so many algorithms, makes it to use the library for multiple purposes including face detection & recognization, identify objects, classify human actions in videos, track camera movements, join images together to produce a high resolution image of an entire scene and much more.
In this I'll try to explain how we can use OpenCV library and python to read and display image. This is implemented using cv2 and Numpy modules.
You can download numpy module from the Python Package Index(PyPI).
$ pip install numpy
We use cv2.imread() function to read an image. The image should be placed in the current working directory or else we need to provide the absoluate path.
import numpy as np import cv2 # Load an color image in grayscale img = cv2.imread('Top-bike-wallpaper.jpg',0)
To display an image in a window, use cv2.imshow() function.
#Display the image cv2.imshow('image',img) #key binding function cv2.waitKey(0) #Destroyed all window we created earlier. cv2.destroyAllWindows()
On running above code, a screenshot of the window will look like this,
Use the function cv2.imwrite() to save an image.
First argument is the file name, second argument is the image you want to save.
Sum it up −
import numpy as np import cv2 #Read the Image # Load an color image in grayscale img = cv2.imread('Top-bike-wallpaper.jpg',0) #Display the image cv2.imshow('image',img) #key binding function k = cv2.waitKey(0) # 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('myBike.jpg',img) cv2.destroyAllWindows()
Save the image by pressing 's' or press 'ESC' key to simply exit without saving.
The Python Imaging Library (PIL) is image manipulation library in python. Use pip to install PIL library,
$ pip install Pillow
from PIL import Image, ImageFilter
#Read image im = Image.open( 'myBike.png' ) #Display image im.show() #Applying a filter to the image im_sharp = im.filter( ImageFilter.SHARPEN ) #Saving the filtered image to a new file im_sharp.save( 'another_Bike.jpg', 'JPEG' )
Image is saved in my default location .i.e. currently working directory and a screenshot of the window will display our images.