Working with image files
OpenCV provides a very simple way to load images, using imread()
:
import cv2 image = cv2.imread('test.jpg')
To show the image, you can use imshow()
, which accepts two parameters:
- The name to write on the caption of the window that will show the image
- The image to be shown
Unfortunately, its behavior is counterintuitive, as it will not show an image unless it is followed by a call to waitKey()
:
cv2.imshow("Image", image)cv2.waitKey(0)
The call to waitKey()
after imshow()
will have two effects:
- It will actually allow OpenCV to show the image provided to
imshow()
. - It will wait for the specified amount of milliseconds, or until a key is pressed if the amount of milliseconds passed is
<=0
. It will wait indefinitely.
An image can be saved on disk using the imwrite()
method, which accepts three parameters:
- The name of the file
- The image
- An optional format-dependent parameter:
cv2.imwrite("out.jpg", image)
Sometimes, it can be very useful to combine multiple pictures by putting them next to each other. Some examples in this book will use this feature extensively to compare images.
OpenCV provides two methods for this purpose: hconcat()
to concatenate the pictures horizontally and vconcat()
to concatenate them vertically, both accepting as a parameter a list of images. Take the following example:
black = np.zeros([50, 50], dtype=np.uint8)white = np.full([50, 50], 255, dtype=np.uint8)cv2.imwrite("horizontal.jpg", cv2.hconcat([white, black]))cv2.imwrite("vertical.jpg", cv2.vconcat([white, black]))
Here's the result:
We could use these two methods to create a chequerboard pattern:
row1 = cv2.hconcat([white, black])row2 = cv2.hconcat([black, white])cv2.imwrite("chess.jpg", cv2.vconcat([row1, row2]))
You will see the following chequerboard:
After having worked with images, it's time we work with videos.