長方形の落書きスケッチパッド

勉強する時間があれば、今のところ保存してください

次の機能を実現するために、長方形の落書き画板を作成します。

ここに画像の説明を挿入

マウスの左ボタンを押してドラッグし、長方形を描画します。マウスの左ボタンがポップアップして描画が完了したら、
「c」キーを
押してアートボードをクリアします。「ESC」キーを押して終了します。

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()

おすすめ

転載: blog.csdn.net/qq_42102546/article/details/123166985