import numpy as np
import cv2
# 空函数
def nothing(x):
pass
# 创建图像
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')
# 为彩色图像创建trackbar
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)
if cv2.waitKey(2) & 0xFF == 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()
int cv::createTrackbar ( const String & trackbarname,
const String & winname,
int * value,
int count,
TrackbarCallback onChange = 0,
void * userdata = 0
);
// # 返回trackbar的位置
int cv::getTrackbarPos ( const String & trackbarname,
const String & winname
);
cv2.createTrackbar(trackbarName, windowName, value, count, onChange) -> None
# 返回trackbar的位置
cv2.getTrackbarPos(trackbarname, winname) -> retval
参数
做一个简单的画图程序,可以改变画笔的颜色和粗细。
SHOW ME THE CODE
import numpy as np
import cv2
# 创建图像
img = np.zeros((400, 800, 3), np.uint8)
cv2.namedWindow('image')
r, g, b = 0, 0, 0
c = 0
ix,iy = -1,-1
drawing = False
thickness = -1
# 鼠标的回调函数
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, r, g, b, c, thickness
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.circle(param, (x, y), 5, (b, g, r), thickness)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
cv2.circle(param, (x, y), 5, (b, g, r), thickness)
# 空函数
def nothing(x):
pass
# 为彩色图像创建trackbar
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
cv2.createTrackbar('clear', 'image', 0, 1, nothing)
cv2.createTrackbar('thickness', 'image', 0, 30, nothing)
# 设置鼠标事件
cv2.setMouseCallback('image', draw_circle, img)
while (1):
cv2.imshow('image', img)
if cv2.waitKey(2) & 0xFF == 27:
break
# 获取当前位置值
r = cv2.getTrackbarPos('R', 'image')
g = cv2.getTrackbarPos('G', 'image')
b = cv2.getTrackbarPos('B', 'image')
c = cv2.getTrackbarPos('clear', 'image')
thickness = cv2.getTrackbarPos('thickness', 'image')
# 清空画布
if c == 0:
img[:] = 0
cv2.destroyAllWindows()