To complete this recipe, the steps are as follows:
- First create an OpenCV window named window:
import cv2, numpy as np
cv2.namedWindow('window')
- Create a variable that will contain the fill color value for the image. The variable is a NumPy array with three values that will be interpreted as blue, green, and red color components (in that order) from the [0, 255] range:
fill_val = np.array([255, 255, 255], np.uint8)
- Add an auxiliary function to call from each trackbar_callback function. The function takes the color component index and new value as settings:
def trackbar_callback(idx, value):
fill_val[idx] = value
- Add three trackbars into window and bind each trackbar callback to a specific color component using the Python lambda function:
cv2.createTrackbar('R', 'window', 255, 255, lambda v: trackbar_callback(2, v))
cv2.createTrackbar('G', 'window', 255, 255, lambda v: trackbar_callback(1, v))
cv2.createTrackbar('B', 'window', 255, 255, lambda v: trackbar_callback(0, v))
- In a loop, show the image in a window with three trackbars and process keyboard input as well:
while True:
image = np.full((500, 500, 3), fill_val)
cv2.imshow('window', image)
key = cv2.waitKey(3)
if key == 27:
break
cv2.destroyAllWindows()