In this tutorial, I will show you how to read, display, and write images using OpenCV's built-in functions.
We will use:
The image below will be used as an example throughout this tutorial:
To read an image with OpenCV, we can use the cv2.imread(filename, flags) function. It takes 2 arguments:
The imread function returns a Numpy array that represents the image or None if the image couldn't be loaded.
Here is the syntax:
import cv2 image = cv2.imread("path-to-image.jpg")
For your reference, check out the documentation for the imread() function.
To display an image with OpenCV, we use the imshow(win_name, img) function. This function also takes 2 arguments:
In order to display the image, we need to call another function: cv2.waitKey(). This function is responsible for keeping the window open for some time. We can pass it a number to specify how long (in milliseconds) the window should stay open. 0 instructs the function to keep the window open indefinitely until a key is typed.
let's see some examples of reading and displaying an image.:
image = cv2.imread('image.jpg') cv2.imshow('color image', image) cv2.waitKey(0)
image = cv2.imread('image.jpg', cv2.IMREAD_UNCHANGED) cv2.imshow('unchanged image', image) cv2.waitKey(0)
image = cv2.imread('image.jpg', cv2.IMREAD_GRAYSCALE) cv2.imshow('grayscale image', image) cv2.waitKey(0)
For your reference, check out the documentation for the imshow() function.
To save an image into the file directory, we use the imwrite(filename, img) function. The function takes 2 arguments.
The function returns a Boolean: True if the image was saved successfully or False otherwise.
image = cv2.imread("cards.jpg") # read the image cv2.imwrite("newimage.png", image) # save image
If you check the content of the directory you will see that a file newimage.png was added:
$ ls image.jpg newimage.png read_write_save.py
For your reference, check out the documentation for the imwrite() function.
With these built-in functions, you can now easily load, display, and save images using OpenCV.
Try experimenting with these functions and if you are a beginner I recommend that you write the code by hand (do not copy / paste) to familiarize yourself with the library.
If you want to learn more about computer vision and image processing then check out my course Computer Vision and Image Processing with OpenCV and Python.
If you need help, don't hesitate to leave a comment in the section below. Also, don't forget to subscribe to the mailing list to be notified of future posts.