我是 numpy 的掩码数组数据结构的新手,我想用它来处理分段彩色图像。
当我使用 matplotlibplt.imshow( masked_gray_image, "gray")
显示蒙版的灰色图像时,无效区域将显示为透明,这就是我想要的。但是,当我对彩色图像执行相同操作时,它似乎不起作用。有趣的是,数据点光标不会显示 rgb 值[r,g,b]
而是 empty []
,但仍然显示颜色值而不是透明的。
我做错了什么还是 matplotlib 中还没有提供imshow
?
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import face
img_col = face() #example image from scipy
img_gray = np.dot(img_col[...,:3], [0.299, 0.587, 0.114]) #convert to gray
threshold = 25
mask2D = img_gray < threshold # some exemplary mask
mask3D = np.atleast_3d(mask2D)*np.ones_like(img_col) # expand to 3D with broadcasting...
# using numpy's masked array to specify where data is valid
m_img_gray = np.ma.masked_where( mask2D, img_gray)
m_img_col = np.ma.masked_where( mask3D, img_col)
fig,axes=plt.subplots(1,4,num=2,clear=True)
axes[0].imshow(mask2D.astype(np.float32)) # plot mask
axes[0].set_title("simple mask")
axes[1].imshow(m_img_gray,"gray") #plot gray verison => works
axes[1].set_title("(works)\n masked gray")
axes[2].imshow(m_img_col) #plot color version, => does not work
axes[2].set_title("(doesn't work)\n masked color")
# manually adding mask as alpha channel to show what I want
axes[3].imshow( np.append( m_img_col.data, 255*(1-(0 < np.sum(m_img_col.mask ,axis=2,keepdims=True) ).astype(np.uint8) ),axis=2) )
axes[3].set_title("(desired) \n alpha channel set manually")
[更新]:为了更清晰,对代码和图像进行了一些小改动......