I/O Operations on Images

Learn to read an image from a file, write an image to a file, and display an image.

In this course, images are the focus of our attention. The first thing we need to know is how to manipulate these objects.

The computer vision library that we’ll use is OpenCV. It is an open-source library that is wide and deep, but we’ll use only a tiny fraction of its functionalities. As you progress as a computer vision practitioner, you’ll get familiar with various aspects of the library, but for now, let’s look at its I/O functions.

Reading images

Press + to interact
import cv2 # Imports OpenCV
image = cv2.imread("./images/hens/paprika2.jpg") # Reads an image from a filepath
type_of_image = type(image) # What is the type of this object?
image_shape = image.shape # The image shape (H, W, C)
print(f"type_of_image = {type_of_image}; image_shape = {image_shape}")

As we can see, after executing the code above, the type of the image object that is returned by cv2.imread() is numpy.ndarray.

The Python version of OpenCV implements the image object as a NumPy array. So, if you have worked with NumPy before, you’ll find yourself in familiar territory, working with OpenCV.

The image shape is (600, 800, 3), corresponding to its height, width, and number of channels. The number of channels, 3, tells us that it is a color image.

Note: To display our mysterious image, we’ll save it in the ./output directory. After running the code widget below, the Educative built-in image viewer will display the image.

Writing images

We already saw that the function that reads an image from a file is cv2.imread(). You will have probably guessed that the function that writes an image to a file is cv2.imwrite(). It takes two arguments: the file path and the image object.

Let’s use it:

Press + to interact
import cv2 # Imports OpenCV
import os
image = cv2.imread("./images/hens/paprika2.jpg") # Reads an image from a filepath
cv2.imwrite(os.path.join('./output', 'the_mysterious_image.png'), image) # Writes an image to a file

Displaying images

The little trick we just used (writing the image to the ./output directory) will work perfectly in this course. However, when you work off the Educative platform, you can use the OpenCV functions cv2.imshow() and cv2.waitKey().

Press + to interact
cv2.imshow("Paprika", image)
cv2.waitKey(0)

These calls spawn a pop-up window (with the name “Paprika” in this case) that shows the image.

Now, we know how to read, write, and display images. That’s a good start!