如何在python中优先组合1D数组连续元素

时间:2017-03-23 11:14:21

标签: python numpy scipy python-imaging-library image-segmentation

我有以下1D数组:

[0, 0, 0, 1, 0, 0, 16, 249, 142, 149, 189, 135, 141, 146, 294, 3, 2, 0, 3, 3, 6, 2, 3, 4, 21, 22, 138, 95, 86, 110, 72, 89, 79, 138, 14, 18, 18, 18, 12, 15, 21, 22, 11, 20, 26, 90, 62, 128, 94, 117, 81, 81, 137, 7, 13, 14, 6, 10, 8, 11, 10, 13, 21, 18, 140, 69, 147, 110, 112, 88, 100, 197, 9, 20, 5, 6, 5, 4, 7, 10, 21, 32, 42, 56, 41, 156, 95, 112, 81, 93, 152, 14, 19, 9, 12, 20, 18, 14, 21, 18, 18, 14, 91, 47, 43, 63, 41, 45, 43, 85, 15, 16, 14, 10, 11]

我可以看到尖峰所在的模式。所以我想将上面的数组分组如下:

[[0, 0, 0, 1, 0, 0, 16], [249, 142, 149, 189, 135, 141, 146, 294], [3, 2, 0, 3, 3, 6, 2, 3, 4, 21, 22], [138, 95, 86, 110, 72, 89, 79, 138]....so on]

我尝试使用K均值,平均值和标准偏差的某种组合。但它们都没有导致这种分组。请帮忙!

编辑: 这些数据是沿y轴累加的x轴上的灰度图像的暗像素值的总和。较高范围组表示书写行,较低范围组表示空行。这意味着,我想在图像上分开书写和空白行。所以有一种模式。书写的行宽度相同,即它们的组长度相同。由于背景噪音,空行可能会突然出现尖峰。但总的来说,手动,我可以看到书面和空白行的模式。我想以编程方式进行。

1 个答案:

答案 0 :(得分:3)

在这种情况下,一种简单的基于阈值的方法将起作用。

x = np.array([0, 0, 0, 1, 0, 0, 16, 249, 142, 149, 189, 135, 141, 146, 294, 3, 2, 
              0, 3, 3, 6, 2, 3, 4, 21, 22, 138, 95, 86, 110, 72, 89, 79, 138, 14, 
              18, 18, 18, 12, 15, 21, 22, 11, 20, 26, 90, 62, 128, 94, 117, 81, 
              81, 137, 7, 13, 14, 6, 10, 8, 11, 10, 13, 21, 18, 140, 69, 147, 
              110, 112, 88, 100, 197, 9, 20, 5, 6, 5, 4, 7, 10, 21, 32, 42, 56, 
              41, 156, 95, 112, 81, 93, 152, 14, 19, 9, 12, 20, 18, 14, 21, 18, 
              18, 14, 91, 47, 43, 63, 41, 45, 43, 85, 15, 16, 14, 10, 11])

mask = x > 30  # Mark values above/below threshold

cuts = np.flatnonzero(np.diff(mask))  # find indices where mask changes
cuts = np.hstack([0, cuts + 1, -1])  # let indices point after the change and add beginning and end of the array.

groups = []
for a, b in zip(cuts[:-1], cuts[1:]):  # iterate over index pairs
    groups.append(x[a:b].tolist())
print(groups)

# [[0, 0, 0, 1, 0, 0, 16], [249, 142, 149, 189, 135, 141, 146, 294], [3, 2, 0, 3, 3, 6, 2, 3, 4, 21, 22], [138, 95, 86, 110, 72, 89, 79, 138], [14, 18, 18, 18, 12, 15, 21, 22, 11, 20, 26], [90, 62, 128, 94, 117, 81, 81, 137], [7, 13, 14, 6, 10, 8, 11, 10, 13, 21, 18], [140, 69, 147, 110, 112, 88, 100, 197], [9, 20, 5, 6, 5, 4, 7, 10, 21], [32, 42, 56, 41, 156, 95, 112, 81, 93, 152], [14, 19, 9, 12, 20, 18, 14, 21, 18, 18, 14], [91, 47, 43, 63, 41, 45, 43, 85], [15, 16, 14, 10]]

更复杂的方法可能涉及拟合分段常数模型或检测统计不稳定性,但通常最好坚持使用最简单的可行方法。