![](/img/trans.png)
[英]Identify the first & last non-zero elements/indices within a group in numpy
[英]NumPy: indices where third dimension is non-zero (image masking)
摘要:我正在尋找類似 '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 數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.