剪切一些值为255的行和列

时间:2022-09-30 21:22:18

I am trying to get rid of all rows and columns in a grayscale numpy array where the values are 255.
My array could be:

我试图摆脱灰度numpy数组中的所有行和列,其值为255.我的数组可能是:

arr = [[255,255,255,255],
       [255,0,0,255],
       [255,255,255,255]]

The result should be:

结果应该是:

arr = [0,0]

I can just interating over the array, but there should be a pythonic way to solve the problem.
For the rows i tried:

我可以只对数组进行交互,但应该有一种pythonic方法来解决问题。对于我试过的行:

arr = arr[~(arr==255).all(1)]

This works really well, but i cannot find an equal solution for colums.

这非常有效,但我找不到相同的colums解决方案。

2 个解决方案

#1


2  

Given boolean arrays for rows and columns:

给定行和列的布尔数组:

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_ creates ordinal indexers which can be used to index arr:

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]])

Therefore you could use

因此你可以使用

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)])

which yields the 2D array

产生2D阵列

[[0 0]]

#2


0  

For the columns, you can simply transpose the array:

对于列,您只需转置数组:

arr = arr.T[~(arr.T==255).all(1)].T
arr = arr[~(arr==255).all(1)]

which results in

结果

>> print(arr)
[[0 0]]

#1


2  

Given boolean arrays for rows and columns:

给定行和列的布尔数组:

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_ creates ordinal indexers which can be used to index arr:

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]])

Therefore you could use

因此你可以使用

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)])

which yields the 2D array

产生2D阵列

[[0 0]]

#2


0  

For the columns, you can simply transpose the array:

对于列,您只需转置数组:

arr = arr.T[~(arr.T==255).all(1)].T
arr = arr[~(arr==255).all(1)]

which results in

结果

>> print(arr)
[[0 0]]