当我尝试从方法返回数组时,我正在获取有线行为,这是代码:
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])
该课程的目标是点击三维图像切片中的一个点(np.array
)并在此位置基于阈值对图像进行分割。
方法createROI
出现了奇怪的行为。正如现在所写的那样,理论上应该取currentImage
并返回currentImage
,但不是那样,它会返回circle_masked_Im
!!
为什么会出现这种情况?
谢谢!
答案 0 :(得分:0)
我根据Python: unwanted change of variable occurs中发布的答案解决了问题。
问题似乎是Python中的变量是引用而不是值。使用deepcopy解决了这个问题:
fom copy importy deepcopy
并将变量指定为
circle_masked_Im = deepcopy(currentImage[:, :, PETSlice])
可能有更优雅的方法来解决问题,但这只是工作正常。