Reading, writing and displaying Images using OpenCV

Reading, displaying and writing images in OpenCV is very simple. Let us start by reading and displaying an image. In OpenCV, we use imread() function to read the images. This function will return a numpy array. This array can be stored in a variable which can then be used to display it. If it fails to read the image correctly, the function returns an empty matrix (None in case of Python).

The signature of the imread() function in OpenCV is shown below:

cv2.imread(filename [, flags])

Parameter Description
filename Name of image to read. It must be a string value. Specifiy either an absolute path or relative path.
flags This is an optional parameter. Flag that can take values of Enumeration Type define by ImreadModes.

Similarly, to display an image in OpenCV, we use imshow() function. The signature of the imshow() function is shown as below:

cv2.imshow (winname, mat)

Parameter Description
winname Name of the window. It is a string value.
mat This is image data to be shown in the window.

Code 1-1 shows a simple way to read an image using imread() function and display it using imshow() function.

Code 1-1
1
2
3
4
5
6
import cv2
path = r'F:\img\lena.jpg'
img = cv2.imread(path)
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Executing the code shown in Code 1-1 will produce the output shown in Figure 1.

No image
Figure 1. Read and display an image.

Code Explanation

Line 1: We started by importing the OpenCV library. The OpenCV library is packaged in cv2. Now we can use cv2 to call any function present in the OpenCV library.
Line 2: We must provide a valid path to an image. In this case, I am reading an image from my disk.

Line 3: The image data is read using cv2.imread() function. We provide the path of the image to read as its first parameter. Optionally, we can provide second parameter. For now, just giving first parameter is enough, we will discuss at later stage. If the path is valid it will return numpy array otherwise None is returned.
Line 4: It displays the image using OpenCV's imshow() function. This will open a separate window and show the image. Note that the first parameter "Image" is displayed as title of the displayed window.

Line 5: The waitKey() function makes the displayed window to wait for the specified amount of time and then closes automatically. However, when we pass 0 as argument then the window will wait till any key is pressed.

Line 6: Finall, we close all winows by calling the destroyAllWindows() function.

Image Read Modes

Notice that we did not provide the second parameter value in the imread() function, i.e. ImreadModes. So, it uses default way to read the image. We can specifiy it by specifying ImreadModes mode. For example, to read a color image, we can specify the flag. Replace line 3 with the following line of code to specify that we read a color image.

img = cv2.imread(path, cv2.IMREAD_COLOR])

Here cv2.IMREAD_COLOR specifies that we are reading a color image. OpenCV will always return 3 channel image with the order BGR image. Where B stands for blue, G for green and R for red channels.

We can read grayscale image by specifying second parameter as cv2.IMREAD_GRAYSCALE. In such case, OpenCV always convert image to the single channel grayscale image. The code in Code 1 - 2 shows how to read and display a grayscale image.

Code 1 - 2
1
2
3
4
5
6
import cv2
path = r'F:\img\lena.jpg'
img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
cv2.imshow('Image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

The output of this code is shown in Figure 2.

No image
Figure 2. Read and display a grayscal image.

A complete list of available ImreadModes are summarized in Table 1.

Table 1: Complete list of Imread flags avilable in OpenCV 4.6

Parameter

Description

IMREAD_UNCHANGED

If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). Ignore EXIF orientation.

IMREAD_GRAYSCALE

If set, always convert image to the single channel grayscale image (codec internal conversion).

IMREAD_COLOR 

If set, always convert image to the 3 channel BGR color image.

IMREAD_ANYDEPTH 

If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.

IMREAD_ANYCOLOR 

If set, the image is read in any possible color format.

IMREAD_LOAD_GDAL 

If set, use the gdal driver for loading the image.

IMREAD_REDUCED_GRAYSCALE_2 

If set, always convert image to the single channel grayscale image and the image size reduced 1/2.

IMREAD_REDUCED_COLOR_2 

If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2.

IMREAD_REDUCED_GRAYSCALE_4 

If set, always convert image to the single channel grayscale image and the image size reduced 1/4.

IMREAD_REDUCED_COLOR_4 

If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4.

IMREAD_REDUCED_GRAYSCALE_8 

If set, always convert image to the single channel grayscale image and the image size reduced 1/8.

IMREAD_REDUCED_COLOR_8 

If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8.

IMREAD_IGNORE_ORIENTATION 

If set, do not rotate the image according to EXIF's orientation flag.

Supported Image Formats

Currently, the following image formats are supported in OpenCV for reading and writing:

  • Windows bitmaps - *.bmp, *.dib
  • JPEG files - *.jpeg, *.jpg, *.jpe
  • JPEG 2000 files - *.jp2 (see the Note section)
  • Portable Network Graphics - *.png (see the Note section)
  • WebP - *.webp (see the Note section)
  • Portable image format - *.pbm, *.pgm, *.ppm *.pxm, *.pnm (always supported)
  • PFM files - *.pfm (see the Note section)
  • Sun rasters - *.sr, *.ras (always supported)
  • TIFF files - *.tiff, *.tif (see the Note section)
  • OpenEXR Image files - *.exr (see the Note section)
  • Radiance HDR - *.hdr, *.pic (always supported)
  • Raster and Vector geospatial data supported by GDAL (see the Note section)

Displaying images with Matplotlib

You can also get the same results by using Matplotlib's imshow() function. Code 1 - 3 shows you how to display images using Matplotlib library.

Code 1 - 3
1
2
3
4
5
6
7
import cv2
import matplotlib.pyplot as plt
path = r'F:\img\lena.jpg'
img = cv2.imread(path)
rgb =  cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
plt.imshow(rgb)
plt.axis('off')

The output of the above code is shown in the Figure 1-3

No image
Figure 1-3: Image displayed using Matplotlib library.

The code in listing Code 1-3 is same as Code 1-1 except few line which are described below:

Line 2: We start by importing matplotlib.pyplot to use its functionality to display image.
Line 5: This line converts image from BGR to RGB format. For now we can leave it as it is and will discuss again when we cover color conversions later in coming chapters. The second parameter indicates this COLOR_BGR2RGB.
Line 6: This uses the Matplotlib’s imshow() function define in pyplot to show the image.
Line 7: Optionally, we can intentionally turn off the axis shown around the image.

Unlike cv2.imshow() which displays the image in a separate window, matplotlib’s imshow() function displays the output image inside the JupyterLab’s output window.

Writing the image to disk

We can write the image to a file on disk using imwrite() function in OpenCV. The code listing in Code 1-4 shows how to write an image to the disk. Note that if full path is not provided, it will write to the image to the same directory where the code is present.

Code 1 - 4
1
2
3
4
import cv2
path = r'F:\img\lena.jpg'
img = cv2.imread(path)
cv2.imwrite("output.jpg", img);

Line 4: We use imwrite() function to write the image to the location specified by the first string parameter. You can specify the absolute path as well.

OpenCV Tutorials