问题相当简单。给定 256x256 灰度图像,我想根据阈值返回带有颜色的彩色图像。
所以我在想:
img=whatever # 2D array of floats representing grayscale image
threshold=0.5
color1=[1.0,0.0,0.0]
color2=[0.0,0.0,1.0]
newImg=np.where(img>threshold,color1,color2)
Run Code Online (Sandbox Code Playgroud)
然而我得到了臭名昭著的:“ValueError:操作数无法与形状一起广播 (500,500) (3,) (3,)”
嗯?我真的期待给出一个数组形状(500,500,3)。为什么不把它们结合起来??
你误解了numpy.where
工作原理。看起来您可能在想,对于 的 True 单元格img>threshold
,where
选择整个 的color1
作为值,而对于 False 单元格,它选择 的整个color2
。不管你在想什么,这不是它的工作原理。
numpy.where
一起广播参数,然后对于第一个参数的每个单元格,选择第二个或第三个参数的相应单元格。要产生形状为 (500, 500, 3) 的结果,参数必须一起广播为 (500, 500, 3) 的形状。您的输入根本不是广播兼容的。
使广播工作的一种方法是在 的末尾添加一个额外的长度为 1 的维度img>threshold
:
newImg=np.where((img>threshold)[..., None],color1,color2)
Run Code Online (Sandbox Code Playgroud)
如果您不熟悉广播,那么numpy.broadcast_arrays
查看一起广播多个数组的结果可能会有所帮助。