轨迹栏
-
- [4. OpenCV轨迹栏](#4. OpenCV轨迹栏)
-
- [4.1 轨迹栏作为调色板](#4.1 轨迹栏作为调色板)
- [4.2 轨迹栏显示不同通道图像](#4.2 轨迹栏显示不同通道图像)
4. OpenCV轨迹栏
会用到以下主要两个函数
cv2.createTrackbar(trackbarName, windowName, value, count, onChange)
创建轨迹栏
主要参数:
- trackbarName:轨迹栏名称
- windowName:附加到的窗口名称
- value:默认值
- count:最大值
- onChange:执行的回调函数每次跟踪栏值更改,下面例子函数什么都不做
getTrackbarPos(trackbarname, winname)
获取轨迹栏的位置
- trackbarname:轨迹栏名称
- winname:附加到的窗口名称
4.1 轨迹栏作为调色板
创建一个黑色图像,通过轨迹栏改变BGR三通道值来显示不同颜色
python
import numpy as np
import cv2
def nothing(x):
pass
# 创建一个黑色的图像,一个窗口
img = np.zeros((512, 512, 3), np.uint8)
cv2.namedWindow('image')
# 创建颜色变化的轨迹栏
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
# 为 ON/OFF 功能创建开关
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
# 得到四条轨迹的当前位置
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()
4.2 轨迹栏显示不同通道图像
OpenCV读取的是BGR形式,通过轨迹栏可以显示不同通道的图像,例如:只有R单通道的图像、将两通道合并的图像、将三通道合并为原图像。
- split(): 通道分离,
(b, g, r)
形式 - merge() :通道合并,输入1通道或者3通道
python
import numpy as np
import cv2
def nothing(x):
pass
# 将选择的通道设置为零矩阵,不显示
def zeros_channels(channel):
zeros = np.zeros_like(channel)
return zeros
img = cv2.imread('lena.jpg')
# 将3通道分离
b, g, r = cv2.split(img)
cv2.namedWindow('image')
# 创建三通道开关的轨迹栏
switch_r = 'R_channel'
cv2.createTrackbar(switch_r, 'image', 0, 1, nothing)
switch_g = 'G_channel'
cv2.createTrackbar(switch_g, 'image', 0, 1, nothing)
switch_b = 'B_channel'
cv2.createTrackbar(switch_b, 'image', 0, 1, nothing)
while (1):
cv2.imshow('image', img)
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# 得到三条轨迹的当前位置
s_r = cv2.getTrackbarPos(switch_r, 'image')
s_g = cv2.getTrackbarPos(switch_g, 'image')
s_b = cv2.getTrackbarPos(switch_b, 'image')
if s_r == 1:
if s_g == 1:
if s_b == 1:
img = cv2.merge([b, g, r]) # 对通道按照BGR的顺序合并生成图像bgr
else:
img = cv2.merge([zeros_channels(b), g, r]) # 不显示b通道
else:
if s_b == 1:
img = cv2.merge([b, zeros_channels(g), r]) # 对通道按照BGR的顺序合并生成图像bgr
else:
img = cv2.merge([zeros_channels(b), zeros_channels(g), r]) # 不显示b, g通道
else:
if s_g == 1:
if s_b == 1:
img = cv2.merge([b, g, zeros_channels(r)]) # 对通道按照BGR的顺序合并生成图像bgr
else:
img = cv2.merge([zeros_channels(b), g, zeros_channels(r)]) # 不显示b, r通道
else:
if s_b == 1:
img = cv2.merge([b, zeros_channels(g), zeros_channels(r)]) # 对通道按照BGR的顺序合并生成图像bgr
else:
img = cv2.merge([zeros_channels(b), zeros_channels(g), zeros_channels(r)]) # 不显示b, g, r通道
cv2.destroyAllWindows()