import cv2
import numpy as np
drawing, start_x, start_y = False, -1, -1
prev_point = None # 上一个点
history = list()
def draw_box(points, color=(0, 255, 0), thickness=1):
if points:
p1, p2 = points
top_left, top_right, bottom_right, bottom_left = p1, (
p2[0], p1[1]), p2, (p1[0], p2[1])
cv2.line(mask, top_left, top_right, color, thickness) # 上边
cv2.line(mask, top_right, bottom_right, color, thickness) # 右边
cv2.line(mask, bottom_right, bottom_left, color, thickness) # 下边
cv2.line(mask, bottom_left, top_left, color, thickness) # 左边
def mouse_event(event, x, y, flags, param):
"""
鼠标的回调函数
"""
global drawing, start_x, start_y, prev_point
points = ((start_x, start_y), (x, y))
# 通过 event 判断具体是什么事件,这里是左键按下
if event == cv2.EVENT_LBUTTONDOWN:
drawing = True
start_x, start_y = x, y
prev_point = None
# 鼠标移动,画图
elif event == cv2.EVENT_MOUSEMOVE:
if drawing:
# 清除拖动的框
draw_box(prev_point, color=(0, 0, 0))
# 画框
draw_box(points)
prev_point = points
elif event == cv2.EVENT_LBUTTONUP:
drawing = False
draw_box(prev_point, color=(0, 0, 0))
draw_box(points)
history.append(points)
prev_point = points
img = cv2.imread("background.jpg")
cv2.namedWindow('image')
# 定义鼠标的回调函数
cv2.setMouseCallback('image', mouse_event)
# 创建掩码,在掩码上画线
mask = np.zeros_like(img)
while True:
cv2.imshow('image', cv2.bitwise_or(img, mask))
# 按下 ESC 键退出
if cv2.waitKey(20) == 27 or cv2.waitKey(20) == ord('q'):
break
elif cv2.waitKey(20) == ord('z'):
if history:
draw_box(history.pop(), color=(0, 0, 0))
for points in history:
print(points)
标签:start,color,point,cv2,标出,opencv,points,画框,event
From: https://www.cnblogs.com/ccqk/p/18423250