Python 用 numpy 和 matplotlib 叠加图像分割
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31877353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overlay an image segmentation with numpy and matplotlib
提问by Greynes
I am trying to overlay two images. The first one is a 512x512 NumPy array (from a CT image). The second one is also a 512x512 NumPy array but I am just interested in the pixels where the value is larger than 0 (a functional image).
我正在尝试覆盖两个图像。第一个是 512x512 NumPy 阵列(来自 CT 图像)。第二个也是 512x512 NumPy 数组,但我只对值大于 0 的像素(功能图像)感兴趣。
To do that I am trying to create a masked array.
为此,我正在尝试创建一个屏蔽数组。
import numpy as np
import numpy.ma as ma
import matplotlib.pyplot as plt
# Both images are loaded from a dicom. Both are numpy arrays of (512,512)
Image1 = readimage(path)
Image2 = readimage(path)
# Create image 2 mask
mask = ma.masked_where(Image2>0, Image2)
Image2_mask = ma.masked_array(Image2,mask)
# Plot images
plt.figure(dpi=300)
y, x = np.mgrid[1:513,1:513]
plt.axes().set_aspect('equal', 'datalim')
plt.set_cmap(plt.gray())
plt.pcolormesh(x, y, Image1,cmap='gray')
plt.pcolormesh(x, y, Image2_mask,cmap='jet')
plt.axis([x.min(), x.max(), y.min(), y.max()])
plt.colorbar()
plt.show()
This code does not show any overlay. What I am doing wrong? Is there any straight way? I am coming from a Matlab environment and I am quite new to Python.
此代码不显示任何叠加。我做错了什么?有什么直接的方法吗?我来自 Matlab 环境,对 Python 还是很陌生。
采纳答案by Imanol Luengo
Why don't you use imshow
instead?
你为什么不imshow
改用?
You can plot a 2D image by doing:
您可以通过执行以下操作来绘制 2D 图像:
plt.imshow(Image1, cmap='gray') # I would add interpolation='none'
Afterwards, you can easily overlay the segmentation by doing:
之后,您可以通过执行以下操作轻松覆盖分段:
plt.imshow(Image2_mask, cmap='jet', alpha=0.5) # interpolation='none'
Changing the alpha will change the opacity of the overlay.
更改 alpha 将更改叠加层的不透明度。
Additionaly, why do you create 2 masks? Only one should be enough, you can do:
另外,你为什么要创建 2 个面具?只有一个就足够了,你可以这样做:
Image2_mask = ma.masked_array(Image2 > 0, Image2)
Practical example:
实际例子:
import numpy as np
mask = np.zeros((10,10))
mask[3:-3, 3:-3] = 1 # white square in black background
im = mask + np.random.randn(10,10) * 0.01 # random image
masked = np.ma.masked_where(mask == 0, mask)
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(1,2,1)
plt.imshow(im, 'gray', interpolation='none')
plt.subplot(1,2,2)
plt.imshow(im, 'gray', interpolation='none')
plt.imshow(masked, 'jet', interpolation='none', alpha=0.7)
plt.show()