在 matplotlib 版本上测试: “3.5.2”和 3.6.0
这感觉像是一个错误,但我不确定在使用带有 alpha 蒙版的彩色图像时是否遗漏了一些东西。
我有两张图片 A 和 B。
B 应作为叠加层应用并具有三个颜色通道。大多数像素为 0,应通过 alpha 掩码过滤掉。
现在的问题是,当我想组合它们时,我得到完整的图像 B。
此设置中未使用每像素 alpha:
plt.imshow(A)
plt.imshow(B, alpha=alphas)
plt.title("result")
plt.show()
当我将 B 减少为灰度时,它按预期工作,但显然它使用了 cmap 而不是我的颜色通道。
plt.imshow(A)
plt.imshow(B[:,:,0], alpha=alphas)
plt.title("one channel result")
plt.show()
MRE代码:
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
A=np.arange(5*5*3).reshape((5,5,3)) / (5*5*3)
plt.imshow(A)
plt.title("A")
plt.show()
B = np.zeros(5*5*3).reshape((5,3,5))
B[2:4, 2:4] = 1
B.shape = (5,5,3) # do some shifting so its not grayscale
plt.imshow(B)
plt.title("B")
plt.show()
alphas = np.zeros(5*5).reshape((5,5))
alphas[B[:,:,1] > 0] = 0.66
plt.imshow(alphas)
plt.title("Alpha mask")
plt.show()
plt.imshow(A)
plt.imshow(B, alpha=alphas) # gives wrong result
plt.title("wrong result")
plt.show()
编辑:目前(2024 年)在此 GitHub Issue
中对此进行跟踪我将“alpha”测试为 5x5 数组,但“imshow”只是忽略该数组。所以我将“B”与“alpha”列连接起来,这样我就得到了一个 (5 x 5 x 4) RGBA 矩阵,称为“C”。
所以你不需要在“imshow”中传递“alpha”数组参数。
import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(2, 3, figsize=(6, 5))
ax1 = ax[0, 0]
ax2 = ax[0, 1]
ax3 = ax[1, 0]
ax4 = ax[1, 1]
ax5 = ax[0, 2]
ax6 = ax[1, 2]
A = np.arange(5*5*3).reshape((5, 5, 3)) / (5*5*3)
ax1.imshow(A)
ax1.set_title("A")
B = np.zeros(5*5*3).reshape((5, 3, 5))
B[2:4, 2:4] = 1
#B.shape = (5, 5, 3) # do some shifting so its not grayscale
B = B.reshape((5, 5, 3))
ax2.imshow(B)
ax2.set_title("B")
alphas = np.zeros(5*5).reshape((5, 5))
alphas[B[:, :, 1] > 0] = 0.66
ax3.imshow(alphas)
ax3.set_title("Alpha mask")
alphas_2 = alphas.reshape(5, 5, 1)
C = np.dstack((B, alphas_2))
ax4.imshow(A)
ax4.imshow(B)
ax4.set_title("A and B")
ax5.imshow(C)
ax5.set_title("C")
ax6.imshow(A)
ax6.imshow(C)
ax6.set_title("A and C")
plt.show()