彩蛋
实现轨迹条控制画笔颜色和笔刷半径,并可以正常绘画。
直接上彩蛋代码
示例代码:
# 彩蛋,创建一个可以调节颜色和笔刷半径的轨迹栏,并且可以通过鼠标进行绘画
import numpy as np
import cv2 as cv
# 定义全局变量
# 如果 True 是鼠标按下
drawing = True
# 如果 True,画矩形,按下‘m’切换到曲线
mode = True
# 笔刷半径,默认是1
radius_of_brush = 1
# 笔刷颜色
b, g, r = 0, 0, 0
def nothing(x):
pass
# 鼠标回调函数
def draw_circle(event, x, y, flags, param):
global ix, iy, drawing, mode, radius_of_brush, b, g, r
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
elif event == cv.EVENT_MOUSEMOVE:
if drawing:
cv.circle(img, (x, y), radius_of_brush, (b, g, r), -1)
elif event == cv.EVENT_LBUTTONUP:
drawing = False
# 创建一个黑色图像,一个窗口
img = np.zeros((300, 512, 3), np.uint8)
cv.namedWindow('image')
# 绑定鼠标回调函数
cv.setMouseCallback('image', draw_circle)
# 创建一个改变颜色的轨迹栏
cv.createTrackbar('R', 'image', 0, 255, nothing)
cv.createTrackbar('G', 'image', 0, 255, nothing)
cv.createTrackbar('B', 'image', 0, 255, nothing)
# 创建一个用来调整笔刷半径的轨迹栏
switch2 = 'radius_of_brush'
cv.createTrackbar(switch2, 'image', 1, 50, nothing)
while 1:
cv.imshow('image', img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
# get current positions of four trackbars
r = cv.getTrackbarPos('R', 'image')
g = cv.getTrackbarPos('G', 'image')
b = cv.getTrackbarPos('B', 'image')
radius_of_brush = cv.getTrackbarPos(switch2, 'image')
cv.destroyAllWindows()
效果图: