用 numpy 和 matplotlib 叠加图像分割 [英] Overlay an image segmentation with numpy and matplotlib
问题描述
我正在尝试叠加两个图像.第一个是 512x512 NumPy 阵列(来自 CT 图像).第二个也是 512x512 NumPy 数组,但我只对值大于 0 的像素(功能图像)感兴趣.
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).
为此,我正在尝试创建一个掩码数组.
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()
此代码不显示任何叠加层.我做错了什么?有什么直接的方法吗?我来自 Matlab 环境,对 Python 还很陌生.
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.
推荐答案
为什么不用 imshow
代替?
您可以通过以下方式绘制 2D 图像:
You can plot a 2D image by doing:
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'
更改 alpha 将更改叠加层的不透明度.
Changing the alpha will change the opacity of the overlay.
另外,你为什么要创建2个面具?一个就够了,你可以这样做:
Additionaly, why do you create 2 masks? Only one should be enough, you can do:
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()
这篇关于用 numpy 和 matplotlib 叠加图像分割的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!