我正在尝试使用鼠标在图像上绘制点。 问题:图像出现,但是当我点击鼠标时,没有绘制任何内容(即使我点击了几次)。
我的Python版本是Python 2.7,带有Anaconda和IPython控制台。 我在运行脚本之前在Ipython控制台中键入%pylab。
这是我的代码:
import numpy as np
from matplotlib import pyplot as plt
#Some code here [. . .]
fig, ax = plt.subplots(1)
ax.imshow(img, interpolation = 'bicubic')
'''preventing plot from rescaling image:'''
ax.set_xlim([0.0, img.shape[1]])
ax.set_ylim([img.shape[0], 0.0])
ax.hold(True)
ax.autoscale = False
#ax.plot(100,100, 'ro') # This works
class MouseMonitor:
flag = True
x = 0.
y = 0.
fig = None
axes = None
def __init__(self, fig, ax):
self.axes = ax
self.fig = fig
def __call__(self, event):
if self.flag:
print('({}, {})'.format(event.xdata, event.ydata))
self.flag = False
else:
d = np.linalg.norm([event.xdata - self.x, event.ydata - self.y])
print('({}, {})\n\n distance between points: {} m\n\n-------------------\n'.format(event.xdata, event.ydata, d))
self.flag = True
self.x = event.xdata
self.y = event.ydata
self.axes.plot(self.y, self.x, 'ro', linewidth = 5) #This don't work
mouse = MouseMonitor(fig, ax)
cid = fig.canvas.mpl_connect('button_press_event', mouse)
答案 0 :(得分:1)
来自tcaswell评论的答案:
将self.axes.figure.canvas.draw_idle()调用添加到回调中。