[英]How to change the index of all the 1 in an 2d numpy array which only has 0s and 1s?
I have a 2d numpy array(arr) which only has 0s and 1s.我有一个只有 0 和 1 的 2d numpy 数组(arr)。
For example, a 2d numpy array in shape(h,w).例如,形状为 (h,w) 的二维 numpy 数组。
I want to resize the array to shape(h // scale, w // scale), and I need to keep all the 1s.我想将数组的大小调整为 shape(h // scale, w // scale),并且我需要保留所有的 1。
# arr is a 2d numpy array
h, w = arr.shape
h_new, w_new = h // scale, w // scale
arr_new = np.zeros((h_new, w_new))
for i in range(h):
for j in range(w):
if arr[i, j] == 1:
arr_new[i // scale, j // scale] = 1
For example, a 2d array like this, and scale=2:例如,像这样的二维数组,并且 scale=2:
[
[0,0,0,0],
[0,1,0,0],
[1,0,0,1],
[0,0,0,1]
]
After runnung the code, arr_new will be:运行代码后, arr_new 将是:
[
[1,0],
[1,1]
]
the change of all the 1s' coordinates:所有1s坐标的变化:
(1,1) -> (0,0)
(2,0) -> (1,0)
(2,3) -> (1,1)
(3,3) -> (1,1)
Is there a better way to do this?有一个更好的方法吗?
Thanks.谢谢。
Just reshape the array by splitting each dimension to grid (SIZE // SCALE, SCALE)
.只需通过将每个维度拆分为网格
(SIZE // SCALE, SCALE)
来重塑数组。 Next reduce all dimensions of size SCALE using max()
to let 1
dominate the SCALExSCALE cell.接下来使用
max()
减少大小 SCALE 的所有维度,让1
支配 SCALExSCALE 单元格。
arr.reshape(h//scale, scale, w // scale, scale).max(axis=(1,3))
Note that this solution requires shape of array
to be multiplicity os (scale, scale)
.请注意,此解决方案要求
array
的形状为多重性 os (scale, scale)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.