Python OpenCV: Converting an image to HSV

The objective of this tutorial is to learn how to read an image and convert it to the HSV color space, using Python and OpenCV .

Introduction

The objective of this tutorial is to learn how to read an image and convert it to the HSV color space, using Python and OpenCV.

The code shown below was tested using Python 3.7.2 and version 4.0.0 of OpenCV.

The code

The first thing we are going to do is importing the cv2 module. This module will make available the functions we need to both read the image and convert it to another color space.

import cv2

Then, to read the original image, we simply need to call the imread function of the previously imported module. As input of this function we need to pass a string with the path to the image file we want to read.

image = cv2.imread('C:/Users/N/Desktop/Test.jpg')

To perform the color space conversion, we need to call the cvtColor function of the cv2 module. This function receives as first input the original image and as second input the color conversion code.

To choose the correct code, we need to take in consideration that, when calling the imread function, the image will be stored in BGR format. Thus, to convert to HSV, we should use the COLOR_BGR2HSV code.

As output, the cvtColor will return the converted image, which we will store in a variable.

hsvImage = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

After this, we will display both images. To show each image, we simply need to call the imshow function. It receives as first input a string with the name to be assigned to the window that will show the image, and as second input the image.

cv2.imshow('Original image',image)
cv2.imshow('HSV image', hsvImage)

To finalize, we will wait for the use to press a key and, after that, destroy the previously created windows.

cv2.waitKey(0)
cv2.destroyAllWindows()

The final code can be seen below.

import cv2
  
image = cv2.imread('C:/Users/N/Desktop/Test.jpg')
hsvImage = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

cv2.imshow('Original image',image)
cv2.imshow('HSV image', hsvImage)
  
cv2.waitKey(0)
cv2.destroyAllWindows()

Testing the code

To test the code, simply run it in a Python environment of your choice. In my case, I’m using IDLE, a Python IDE.

Note that, before running the code, you need to make sure to change the argument of the imread function to point to an image in your computer.

After running the code, you should get an output similar to figure 1, which shows both the original image and the image in HSV.

Output of the program, showing the original image the and image in the HSV color space.
Figure 1 – Output of the program, showing the original image the and image in the HSV color space.

Leave a Reply

%d bloggers like this: