本文关于鼠标绘画,事件捕捉,以及刻度条控制。
左键画圆
import numpy as np
import cv2
def call_back_func(event,x,y,flags,param):
#flags: Any relevant flags passed by OpenCV.一般为1表示正确
#params: Any extra parameters supplied by OpenCV.传递的参数
if event==cv2.EVENT_LBUTTONDOWN:
#print(flags,param)
cv2.circle(img,(x+71,y+71),100,(0,255,0),1)
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('hello4')
#cv2.setMouseCallback('hello4',call_back_func,['he'])
cv2.setMouseCallback('hello4',call_back_func)
while True:
cv2.imshow("hello4",img)
if cv2.waitKey(20)==27:#20ms刷新
break
cv2.destroyAllWindows()
画曲线
import cv2
import numpy as np
drawing = False #是否在画
ix,iy = -1,-1#临时坐标,记录位置
def draw_lines(event,x,y,flags,param):
global ix,iy,drawing
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
ix,iy = x,y#开始画的坐标
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
cv2.line(img,(ix,iy),(x,y),(0,255,0),1)#红色
ix,iy=x,y#1111处
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
img = np.zeros((300,300,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_lines)
while(1):
cv2.imshow('image',img)
if cv2.waitKey(1) == 27:#esc退出
break
cv2.destroyAllWindows()
#1111处代码是否注释如下图。
画刷新的矩形
即在鼠标拖动过程中矩形一直在重绘,知道鼠标抬起一个矩形才算完成。
import cv2
import numpy as np
import copy
drawing = False #是否在画
rectx,recty=-1,-1#矩形初始位置
imgtemp=0#原画纸
def draw_rects(event,x,y,flags,param):
global drawing,rectx,recty,imgtemp,img
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
imgtemp=copy.deepcopy(img)#深拷贝
rectx,recty=x,y
# print("LBUTTONDOWN")
elif event == cv2.EVENT_MOUSEMOVE:
if drawing == True:
img = copy.deepcopy(imgtemp)
cv2.rectangle(img,(rectx,recty),(x,y),(0,255,0),1)#红色
# print("MOUSEMOVE")
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
img = np.zeros((300,300,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_rects)
while(1):
cv2.imshow('image',img)
if cv2.waitKey(1) == 27:#esc退出
break
cv2.destroyAllWindows()
使用刻度条
import cv2
import numpy as np
def nothing(x):#回调函数
pass
img = np.zeros((300,512,3), np.uint8)#300行,512列,3维,不包括刻度条
cv2.namedWindow('image')
cv2.createTrackbar('R','image',0,255,nothing)#创建刻度条
#五个参数分别为刻度条标签,窗口名,刻度默认值,刻度最大值,刻度变化时回调函数,该实例在窗口重绘时根据刻度值改变颜色,所以回调函数什么也不做
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
cv2.createTrackbar("switch", 'image',0,1,nothing)#当做按钮或者开关
print(len(img[0]))
while(1):
cv2.imshow('image',img)
if cv2.waitKey(1) == 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()