摘要:我正在寻找类似“numpy.nonzero”的东西,但有所不同。我想搜索包含第三维中任何非零元素的所有索引。如果存在任何元素,请给我该维度的索引。
详细信息:我的项目涉及接收、解析然后输出修改后的图像文件。首先将图像转换为 3D numpy 数组。使用该文件创建掩码。接下来,它使用“numpy.bitwise_and”来查找掩码的位模式与源图像重叠的位置,然后根据这些索引执行操作。
mask = create_mask(self.image) # spare array, same size as self.image
overlap = np.bitwise_and(self.image, mask)
indices = []
for y, row in enumerate(overlap):
for x, col in enumerate(row):
if any(col): # any RGB values are not 0
indices.append((y,x))
for (y, x) in indices:
pass # do stuff
解决这个问题的最佳方法是什么?我确信有比上面所示的简单方法更好的方法。
最佳答案
一种 NumPythonic 方法是使用 .any
沿着最后一个轴,即 .any(axis=-1)
或简单地 .any(-1)
,然后使用 np.argwhere
获取相应的有效索引,就像这样 -
indices = np.argwhere(overlap.any(-1))
请注意,indices
将是一个 NumPy 数组。
关于python - NumPy:第三维非零的索引(图像掩蔽),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954419/