【发布时间】: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
【问题讨论】:
-
我们可以假设
values是mid_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