Save it for now, if you have time to study
Write a rectangular graffiti drawing board to achieve the function:
Press and drag the left mouse button to draw a rectangle, when the left mouse button pops up to complete the drawing
Press the 'c' key to clear the artboard
Press the 'ESC' key to exit
import numpy as np
import cv2 as cv
from random import randint
class Painter:
def __init__(self) -> None:
self.mouse_is_pressed = False
self.last_pos = (-1, -1)
self.width = 500
self.height = 500
self.img = np.zeros((self.width, self.height, 3), np.uint8)
self.window_name = 'painter'
self.color = None
def run(self):
print('画板,拖动鼠标绘制矩形框,按ESC退出,按c键清空画板')
# 框随意变大小
cv.namedWindow(self.window_name)
# 鼠标响应
cv.setMouseCallback(
self.window_name,
lambda event, x, y, flags, param: self.on_draw(
event, x, y, flags, param
)
)
while True:
cv.imshow(self.window_name, self.img)
k = cv.waitKey(1) & 0xFF
if k == ord('c'):
self.clean()
elif k == 27:
break
cv.destroyAllWindows()
def on_draw(self, event, x, y, flags, param):
# TODO(You): 请正确实现画板事件响应,完成功能
pos = (x, y)
if event == cv.EVENT_LBUTTONDOWN:
self.mouse_is_pressed = True
self.last_pos = pos
elif event == cv.EVENT_MOUSEMOVE:
if self.mouse_is_pressed == True:
self.begin_draw_rectangle(self.last_pos, pos)
elif event == cv.EVENT_LBUTTONUP:
self.end_draw_rectangle(self.last_pos, pos)
self.mouse_is_pressed = False
def clean(self):
cv.rectangle(self.img, (0, 0), (self.height, self.width), (0, 0, 0), -1)
def begin_draw_rectangle(self, pos1, pos2):
if self.color is None:
self.color = (randint(0, 256), randint(0, 256), randint(0, 256))
cv.rectangle(self.img, pos1, pos2, self.color, -1)
def end_draw_rectangle(self, pos1, pos2):
self.color = None
if __name__ == '__main__':
p = Painter()
p.run()