【问题标题】:Returning an incorrect variable from method从方法返回不正确的变量
【发布时间】:2017-06-13 14:41:04
【问题描述】:

当我尝试从一个方法返回一个数组时,我得到了一个有线行为,代码如下:

import matplotlib.pyplot as plt
import numpy as np
import sys

class ClickAndRoi:
    def __init__(self, fig = [], ax = []):

        self.selected_pixel = []              
        if fig == []:
            fig = plt.gcf()
        if ax == []:
            ax = plt.gca()

        self.fig = fig
        self.ax = ax
        self._ID1 = self.fig.canvas.mpl_connect('button_press_event', self._onclick)
        plt.waitforbuttonpress()

        if sys.flags.interactive:
            plt.show(block=False)
        else:
            plt.show()

    def _onclick(self, event):
        if event.inaxes:
            x, y = event.xdata, event.ydata
            self.selected_pixel = [x, y]
            self.ax.scatter(self.selected_pixel[0],
                            self.selected_pixel[1],
                            s=5,
                            c='red',
                            marker='o')
            plt.draw()
            if sys.flags.interactive:
                pass
            else:        
                plt.close(self.fig)
            pass              

    def createROI(self, currentImage, PETSlice):
        print(self.selected_pixel)
        circle_masked_Im = currentImage[:, :, PETSlice]
        nx, ny = np.shape(circle_masked_Im)
        cordx, cordy = np.ogrid[0:nx, 0:ny]
        circle_mask = ((cordx - self.selected_pixel[1])**2 +
                        (cordy - self.selected_pixel[0])**2 <  10)
        circle_masked_Im[circle_mask] = 0

        return currentImage

我怎么称呼它:

plt.imshow(Current_Image[:, :, 50])    #50 is the slice of the 3d image
myROI = ClickAndRoi()

segemented_Image = myROI.createROI(SUV, 50) #50 is the slice of the 3d image

plt.close()
plt.imshow(segemented_Image[:,:, 50])

该类的目标是单击 3d 图像切片 (np.array) 中的一个点,并基于此位置通过阈值分割图像。

奇怪的行为来自方法createROI。正如它现在所写的那样,理论上应该采用currentImage 并返回currentImage,但是,它返回的是circle_masked_Im!!

为什么会有这种行为?

谢谢!

【问题讨论】:

  • 我可以看到SUVprint(type(SUV)) 的初始化。
  • 这是结果:&gt;&gt;&gt; print(type(SUV)) &lt;class 'numpy.ndarray'&gt;

标签: python class matplotlib


【解决方案1】:

我根据Python: unwanted change of variable occurs 中发布的答案解决了问题。

问题似乎在于 Python 中的变量是引用而不是值。使用 deepcopy 解决了这个问题:

fom copy importy deepcopy

并将变量赋值为

circle_masked_Im = deepcopy(currentImage[:, :, PETSlice])

可能有一种更优雅的方法来解决问题,但这很好用。

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 2015-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    相关资源
    最近更新 更多