且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从numpy数组中删除连续的数字

更新时间:2022-01-31 22:46:56

我检查了此解决方案是否适用于您的整个图像,而不适用于较小的样本,并且确实适用.
我将仅针对该小型数组给出一个示例:

I checked if this solution would work on your whole image rather than on that small sample, and it does work.
I will give an example just for that small array:

import numpy as np

x = np.array([[1, 1, 1, 2, 2, 1, 2],
              [1, 1, 1, 2, 2, 1, 2],
              [1, 1, 1, 2, 2, 1, 2],
              [1, 1, 1, 2, 2, 1, 2],
              [3, 3, 3, 4, 4, 1, 2],
              [3, 3, 3, 4, 4, 1, 2],
              [5, 5, 5, 6, 6, 1, 2],
              [7, 7, 7, 8, 8, 1, 2],
              [7, 7, 7, 8, 8, 1, 2]])

rows_mask = np.insert(np.diff(x[:, 0]).astype(np.bool), 0, True)
columns_mask = np.insert(np.diff(x[0]).astype(np.bool), 0, True)

print(x[np.ix_(rows_mask, columns_mask)])

给予:

[[1 2 1 2]
 [3 4 1 2]
 [5 6 1 2]
 [7 8 1 2]]

从这里您可以计算平均值.

From here you can calculate the average.

关于获取 rows_mask columns_mask 的信息,您可以在这里阅读: np.ix _ 仅返回对角线元素:

About getting rows_mask and columns_mask you can read here: Remove following duplicates in a numpy array .
Also, note that without np.ix_ only diagonal elements would be returned: Boolean array indexing