1. 效果
2. 代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by zxq on 2021/2/7
import cv2
import numpy as np
def nothing(x):
pass
"""
窗口名字是image,这个窗口里面有4个滑动条,分别是R,G,B,switch.
"""
# 1, Create a black image, a window
img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow('image')
"""
参数:
trackbarName:滑动条的名称
windowName:所在窗口的名称
value: 滑块起始值
count: 滑块最大值
onChange: 回调函数,即当滑块位置改变时就会调用的函数,并且回调函数第一个参数为滑块位置所对应的值
"""
# 2, create trackbars for color change
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image', 0, 1, nothing)
while 1:
cv2.imshow('image', img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# 3, get current positions of four trackbars
r = cv2.getTrackbarPos('R', 'image')
g = cv2.getTrackbarPos('G', 'image')
b = cv2.getTrackbarPos('B', 'image')
s = cv2.getTrackbarPos(switch, 'image')
if s == 0:
img[:] = 0
else:
img[:] = [b, g, r]
cv2.destroyAllWindows()