我试图摆脱灰度numpy数组中的所有行和列,其中值为255.
我的阵列可能是:
arr = [[255,255,255,255],
[255,0,0,255],
[255,255,255,255]]
结果应该是:
arr = [0,0]
我可以只是对数组进行交互,但应该有一种pythonic方法来解决问题.
对于我试过的行:
arr = arr[~(arr==255).all(1)]
这非常有效,但我无法找到一个平均的colums解决方案.
最佳答案 给定行和列的布尔数组:
In [26]: rows
Out[26]: array([False, True, False], dtype=bool)
In [27]: cols
Out[27]: array([False, True, True, False], dtype=bool)
np.ix_
创建了可用于索引arr的序数索引器:
In [32]: np.ix_(rows, cols)
Out[32]: (array([[1]]), array([[1, 2]]))
In [33]: arr[np.ix_(rows, cols)]
Out[33]: array([[0, 0]])
因此你可以使用
import numpy as np
arr = np.array([[255,255,255,255],
[255,0,0,255],
[255,255,255,255]])
mask = (arr != 255)
rows = mask.all(axis=1)
cols = mask.all(axis=0)
print(arr[np.ix_(rows, cols)])
产生2D阵列
[[0 0]]