簡體   English   中英

從方法返回錯誤的變量

[英]Returning an incorrect variable from method

當我嘗試從方法返回數組時,出現了有線行為,這是代碼:

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

為什么這種行為?

謝謝!

我根據Python中發布的答案解決了這個問題:發生了不必要的變量更改

問題似乎在於Python中的變量是引用而不是值。 使用Deepcopy解決了該問題:

fom copy importy deepcopy

並將變量分配為

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

也許有一種更優雅的方式來解決問題,但這很好。

暫無
暫無

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

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