- 目标:创建滑动条,把滑动条绑定到opencv窗口
- 主要函数:cv2.getTrackbarPos();cv2.creatTrackbar()
- 示例:我们创建一个窗口和一个滑动条,通过滑动条来改变窗口的颜色。先介绍一下cv2.creatTrackbar()函数,函数的第一个参数时滑动条的名字,第二个参数时滑动条被放置的窗口的名字,第三个参数是滑动条默认值,第四个参数时滑动条的最大值,第五个参数时回调函数,每次滑动都会调用回调函数。
第二个函数cv2.getTrackbarPos(),共有2个参数,第一个参数是滑动条名字,第二个时所在窗口偶,返回值是滑动条位置。
# -*- encoding: utf-8 -*-
import cv2
import numpy as np
# 定义回调函数,此程序无需回调,所以Pass即可
def callback(object):
pass
img = np.zeros((500, 400, 3), np.uint8)
cv2.namedWindow('image')
# 创建一个开关滑动条,只有两个值,起开关按钮作用
switch = '0:OFF\n1:ON'
cv2.createTrackbar(switch, 'image', 0, 1, callback)
cv2.createTrackbar('R', 'image', 0, 255, callback)
cv2.createTrackbar('B', 'image', 0, 255, callback)
cv2.createTrackbar('G', 'image', 0, 255, callback)
while(True):
r = cv2.getTrackbarPos('R', 'image')
g = cv2.getTrackbarPos('G', 'image')
b = cv2.getTrackbarPos('B', 'image')
if cv2.getTrackbarPos(switch, 'image') == 1:
img[:] = [b, g, r]
else:
img[:] = [255, 255, 255]
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cv2.imshow('image', img)
cv2.destroyAllWindows()
结果:
# -*- encoding: utf-8 -*-
import cv2
import numpy as np
# 定义回调函数,此程序无需回调,所以Pass即可
def callback(object):
pass
img = np.zeros((300, 400, 3), np.uint8)
cv2.namedWindow('image')
# 创建一个开关滑动条,只有两个值,起开关按钮作用
switch = '0:OFF\n1:ON'
cv2.createTrackbar(switch, 'image', 0, 1, callback)
cv2.createTrackbar('R', 'image', 0, 255, callback)
cv2.createTrackbar('B', 'image', 0, 255, callback)
cv2.createTrackbar('G', 'image', 0, 255, callback)
def Mouseback(event, x, y, flags, param):
if flags == cv2.EVENT_FLAG_LBUTTON and event == cv2.EVENT_MOUSEMOVE:
cv2.circle(img, (x, y), 1, [b, g, r], 1)
img[:] = [255, 255, 255]
while(True):
r = cv2.getTrackbarPos('R', 'image')
g = cv2.getTrackbarPos('G', 'image')
b = cv2.getTrackbarPos('B', 'image')
if cv2.getTrackbarPos(switch, 'image') == 1:
cv2.setMouseCallback('image', Mouseback)
else:
img[:] = [255, 255, 255]
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cv2.imshow('image', img)
cv2.destroyAllWindows()