最近在学习OpenCV,照着官网的教程学习,学习Gui Features in Opencv,其中主要内容参考这一章节的内容,鼠标事件部分对应前一章的学习内容,链接如下:opencv官网教程
看本博客内容基本就可以实现这个章节内容,如果还有问题可以下载链接:源程序
这一节主要实现的功能是,利用Trackbar相关命令,实现功能如下:
#create a white image, a window
img = 255*np.ones((350,512,3),np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_mousepush)
#create trackbars for color change,switch of erase,painter thickness
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,8,nothing)
switch = 'erase'
cv.createTrackbar(switch,'image',0,1,nothing)
#get info painter function
def get_painter():
# get current positions of four trackbars
r = cv.getTrackbarPos('R', 'image')
g = cv.getTrackbarPos('G', 'image')
b = cv.getTrackbarPos('B', 'image')
thickness = cv.getTrackbarPos('thickness','image')
s = cv.getTrackbarPos(switch,'image')
color = (b,g,r) #color scales
return color,thickness,s
# mouse callback function
#initialize初始化
drawing = False #painter is false,not beginning painting
mode = False #切换画线和画矩形功能
ix, iy = 0, 0
def draw_mousepush(event,x,y,flags,param):
global ix,iy,drawing,mode #引入全局变量
color,thickness,s = get_painter() #从get_painter函数引入参数
# moniter mouse event.When push leftbutton down,beginning painting
if event == cv.EVENT_LBUTTONDOWN:
drawing = True
ix, iy = x, y
#按住左键滑动,则开始在鼠标所在位置画圆,从而连成曲线
elif event == cv.EVENT_MOUSEMOVE and flags == cv.EVENT_FLAG_LBUTTON:
if drawing == True:
if s == 1: #打开橡皮擦功能
cv.circle(img,(x,y),10,(255,255,255),-1)
else:
if mode == False: #画线
cv.circle(img,(x,y),thickness,color,-1)
else:
cv.rectangle(img,(ix,iy),(x,y),color,-1)
elif event == cv.EVENT_LBUTTONUP:
drawing = False
# main function
while(1):
color,thickness,_ = get_painter()
cv.imshow('image',img)
k = cv.waitKey(1) & 0xFF
if k ==27: #ESC退出
break
elif k == ord('m'):
mode = not mode
cv.destroyAllWindows()