将图片和情节与matplotlib与alpha通道相结合

时间:2018-02-28 09:15:24

标签: python image matplotlib

我有一个带有alpha通道的.png图像和一个用numpy生成的随机图案。 我想用matplotlib来描述这两个图像。底部图像必须是随机图案,在此之后,我想看到第二张图片(附在帖子的末尾)。

两张图片的代码如下:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# Random image pattern
fig = plt.subplots(figsize = (20,4))

x = np.arange(0,2000,1)
y = np.arange(0,284,1)
X,Y = np.meshgrid(x,y)
Z = 0.6+0.1*np.random.rand(284,2000)
Z[0,0] = 0
Z[1,1] = 1

# Plot the density map using nearest-neighbor interpolation
plt.pcolormesh(X,Y,Z,cmap = cm.gray)

结果如下图所示:

enter image description here

要导入图像,我使用以下代码:

# Sample data
fig = plt.subplots(figsize = (20,4))

# Plot the density map using nearest-neighbor interpolation
plt.imread("good_image_2.png")
plt.imshow(img)
print(img.shape)

图片如下:

enter image description here

因此,我想要的最终结果是:

enter image description here

1 个答案:

答案 0 :(得分:1)

你可以为 Z 创建一个类似图像的数组,然后只需使用 imshow 在按钮图像等之前显示它。请注意,这只有效,因为你的png有一个alpha通道。

代码:

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# Plot the density map using nearest-neighbor interpolation
img = plt.imread("image.png")
(xSize, ySize, cSize) = img.shape
x = np.arange(0,xSize,1)
y = np.arange(0,ySize,1)
X,Y = np.meshgrid(x,y)
Z = 0.6+0.1*np.random.rand(xSize,ySize)
Z[0,0] = 0
Z[1,1] = 1

# We need Z to have red, blue and green channels
# For a greyscale image these are all the same
Z=np.repeat(Z,3).reshape(xSize,ySize,3)


fig = plt.figure(figsize=(20,8))
ax = fig.add_subplot(111)
ax.imshow(Z, interpolation=None)
ax.imshow(img, interpolation=None)

fig.savefig('output.png')

输出: enter image description here

如果您愿意,也可以关闭轴。

ax.axis('off')

enter image description here