OpenCV (Open Source Computer Vision) is a library of programming functions mainly aimed at real-time computer vision
OpenCV-Python is the Python API for OpenCV, combining the best qualities of the OpenCV C++ API and the Python language. It has large user base, with good documentation, Huge library and support
OR
pip install opencv-python
To install OpenCV
The prerequisite python packages are
1. Numpy.
2. Matplotlib (optional, but needed many cases)
In windows, install all packages into their default locations. Python will be installed to C:/Python27/.
After instllation import Numpy by the command
import numpy
Now , Download latest OpenCV release from sourceforge site extract it.
Copy file- cv2.pyd (from opencv/build/python/2.7) and paste it to C:/Python27/lib/site-packeges.
Now, open Python IDLE and type following codes in Python terminal.
import cv2
print cv2.__version__
Now your OpenCV is ready to use !!!
Read Show and write an Image
To read an image use the command cv2.imread('file name' ) with full path of your file
import numpy as np import cv2 img= cv2.imread('C:\Users\user\Desktop\python\image.jpg')
Try print img to check whether you are done.
You can also use attribute to load image.
cv::IMREAD_UNCHANGED = -1,
cv::IMREAD_GRAYSCALE = 0,
cv::IMREAD_COLOR = 1,
cv::IMREAD_ANYDEPTH = 2,
cv::IMREAD_ANYCOLOR = 4,
cv::IMREAD_LOAD_GDAL = 8,
cv::IMREAD_REDUCED_GRAYSCALE_2 = 16,
cv::IMREAD_REDUCED_COLOR_2 = 17,
cv::IMREAD_REDUCED_GRAYSCALE_4 = 32,
cv::IMREAD_REDUCED_COLOR_4 = 33,
cv::IMREAD_REDUCED_GRAYSCALE_8 = 64,
cv::IMREAD_REDUCED_COLOR_8 = 65
Now to show image on your python interface, try cv2.imshow()
cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows()
Please note the commands cv2.waitKey(0) and cv2.destroyAllWindows()
cv2.waitKey(0) is a keyboard binding function. here since we have given zero, it will wait indefinitely. you may also put ASCII values for specif interruption.
cv2.destroyAllWindows() destroys all the windows we created.
cv2.namedWindow('name', cv2.WINDOW_AUTOSIZE) cv2.imshow('name',img_file) cv2.waitKey(0) cv2.destroyAllWindows()
Now lets write an image file by cv2.imwrite('C:/Users/user/Desktop/python/newimg.png',img)
Please have a look at the following example
import numpy as np import cv2 img = cv2.imread('C:/Users/user/Desktop/python/image.jpg') cv2.imshow('image',img) k = cv2.waitKey(0) if k == 27: # wait for ESC key to exit cv2.destroyAllWindows() elif k == ord('s'): # wait for 's' key to save and exit cv2.imwrite('C:/Users/user/Desktop/python/newimg.png',img) cv2.destroyAllWindows() cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows()