opencv_python学习笔记五
7把鼠标当画笔
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/11/14 9:42
# @Author : Retacn
# @Site : 处理鼠标事件
# @File : mouseDraw.py
# @Software: PyCharm
import cv2
events=[i for i
in dir(cv2)
if 'EVENT'
in i]
print(events)
['EVENT_FLAG_ALTKEY', 'EVENT_FLAG_CTRLKEY', 'EVENT_FLAG_LBUTTON', 'EVENT_FLAG_MBUTTON', 'EVENT_FLAG_RBUTTON', 'EVENT_FLAG_SHIFTKEY', 'EVENT_LBUTTONDBLCLK', 'EVENT_LBUTTONDOWN', 'EVENT_LBUTTONUP', 'EVENT_MBUTTONDBLCLK', 'EVENT_MBUTTONDOWN', 'EVENT_MBUTTONUP', 'EVENT_MOUSEHWHEEL', 'EVENT_MOUSEMOVE', 'EVENT_MOUSEWHEEL', 'EVENT_RBUTTONDBLCLK', 'EVENT_RBUTTONDOWN', 'EVENT_RBUTTONUP']
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/11/14 9:42
# @Author : Retacn
# @Site : 处理鼠标事件,双击画圆
# @File : mouseDraw.py
# @Software: PyCharm
import cv2
import numpy as
np
#events=[i for i in dir(cv2) if 'EVENT' in i]
#print(events)
#鼠标事件回调函数
def draw_circle(event,x,y,flags,param):
if event==cv2.EVENT_LBUTTONDBLCLK:
cv2.circle(img,(x,y),100,(255,0,0),-1)
#创建图像与窗口
#将窗口和回调函数邦定
img=np.zeros((512,512,3),np.uint8)
cv2.namedWindow("Mouse_draw")
cv2.setMouseCallback("Mouse_draw",draw_circle)
while(1):
cv2.imshow("Mouse_draw",img)
if cv2.waitKey(20)&0xFF==27:
break;
cv2.destroyAllWindows()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2016/11/14 9:55
# @Author : Retacn
# @Site : 根据选择在拖动时画矩形或是画圆
# @File : mouseDraw2.py
# @Software: PyCharm
import cv2
import numpy as
np
# 当鼠标按下的为true
drawing = False
# 如果mode为true绘制矩形,按下m
绘制曲线
mode = True
lx, ly = -1, -1
# 回调函数
def draw_circle(event, x, y, flags,
param):
global lx, ly, drawing, mode
# 当按下左健时返回起始位置坐标
if
event == cv2.EVENT_LBUTTONDOWN:
drawing = True
lx, ly = x, y
# 当左健按下并移动是绘制图形,event(移动),flag(是否按下)
elif
event == cv2.EVENT_MOUSEMOVE and
flags == cv2.EVENT_FLAG_LBUTTON:
if drawing ==
True:
if mode ==
True:
cv2.rectangle(img, (lx, ly), (x, y), (0,
255, 0), -1)
else:
# 绘制圆
cv2.circle(img, (x, y),
3, (0,
0, 255), -1)
# 当鼠标放开停止
elif
event == cv2.EVENT_LBUTTONUP:
drawing = False
img = np.zeros((512,
512, 3), np.uint8)
cv2.namedWindow("Mouse_draw2")
cv2.setMouseCallback('Mouse_draw2', draw_circle)
while (1):
cv2.imshow('Mouse_draw2', img)
k = cv2.waitKey(1) &
0xFF
if
k == ord('m'):
mode = not mode
elif k ==
27:
break