簡體   English   中英

使用Matplotlib在Python中使用鼠標在圖像上繪制點

[英]Using mouse to plot points on image in Python, with Matplotlib

我正在嘗試使用鼠標在圖像上繪制點。 問題:出現了圖像,但是當我單擊鼠標時,沒有繪制任何內容(即使我單擊了幾次)。

我的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()調用添加到回調中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM