Reputation: 3967
Tested on matplotlib version: '3.5.2' and 3.6.0
This feels like a bug but I'm not sure if I'm missing something when using color images with an alpha mask.
I have two images A and B.
B should be applied as a overlay and has three color channels. Most pixels are 0 which shall be filtered out by an alpha mask.
Now the problem when I want to combine them I get the full image B.
Per pixel alpha is somehow not used in this setup:
plt.imshow(A)
plt.imshow(B, alpha=alphas)
plt.title("result")
plt.show()
When I reduce B to grayscale, it works as expected but it obviously then uses a cmap and not my color channels.
plt.imshow(A)
plt.imshow(B[:,:,0], alpha=alphas)
plt.title("one channel result")
plt.show()
MRE code:
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()
EDIT: This is currently (2024) tracked in this GitHub Issue
Upvotes: 1
Views: 814
Reputation: 670
I tested "alpha" as a 5x5 array, but the "imshow" simply ignores that array. So I joined "B" with an "alpha" column, so I got an (5 x 5 x 4) RGBA matrix, called "C".
So you don't need to pass a "alpha" array parameter in "imshow".
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()
Upvotes: 1