【问题标题】:Select one random index per unique element in NumPy array and account for missing ones from reference array为 NumPy 数组中的每个唯一元素选择一个随机索引,并考虑参考数组中缺失的索引
【发布时间】:2019-04-01 02:52:30
【问题描述】:

如果我有以下情况

import numpy as np

mid_img = np.array([[0, 0, 1],
                    [2, 0, 2],
                    [3, 1, 0]])

values = np.array([0, 1, 2, 3, 4])              

locations = np.full((len(values), 2), [-1, -1])
locations[np.argwhere(mid_img == values)] = mid_img  # this of course doesn't work, but hopefully shows intent

'locations' 看起来像这样(仅作为解释的中间步骤显示。不需要获取此输出。

[[[0, 0], [0, 1], [1, 1], [2, 2]],  #ie, locations matching values[0]
 [[0, 2], [2, 1]],                  #ie, locations matching values[1]
 [[1, 0], [1, 2]],                  #ie, locations matching values[2]
 [[2, 0]]]                          #ie, locations matching values[3]
 [[-1, -1]]]                        #ie, values[4] not found

然后最终输出会为每个值行随机选择位置:

print locations

输出:

[[0, 1],
 [2, 1],
 [1, 0],
 [2, 0],
 [-1, -1]

这是一个循环版本的过程:

for row_index in np.arange(0, len(values)):
    found_indices = np.argwhere(mid_img == row_index)
    try:
        locations[row_index] = found_indices[np.random.randint(len(found_indices))]
    except ValueError:
        pass

【问题讨论】:

  • 我们可以假设valuesmid_img 中的所有唯一值吗?另外,我们可以假设mid_img 仅具有正值吗?
  • 哦,好问题。 mid_img 将仅为 0-255 int(因此始终为正),并且值将始终使用唯一的 int 填充(无重复)
  • 所以,values 中的 4 看起来很奇怪。
  • 目标是表明如果没有找到一个值,应该保留一些任意的非正值(即-1,-1)
  • mid_img 中是否有一些独特的元素在 values 中不存在 - 类似于:values = np.array([0, 1, 3, 4]) (缺少 2 个)?

标签: python python-2.7 numpy image-processing array-broadcasting


【解决方案1】:

这是一种矢量化方式 -

# Get flattened sort indices for input array
idx = mid_img.ravel().argsort()

# Get counts for all uniqe elements
c = np.bincount(mid_img.flat)
c = c[c>0]

# Get bins to be used with searchsorted later on so that we select 
# exactly one unique index per group. These would be linear indices
bins = np.repeat(1.0/c,c).cumsum()
n = len(c)
sidx = np.searchsorted(bins,np.random.rand(n)+np.arange(n))
out_lidx = idx[sidx]

# Convert to row-col index format
row,col = np.unravel_index(out_lidx, mid_img.shape)

# Initialize output array
locations = np.full((len(values), 2), [-1, -1])

# Get valid ones based on values and indexed output
valid = values <= mid_img[row[-1],col[-1]]

# Finally assign row, col indices into final output
locations[valid,0] = row
locations[valid,1] = col

【讨论】:

  • 感谢迪瓦卡!像往常一样,您的解决方案总是非常有用。
猜你喜欢
  • 1970-01-01
  • 2013-06-09
  • 2014-04-21
  • 2020-03-20
  • 2014-06-09
  • 1970-01-01
  • 2018-03-24
  • 2012-01-05
相关资源
最近更新 更多