| import cv2
|
| import numpy as np
|
| import math
|
|
|
|
|
| class Canvas:
|
|
|
| def __init__(self, width, height):
|
|
|
| self.width = width
|
| self.height = height
|
|
|
| self.canvas = np.zeros((height, width, 3), dtype=np.uint8)
|
|
|
| self.prev_point = None
|
| self.color = (255, 255, 255)
|
| self.thickness = 6
|
|
|
| def set_color(self, color):
|
| self.color = color
|
|
|
| def lift(self):
|
|
|
| self.prev_point = None
|
|
|
| def clear(self):
|
| self.canvas = np.zeros((self.height, self.width, 3), dtype=np.uint8)
|
| self.prev_point = None
|
|
|
| def draw(self, point, erase=False):
|
|
|
| if point is None:
|
| self.prev_point = None
|
| return
|
|
|
| if self.prev_point is None:
|
| self.prev_point = point
|
| return
|
|
|
|
|
| if erase:
|
| draw_color = (0, 0, 0)
|
| thickness = 30
|
| else:
|
| draw_color = self.color
|
| thickness = self.thickness
|
|
|
| x1, y1 = self.prev_point
|
| x2, y2 = point
|
|
|
|
|
| distance = math.hypot(x2 - x1, y2 - y1)
|
|
|
| if distance > 0:
|
| steps = int(distance / 2)
|
|
|
| for i in range(steps):
|
| t = i / steps
|
| xi = int(x1 + (x2 - x1) * t)
|
| yi = int(y1 + (y2 - y1) * t)
|
|
|
| cv2.circle(
|
| self.canvas,
|
| (xi, yi),
|
| thickness // 2,
|
| draw_color,
|
| -1,
|
| cv2.LINE_AA
|
| )
|
|
|
|
|
| cv2.line(
|
| self.canvas,
|
| self.prev_point,
|
| point,
|
| draw_color,
|
| thickness,
|
| cv2.LINE_AA
|
| )
|
|
|
| self.prev_point = point
|
|
|