在图像上点击鼠标点击

时间:2017-01-02 13:51:12

标签: python-3.x matplotlib plot

我在Python 3中编写代码以在DICOM图像上绘制一些标记。为此,我写了一个很短的程序:

在主程序中,我从终端读取DICOM文件名并绘制图像。

main_prog.py:

import sys
import dicom as dcm
import numpy as np
from   matplotlib import pyplot as plt
from   dicomplot import dicomplot as dcmplot

filename  = sys.argv[1]
dicomfile = dcm.read_file(filename)
dicomimg  = dicomfile.pixel_array

fig = plt.figure(dpi = 300)
ax  = fig.add_subplot(1, 1, 1)
plt.set_cmap(plt.gray())
plt.pcolormesh(np.flipud(dicomimg))
dcm  = dcmplot(ax)

plt.show()

然后,我定义了一个类来存储用户点击的坐标,并在图像上一次绘制每个坐标:

dicomplot.py

from   matplotlib import pyplot as plt

class dicomplot():
    def __init__(self, img):
        self.img    = img
        self.fig    = plt.figure(dpi = 300)
        self.xcoord = list()
        self.ycoord = list()
        self.cid    = img.figure.canvas.mpl_connect('button_press_event', self)

    def __call__(self, event):
        if event.button == 1:
            self.xcoord.append(event.x)
            self.ycoord.append(event.y)
            self.img.plot(self.ycoord, self.xcoord, 'r*')
            self.img.figure.canvas.draw()
        elif event.button == 2:
            self.img.figure.canvas.mpl_disconnect(self.cid)
        elif event.button == 3:
            self.xcoord.append(-1)
            self.ycoord.append(-1)

问题在于,当我点击图像时,标记会以不同的比例显示,而不是按原样显示在图像上。

如何修改我的代码,以便点击图片时,所有鼠标点击都会被存储并绘制到所需的位置?

1 个答案:

答案 0 :(得分:1)

MouseEvent个对象带有x / yxdata / ydata属性(docs)。第一组是屏幕坐标(左下角的前像素),第二组(*data)位于数据坐标中。

您可能也对mpldatacursor感兴趣。