OpenCV
鼠标事件
- 创建窗口
- 设置窗口大小
- 鼠标事件监听
- 打开背景图
"""
鼠标事件
down
up
move
"""
import cv2
import numpy as np
WINNAME = 'DRAWBOARD'
st_point = (-1, -1)
end_point = (-1, -1)
def drawLine(event, x, y, flags, param):
global st_point, end_point
img_copy = bg_img.copy()
if event == cv2.EVENT_LBUTTONDOWN:
print('EVENT_LBUTTONDOWN', event, x, y, flags, param)
st_point = (x, y)
if event == cv2.EVENT_MOUSEMOVE and flags:
end_point = (x, y)
cv2.line(img_copy, st_point, end_point, color=(0, 0, 255), thickness=2)
cv2.imshow(WINNAME, img_copy)
if event == cv2.EVENT_LBUTTONUP:
print('EVENT_LBUTTONUP', event, x, y, flags, param)
end_point = (x, y)
cv2.line(bg_img, st_point, end_point, color=(0, 0, 255), thickness=2)
cv2.imshow(WINNAME, bg_img)
def drawRectangle(event, x, y, flags, param):
global st_point, end_point
img_copy = bg_img.copy()
if event == cv2.EVENT_LBUTTONDOWN:
print('EVENT_LBUTTONDOWN', event, x, y, flags, param)
st_point = (x, y)
if event == cv2.EVENT_MOUSEMOVE and flags:
end_point = (x, y)
cv2.rectangle(img_copy, st_point, end_point, color=(0, 0, 255), thickness=2)
cv2.imshow(WINNAME, img_copy)
if event == cv2.EVENT_LBUTTONUP:
print('EVENT_LBUTTONUP', event, x, y, flags, param)
end_point = (x, y)
cv2.rectangle(bg_img, st_point, end_point, color=(0, 0, 255), thickness=2)
cv2.imshow(WINNAME, bg_img)
def drawPolylines(event, x, y, flags, param):
global st_point, end_point
if event == cv2.EVENT_LBUTTONDOWN:
print('EVENT_LBUTTONDOWN', event, x, y, flags, param)
st_point = (x, y)
end_point = st_point
if event == cv2.EVENT_MOUSEMOVE and flags:
last_x, last_y = st_point, end_point
st_point = end_point
end_point = (x, y)
print('EVENT_MOUSEMOVE', event, x, y, flags, param)
pts = np.array([last_x, last_y, st_point, end_point])
cv2.polylines(bg_img, [pts], isClosed=False, color=(0, 0, 255), thickness=2)
cv2.imshow(WINNAME, bg_img)
if event == cv2.EVENT_LBUTTONUP:
print('EVENT_LBUTTONUP', event, x, y, flags, param)
last_x, last_y = st_point, end_point
st_point = end_point
end_point = (x, y)
pts = np.array([last_x, last_y, st_point, end_point])
cv2.polylines(bg_img, [pts], isClosed=False, color=(0, 0, 255), thickness=2)
cv2.imshow(WINNAME, bg_img)
def callBack(event, x, y, flags, param):
drawPolylines(event, x, y, flags, param)
if __name__ == '__main__':
cv2.namedWindow(WINNAME, cv2.WINDOW_NORMAL)
cv2.resizeWindow(WINNAME, 360, 360)
cv2.setMouseCallback(WINNAME, callBack, param='hello')
bg_img = cv2.imread('snower.jpg')
cv2.imshow(WINNAME, bg_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
鼠标绘制直线
鼠标绘制矩形
鼠标绘制曲线