2017-01-02 171 views
1

我在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

MouseEvent对象同时携带x/yxdata/ydata属性(docs)。第一组是在屏幕坐标(左下角的像素)和第二组(*data)在数据坐标中。您可能也有兴趣mpldatacursor