在两个Numpy数组中查找序列



我有两个Numpy数组,其中包含来自另一个数组的最大值和最小值的索引。

例如,对于一个输出,最大值和最小值数组看起来像这样:

Maxima indices are (array([ 4, 10, 14, 37, 43, 51, 59, 67, 81, 89, 95]),)
Minima indices are (array([ 7, 12, 25, 33, 40, 49, 56, 63, 76, 92]),)

这些索引来自图像行中的强度值。

我需要找出最大值在两个最小值之间的四个索引位置内出现的次数-换句话说:

minima + 4 + maxima + 4 + minima

我如何在Python中有效地做到这一点?如何比较两个数组中的索引值以找到该序列的实例,然后计算总共有多少个实例?

非常感谢你的帮助。

EDIT:每个最大值必须在左侧和右侧最接近的最小值的4个位置内。基本上,我试图识别基于强度值的图像内的虚线。

让我们试试。

import numpy
# create a vector for distances from the nearest leftmost minimum
# img_len is the length of the image row
# first we create an integer vector with 1 at each minimum
b = numpy.zeros(img_len, dtype='int')
# then we create an integer vector for the distances
d = numpy.zeros(img_len, dtype='int')
# we mark leftmost distances up to the first minimum to be largest possible
d[:minima[0]] = minima[0] - numpy.arange(minima[0])
# then we iterate through the vector and calculate the distances
for i in range(len(minima) - 1):
    prev = minima[i]
    next = minima[i+1]
    # now we have a gap between the two minima
    # let's fill it with a triangle 0,1,2,...,2,1,0
    k = (next-prev + 1) // 2
    d[prev:prev+k+1] = numpy.arange(k+1)
    d[next-k+1:next] = k -1 - numpy.arange(k-1)
# fill in the space after the last minimum:
d[minima[-1]:] = numpy.arange(img_len - minima[-1])
# all maxima whose distance is less than D from the closest minimum
results = [ m for m in maxima if d[m] < D ]

除非从代码中可以明显看出,否则我们的想法是创建一个向量d,它对应于离最近的最小值的距离。生成的向量,例如,4、3、2、1,0,1,2,3、2、1,0,1,2,- 1,0,…0对应于最小位置。最困难的事情是在循环中正确地制作三角形。(我希望我把所有的off-by-one都清理干净了…)

当然,现在您也可以为最大位置创建一个元组列表:

[ (m, d[m]) for m in maxima ]

对于问题中的数据,返回:

[(4, 3),
 (10, 2),
 (14, 2),
 (37, 3),
 (43, 3),
 (51, 2),
 (59, 3),
 (67, 4),
 (81, 5),
 (89, 3),
 (95, 3)]

即使在问题中的两个最小值之间存在不止一个最大值,代码也可以工作。(如果只有一个最大值,那么代码将几乎完全不同。)

我将把这个作为另一个答案,因为这是一个完全不同的方法。不是很节省空间,但是代码很短,而且很傻。

import numpy
# let's assume minima and maxima are 1-d arrays
# then the distance matrix for distances between any maximum to any minimum is:
md = numpy.amin(numpy.abs(maxima[:,None]-minima[None,:]), axis=1)
# the maxima which are at most D pixels away form the closest minima:
cm = maxima[md < D]

这些当然可以组合成一个很难理解的一行。

简要说明:

  • 计算所有最小值(列)和最大值(行)之间的距离矩阵(充满冗余和不相关的信息)
  • 矩阵的绝对值给出了每个最大值到每个最小值之间的距离
  • 从每个最大值到任何最小值的最短距离是用amin沿行
  • cm是通过索引布尔数组的最大值来计算的(当距离低于限制时为true)

如果向量很长,这可能会变慢。如果不着急,这是一段简单的代码。

最新更新