Opencv之调色板函数使用及案例

1、Trackbar functions

函数1:cv2.getTrackbarPos() 

参数使用:

trackbarname     Name of the trackbar.

winname      Name of the window that is the parent of the trackbar.

函数2:cv2.createTrackbar()

参数使用:

trackbarname     Name of the created trackbar.

winname      Name of the window that will be used as a parent of the created trackbar.

value     Optional pointer to an integer variable whose value reflects the position of the slider. Upon creation, the slider position is defined by this variable.

count    Maximal position of the slider. The minimal position is always 0.

onChange   Pointer to the function to be called every time the slider changes position. This function should be prototyped as void Foo(int,void*); , where the first parameter is the trackbar position and the second parameter is the user data (see the next parameter). If the callback is the NULL pointer, no callbacks are called, but only value is updated.

userdata      User data that is passed as is to the callback. It can be used to handle trackbar events without using global variables.

2、Code Demo

# -*- coding: utf-8 -*-
import cv2
import numpy as np
# 定义一个回调函数,供createTrackbar()函数使用
def nothing(x):
pass
# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')        # 定义一个window name,供createTrackbar()函数使用
# create trackbars for color change
cv2.createTrackbar('R','image',100,255,nothing)   # 参数1:调色板的名称;参数2:window name;参数3:默认值;参数4:最大值;参数5:调色值变化的回调函数
cv2.createTrackbar('G','image',150,255,nothing)   # 注解:对于参数3,这里是展现的默认值,最小值是从0开始
cv2.createTrackbar('B','image',20,255,nothing)
# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'   # 注解,这里的换行符\n显示不出来?
cv2.createTrackbar(switch, 'image',0,1,nothing)
while(1):
cv2.imshow('image',img)         # 显示图像,其中参数1为;window name;参数2为:一个image
k = cv2.waitKey(1) & 0xFF       # 等待键盘输入
if k == 27:                     # 如果为Esc,则退出
break
# 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:                      # 如果当前的s调色板位置为0,返回[0,0,0],即黑色
# img[:] = 0
img[:] = [255,255,255]
else:                           # 否则返回[b,g,r]组合色
img[:] = [b,g,r]
cv2.destroyAllWindows()             # 销毁Windows事件

3、参考网址

参考资料1(getTrackbarPos函数使用):

http://docs.opencv.org/3.3.0/d7/dfc/group__highgui.html#ga122632e9e91b9ec06943472c55d9cda8

参考资料2(createTrackbar()函数使用):

http://docs.opencv.org/3.3.0/d7/dfc/group__highgui.html#gaf78d2155d30b728fc413803745b67a9b

参考资料3:

http://docs.opencv.org/3.3.0/d9/dc8/tutorial_py_trackbar.html

4、思考

调色板和控制条布局怎么控制?

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: