Skip to content

Instantly share code, notes, and snippets.

@cwindolf
Last active April 1, 2020 16:19
Show Gist options
  • Save cwindolf/0221c5d83e42cbb14c00d582774db7a7 to your computer and use it in GitHub Desktop.
Save cwindolf/0221c5d83e42cbb14c00d582774db7a7 to your computer and use it in GitHub Desktop.
You just wanna draw a black and white image into an array real quick
import numpy as np
import matplotlib.pyplot as plt
class bwdrawer:
"""Draw one pixel at a time on a black and white canvas.
Usage (in a script or a repl):
```
drawer = bwdrawer(my_width, my_height)
# click and drag to draw on the figure canvas
# pyplot will block until you X out the window
result = drawer.canvas # this is your np.uint8 array
```
"""
def __init__(self, w, h):
self.pen = False
self.canvas = np.zeros((h, w), dtype=np.uint8)
self.fig, self.ax = plt.subplots(1, 1)
self.im = None
self.hardreset()
self.fig.canvas.mpl_connect("button_press_event", self.down)
self.fig.canvas.mpl_connect("button_release_event", self.up)
self.fig.canvas.mpl_connect("motion_notify_event", self.move)
plt.show(block=True)
def hardreset(self):
self.im = self.ax.imshow(self.canvas, cmap="binary", vmin=0, vmax=1)
self.fig.canvas.draw()
def update(self):
self.im.set_data(self.canvas)
self.fig.canvas.draw()
def down(self, event):
self.pen = True
y, x = int(np.floor(event.ydata)), int(np.floor(event.xdata))
self.canvas[y, x] = 1
self.update()
def up(self, _):
self.pen = False
def move(self, event):
if self.pen:
y, x = int(np.floor(event.ydata)), int(np.floor(event.xdata))
self.canvas[y, x] = 1
self.update()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment