In [1]:
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import matplotlib.image as io
# magic to get interactive pyplot window in notebook
%matplotlib notebook
In [2]:
"""
Annotator class to wrap pyplot mouse events and save clicked points
"""
class Annotator(object):
def __init__(self, plt):
self.xdata = []
self.ydata = []
self.points = []
self.plt = plt
def _draw_lines(self):
self.plt.plot(self.xdata, self.ydata, color='r', linestyle='-', linewidth=2)
self.plt.draw()
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
self._draw_lines()
def mouse_release(self, event):
pass
def mouse_click(self, event):
x, y = event.xdata, event.ydata
if event.button == 1: # left click
self.xdata.append(x)
self.ydata.append(y)
self.points.append((x,y))
elif event.button == 3: # right click
self.xdata = []
self.ydata = []
self.points = []
self.plt.cla()
self.plt.imshow(self.img)# re-render image
self._draw_lines()
self.plt.draw()
def start(self, img):
self.img = img
# connect some pyplot mouse events to our class methods
self.plt.connect('motion_notify_event', self.mouse_move)
self.plt.connect('button_release_event', self.mouse_release)
self.plt.connect('button_press_event', self.mouse_click)
self.xdata = []
self.ydata = []
self.plt.imshow(self.img)
self.plt.show()
In [3]:
img = io.imread('lena.jpg')
annotator = Annotator(plt) #create an annotator
annotator.start(img)# start the annotator on image
# controls:
# left-click: add point
# right-click: delete all points
# NOTE: to stop annotating, click the "power" button above image on the right.
In [5]:
# get points from annotator instance.
pnts = annotator.points
for pnt in pnts:
print(pnt)