NumPy条件获取最大(R,G,B)>阈值的单元格

2024-04-25 23:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个面具,它有一个对应于图像中某些细胞的面具。这些单元格至少应有一个RGB颜色值大于阈值。我的代码不起作用:

B = image[0:h,0:w,0].astype(int)
G = image[0:h,0:w,1].astype(int)
R = image[0:h,0:w,2].astype(int)
mask = np.zeros((h,w))

mask[np.where( max(R,G,B) > threshold )] = 1

这会产生一个错误:

ValueError occurred Message=The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


Tags: 代码图像image颜色npzerosmask阈值
1条回答
网友
1楼 · 发布于 2024-04-25 23:19:32

由于您的图像是一个三维数组(h, w, 3),因此只需取最后一个轴的最大值即可获得max(R, G, B)

np.max(image, axis=-1)

将返回值与threshold进行比较,得到一个bool数组。将其转换为int以获得0和1的掩码:

mask = (np.max(image, axis=-1) > threshold).astype(int)

相关问题 更多 >