python - 使用 Matplotlib 在 Python 中使用鼠标在图像上绘制点

标签 python matplotlib plot mouse

我正在尝试使用鼠标在图像上绘制点。 问题:图像出现,但是当我单击鼠标时,没有绘制任何内容(即使我单击几次)。

我的 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) 

最佳答案

tcaswell 评论的回答:

将 self.axes.figure.canvas.draw_idle() 调用添加到回调中。

关于python - 使用 Matplotlib 在 Python 中使用鼠标在图像上绘制点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33370613/

相关文章:

python - 在 Python 中一次打印文件中的字母 3 个字母

Python绘图强制按字母顺序而不是按时间顺序对日期进行排序

matlab - 内部和外部颜色不同的表面绘图

python - 将 2 个不同年份的 .resample(D).size() 绘制到一张图表中?

线程 : can't start new thread 中的 Python 异常

python - 分析日期并每月打印下一个日期

Python - 没有网格、刻度标签和外主圆(边界)的极坐标图

python - 谷歌 Colabs Notebook 中保存的图像与本地计算机中保存的图像不同

r - 将相关矩阵图形保存为 PDF

python - 用 numpy/python 推断数据