Reading, displaying, and saving images
Let's see how we can load an image in OpenCV-Python. Create a file named first_program.py
and open it in your favorite code editor. Create a folder named images
in the current folder, and make sure that you have an image named input.jpg
in that folder.
Once you do that, add the following lines to that Python file:
import cv2 img = cv2.imread('./images/input.jpg')
cv2.imshow('Input image', img) cv2.waitKey()
If you run the preceding program, you will see an image being displayed in a new window.
What just happened?
Let's understand the previous piece of code, line by line. In the first line, we are importing the OpenCV library. We need this for all the functions we will be using in the code. In the second line, we are reading the image and storing it in a variable. OpenCV uses NumPy data structures to store the images. You can learn more about NumPy at http://www.numpy.org
.
So if you open up the Python shell and type the following, you will see the datatype printed on the terminal:
> import cv2 > img = cv2.imread('./images/input.jpg') > type(img) <type 'numpy.ndarray'>
In the next line, we display the image in a new window. The first argument in cv2.imshow
is the name of the window. The second argument is the image you want to display.
You must be wondering why we have the last line here. The function, cv2.waitKey()
, is used in OpenCV for keyboard binding. It takes a number as an argument, and that number indicates the time in milliseconds. Basically, we use this function to wait for a specified duration, until we encounter a keyboard event. The program stops at this point, and waits for you to press any key to continue. If we don't pass any argument, or if we pass as the argument, this function will wait for a keyboard event indefinitely.
The last statement, cv2.waitKey(n)
, performs the rendering of the image loaded in the step before. It takes a number that indicates the time in milliseconds of rendering. Basically, we use this function to wait for a specified duration until we encounter a keyboard event. The program stops at this point, and waits for you to press any key to continue. If we don't pass any argument, or if we pass 0 as the argument, this function waits for a keyboard event indefinitely.