鼠标事件的返回值
在鼠标左键双击之处画圆圈的代码
import cv2
from cv2 import EVENT_LBUTTONUP
import numpy as np
# 鼠标左键双击之处画个圈圈
def draw_circle(event,x,y,flags,param): #不知道flags和param参数意义
if event == cv2.EVENT_LBUTTONDBLCLK: #left botton double click
cv2.circle(img,(x,y),100,(255,0,0),-1)
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle) #鼠标响应
while(1):
cv2.imshow('image',img)
if cv2.waitKey(20) & 0xff == 27:
break
cv2.destroyAllWindows()
Trackbar 滑动条
首先设立一个窗口,然后把trackbar放在窗口里
cv2.createTrackbar('滑动条名称`,windows,origin_value,maximun,function)
其中function为响应函数,可以设置一个什么都不做的函数。
返回滑动条的值num = cv2.getTrackbarPos(滑动条名称,windows)
以下代码为按下左键画图:
#按住鼠标左键来绘制图像,松开回到原点。点击键盘m更改绘图模式(圈圈或rectangle)
drawing = False #鼠标按下时为True
mode = True # 1为cycle,0为rec
ix,iy = -1,-1
def nothing():
pass
cv2.namedWindow("image")
cv2.createTrackbar('R',"image",0,255,nothing)
cv2.createTrackbar('G',"image",0,255,nothing)
cv2.createTrackbar('B',"image",0,255,nothing)
def draw_picture(event,x,y,flags,param):
global ix,iy,drawing,mode #if edit value in function , use global
r = cv2.getTrackbarPos("R","image")
g = cv2.getTrackbarPos("G","image")
b = cv2.getTrackbarPos("B","image")
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y #rectangle 要用到
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON: #event看鼠标是否移动,flags看是否按下
if drawing == True:
if mode == True:
cv2.circle(img,(x,y),3,(b,g,r),-1)
else:
cv2.rectangle(img,(ix,iy),(x,y),(b,g,r),-1)
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
img = np.zeros((512,512,3),np.uint8)
cv2.setMouseCallback("image",draw_picture)
while(1):
cv2.imshow("image",img)
k = cv2.waitKey(1)&0xff
if k ==ord('m'):
mode = not mode
elif k ==27:
break