在一个numpy数组中获取并显示3个通道图像的堆栈中的一个图像

2024-10-02 02:41:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一堆图像。堆栈上的第一个如下所示:

enter image description here

import dicom as dc
dcm = dc.read_file('full_stack.dcm')
dcm = dcm.pixel_array
print type(dcm)
print dcm.shape

这给了我

^{pr2}$

所以看起来有:

  • 3个通道
  • 180张图片
  • 宽度为480
  • 身高640

太好了。在

我的目标是提取堆栈中的图像。然后,我要显示这个图像。听起来很简单。在

这是我的策略。我希望有任何关于这方面的想法/反馈:

1)得到一张图片。使用基本切片获得堆栈上的第10张图像

dcm1 = dcm[0:, 10:11]
dcm1.shape
(3, 1, 480, 640)

2)要使用plt.imshow在pyplot中实际绘制,我们需要以下形状:(r,c,channels)。所以我想用暴力来破坏这个形象。在

dcm2 = np.squeeze(dcm1, axis=1)  # throw away the '1'...this makes me nervous
print 'threw away the "1":              ', dcm2.shape
dcm3 = np.swapaxes(dcm2, 0,2)
print 'swapped the first and last dim:  ', dcm3.shape
dcm4 = np.swapaxes(dcm3, 0,1)
print 'swapped the first and second dim:', dcm4.shape

现在,我把这个可怜的形象弄得一团糟:

threw away the "1":               (3, 480, 640)
swapped the first and last dim:   (640, 480, 3)
swapped the first and second dim: (480, 640, 3)

是时候策划了!有什么可能发生的?在

imgplot = plt.imshow(dcm4)

我得到的是:

enter image description here

不知怎么的,我的形象现在有各种各样的颜色,看起来很糟糕。在

我的问题从这里开始——有人知道发生了什么吗?显然,我的方法是简单的和不令人满意的。但我不知道该去哪里。在

额外的东西,可能不是真正相关的

在这一点上,我尝试将频道分成一个频道,然后将其复制到三个频道,这样imshow可以阅读它,我将为您保存详细信息,但它提供了以下信息:

enter image description here


Tags: andthe图像堆栈npfirstprintshape
2条回答

我对dicom图像一无所知,我也没有文件来测试它,但是我可以想象一个简单的转置操作应该会给您所需的输出

import numpy as np

a = np.random.rand(3,1,480,640)
b = np.transpose(a[:,0,:,:], axes=[1,2,0])
print (b.shape) # (480L, 640L, 3L)

这个解决方案对我很有效。请验证输入数组中的值范围是否在0-255范围内,是否为uint8数据类型。光是尺寸不足以再现结果。例如,以下设置适用于我:

In [50]: img = np.random.randint(0, 255, (3, 180, 480, 640), dtype=np.uint8)
In [51]: img1 = np.squeeze(img[:, 9:10])

# proper_img is a *view*; caution while modifying it
In [52]: proper_img = np.moveaxis(img1, source=0, destination=-1)
In [53]: plt.imshow(proper_img)

我得到的情节如下:

enter image description here

相关问题 更多 >

    热门问题