Python OpenCV: How to add a slider to a window

Introduction

In this tutorial, we will learn how to add a slider to a OpenCV window where we are displaying an image, using Python.

A slider might be useful in scenarios where we want to test different values for a function and we want to change those values manually in a simple user interface. For example, if we are converting an image to black and white (like covered here) and we want to test different thresholds, we can use a slider to change the threshold value.

A simple example

As usual, we will start by importing the cv2 module. This will make available the functions we need to display an image and add a slider to it.

import cv2

After that, we will read an image from the file system. To do so, we simply need to call the imread function, passing as input the path to the image. You can check in more detail how to read and display an image on this previous tutorial.

img = cv2.imread('C:/Users/N/Desktop/monument.png')

After that, we will display the image in a window, with a call to the imshow function. As first input we need to pass the name of the window and as second the image. Note that we will define a variable to hold the name of the window since we will need to also use it when creating the slider.

windowName = 'image'

cv2.imshow(windowName, img)

To create a slider, we need to call the createTrackbar function from the cv2 module (note that OpenCV refers to this widget as trackbar). The function receives the following parameters:

  • Name of the slider. We will call it “slider”;
  • Name of the window where the slider will be created. We will pass the previously created variable that holds the image window name;
  • Initial value of the slider in the scale. We will start at zero (the range for this widget always starts at 0);
  • Maximum value of the slider scale. We will use a value of 100;
  • Callback function that will be called every time the position of the slider changes. We will check its definition below, but it will be called on_change.
cv2.createTrackbar('slider', windowName, 0, 100, on_change)

We will then wait for the user to press a key to destroy the created window and end the program.

cv2.waitKey(0)
cv2.destroyAllWindows()

To finalize, we will check the implementation of the on_change function. It will receive as input a variable with the current value of the slider. In the implementation of the function, we will just print the value received.

def on_change(value):
    print(value)

The complete code can be seen below.

import cv2


def on_change(value):
    print(value)


img = cv2.imread('C:/Users/N/Desktop/monument.png')

windowName = 'image'

cv2.imshow(windowName, img)
cv2.createTrackbar('slider', windowName, 0, 100, on_change)

cv2.waitKey(0)
cv2.destroyAllWindows()

To test the previous code, simply run it in a tool of your choice. I’ll be using PyCharm, a Python IDE.

You should get a result similar to figure 1. As can be seen, a slider was added to the image window, as expected. If you change its position, you should then see its current value getting printed to the console.

Adding a slider to the image with OpenCV.
Figure 1 – Adding a slider to the image with OpenCV.

A more complex example

Now that we already covered the basics in the previous section, we will create a slightly more complex application. Instead of simply printing the value of the slider to the console, we will now draw this value in the image.

All the code will be the same except for the callback function. So, we will focus our analysis on the on_change function.

The first thing we will do is creating a copy of the original image. This is needed because the function to write text changes the image. So, if we always use the original image, the numbers will overlap over each other as we are changing the slider. To avoid this, every time the callback executes, we copy the original image (unaltered) and write the slider value on the image copy.

The procedure to copy an image was covered in this post. In short, we simply need to call the copy method on our original image.

imageCopy = img.copy()

To write text to an image, we need to call the putText function from the cv2 module. It receives the following parameters:

  • Image to write the text. We will pass our image copy;
  • Text to be drawn, as a string. We will pass the value from the slider, after converting it to a string;
  • A tuple with the coordinates (x and y) of the bottom left corner where to put the text. We will put the text on the bottom left of the image. We will use x equal to 0 and y equal to the height of the image minus 10 pixels (more details on how to get the image dimensions here);
  • The font, from the cv2 module. You can check the possible values here. We are going to use FONT_HERSHEY_SIMPLEX;
  • The scale of the text. We will use a value of 1.0 to maintain the font-specific base size;
  • A tuple with the BGR values for the color of the font. We will set it to black (B=0, G=0, R=0);
  • The thickness of the lines to draw the text. We will use a value of 4.
cv2.putText(imageCopy, str(val), (0, imageCopy.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 4)

Now that we have drawn the slider value in the image, we will display it in a window.

cv2.imshow(windowName, imageCopy)

The whole callback function can be seen in the code snippet below.

def on_change(val):

    imageCopy = img.copy()

    cv2.putText(imageCopy, str(val), (0, imageCopy.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 4)
    cv2.imshow(windowName, imageCopy)

The complete code can be seen below.

import cv2


def on_change(val):

    imageCopy = img.copy()

    cv2.putText(imageCopy, str(val), (0, imageCopy.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 0), 4)
    cv2.imshow(windowName, imageCopy)


img = cv2.imread('C:/Users/N/Desktop/monument.png')

windowName = 'image'

cv2.imshow(windowName, img)
cv2.createTrackbar('slider', windowName, 0, 100, on_change)

cv2.waitKey(0)
cv2.destroyAllWindows()

After running the previous code, you should get a result like shown on figure 2. As can be seen, when moving the slider, the value will be drawn in the bottom left corner of the image.

Drawing the current slider value on the image.
Figure 2 – Drawing the selected value on the image.

Other OpenCV Posts

Technical details

  • Operating system: Windows 8.1
  • Python version: 3.7.2
  • OpenCV version: 4.1.2

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading