Matplotlib 阈值大津:属性错误:';AxesSubplot';对象没有属性';拉威尔';

Matplotlib 阈值大津:属性错误:';AxesSubplot';对象没有属性';拉威尔';,matplotlib,plot,dicom,simpleitk,niftynet,Matplotlib,Plot,Dicom,Simpleitk,Niftynet,我加载了漂亮的文件(这些文件也是从.pack CT扫描转换而来的)。我的目标是使用threashold-otsu算法从背景中屏蔽它,并比较两幅图像。当我尝试绘图时,我得到了错误 AttributeError: 'AxesSubplot' object has no attribute 'ravel' 下面是代码,并附上一个屏幕截图 import SimpleITK as sitk import matplotlib.pyplot as plt import numpy as np from s

我加载了漂亮的文件(这些文件也是从.pack CT扫描转换而来的)。我的目标是使用threashold-otsu算法从背景中屏蔽它,并比较两幅图像。当我尝试绘图时,我得到了错误

AttributeError: 'AxesSubplot' object has no attribute 'ravel'
下面是代码,并附上一个屏幕截图

import SimpleITK as sitk
import matplotlib.pyplot as plt
import numpy as np
from skimage.filters import threshold_otsu

#THRESHOLD OTSU
img = sitk.GetArrayFromImage(sitk.ReadImage("\\\\x.x.x.x/users/ddff/python/nifts/prr_ipsi.nii"))
print(img.shape)
thresh = threshold_otsu(img.flatten())
#thresh = thresh.reshape(img.shape)
binary = img <= thresh

#I can plot this image slice fine
plt.imshow(img[20,:,:])

fig, axes = plt.subplots(ncols=1)
ax = axes.ravel()
ax[0] = plt.subplot(1, 3, 1)
ax[1] = plt.subplot(1, 3, 2)
ax[2] = plt.subplot(1, 3, 3, sharex=ax[0], sharey=ax[0])

ax[0].imshow(img[20,:,:], cmap=plt.cm.gray)
ax[0].set_title('Original Breast Delineation')
ax[0].axis('off')

ax[1].hist(thresh, bins=256)
ax[1].set_title('Histogram ')
ax[1].axvline(thresh, color='r')

ax[2].imshow(binary[20,:,:], cmap=plt.cm.gray)
ax[2].set_title('Thresholded')
ax[2].axis('off')

plt.show()[enter image description here][1]
将SimpleTk作为sitk导入
将matplotlib.pyplot作为plt导入
将numpy作为np导入
从skimage.filters导入阈值\u otsu
#门槛大津
img=sitk.GetArrayFromImage(sitk.ReadImage(“\\\\x.x.x/users/ddff/python/nifts/prr\u ipsi.nii”))
打印(图像形状)
thresh=阈值_otsu(img.flatte())
#脱粒=脱粒重塑(img.形状)

binary=img
只是一个带有一列的单个图形,因此没有任何东西可以展开
或展平。如果有多个子图,它将起作用。但是,如果只有一行或一列,则可以在不使用
ravel
的情况下执行以下操作

fig, ax = plt.subplots(ncols=3, sharex=True, sharey=True)

ax[0].imshow(img[20,:,:], cmap=plt.cm.gray)
ax[0].set_title('Original Breast Delineation')
ax[0].axis('off')

ax[1].hist(thresh, bins=256)
ax[1].set_title('Histogram ')
ax[1].axvline(thresh, color='r')

ax[2].imshow(binary[20,:,:], cmap=plt.cm.gray)
ax[2].set_title('Thresholded')
ax[2].axis('off')
如果需要子地块实例的2d矩阵,可以使用Thomas Kühn的建议

fig, ax = plt.subplots(ncols=3, sharex=True, sharey=True, squeeze=False)
然后你可以访问子地块作为

ax[0][0].imshow()
ax[0][1].imshow()
......

如果需要轴的完整2D矩阵,可以在调用
plt.subplot
时添加
squeze=False
。有关如何使
axes.ravel()
独立于
ncol
nrows
工作的方法,请参阅我对问题的评论。