Add Trackbar and Bind on_change Event for OpenCV Window

In this tutorial, we will use an example to show you how to add a trackbar on opencv window and how to bind an on_change event for this trackbar.

Best Practice to Add Trackbar and Bind on_change Event for OpenCV Window

1.Read an image using opencv

import cv2

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

2.Create a function to process the value when trackbar is changed

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)

Here val is the value of trackbar.

3.Use cv2.createTrackbar() to create a trackbar and bind on_change event

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

cv2.waitKey(0)
cv2.destroyAllWindows()

Run this code, you will get this result.

Add Trackbar and Bind on_change Event for OpenCV Window