1.问题背景
opencv 官方手册 文档 练习题
使用轨迹栏创建颜色和画笔半径可调的Paint应用程序。有关绘制的信息,请参阅有关鼠标处 理的先前教程。
2.代码部分
另外一个官方demo留下的作业,代码难以精美,请理解。
import numpy as np
import cv2 as cv
# 鼠标回调函数
def draw_circle(event, x, y,thick,param):
global ix, iy, drawing, mode,color,thicness
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
elif event == cv.EVENT_MOUSEMOVE:
if drawing == True:
cv.circle(img, (x, y), thicness, color, -1,cv.LINE_AA )
elif event == cv.EVENT_LBUTTONUP:
drawing = False
cv.circle(img, (x, y), thicness, color, -1,cv.LINE_AA )
def nothing(x):
pass
# 创建一个的图像,一个窗口
img = np.full((300, 512, 3), 255, np.uint8)
cv.namedWindow('image')
cv.imshow('image', img)
# 创建颜色变化的轨迹栏
cv.createTrackbar('R', 'image', 0, 255, nothing)
cv.createTrackbar('G', 'image', 0, 255, nothing)
cv.createTrackbar('B', 'image', 0, 255, nothing)
cv.createTrackbar('Thickness', 'image', 1, 10, nothing)
color=[0,0,0]
drawing = False
thicness=5
cv.setMouseCallback('image', draw_circle,(0,0,0))
#cv.SetMouseCallback(windowName, onMouse, param=None) → None
while (1):
cv.imshow('image', img)
k = cv.waitKey(1) & 0xFF
if k == 27:
break
# 得到四条轨迹的当前位置
r = cv.getTrackbarPos('R', 'image')
g = cv.getTrackbarPos('G', 'image')
b = cv.getTrackbarPos('B', 'image')
thicness=cv.getTrackbarPos('Thickness', 'image')
color=[b,g,r]
cv.destroyAllWindows()
3.运行效果