在 numpy 数组中仅随机排列一部分索引(类似于非黑色像素)的最快方法
Fastest way to randomly permute only a subset of indices (akin to non-black pixels) in a numpy array
我有一个 3D numpy 形状数组,例如:(500,500,3),只有一些 [i,j,:] 单元格在所有 3 个通道中都为零(想象一个所有通道都为零的 RGB 图像= 黑色像素)。执行这些值的就地排列的最快方法是什么,以便 'all zero' [i,j] 单元格保持 post-排列(在图像示例中,黑色像素保持黑色,所有其余排列)。
这是这样一个数组的示例,以及一个可行的解决方案(但我希望它尽可能快):
# make the numpy array
a = np.zeros((500,500,3))
a[100:200,100:200] = 1
a[200:300,200:300] = 2
# extract (i,j) indices and corresponding RGB values for indices that are not all zero RGB
idx_to_val = {idx[:-1]: a[idx[:-1]] for idx, _ in np.ndenumerate(a) if sum(a[idx[:-1]]) > 0}
idx, vals = list(idx_to_val.keys()), list(idx_to_val.values())
# shuffle the (i,j) indices
np.random.shuffle(idx)
# fill in a new numpy array at these not-all-zero indices with the non-shuffled values
a_perm = np.zeros(a.shape)
a_perm[tuple(zip(*idx))] = vals
任何关于更快解决方案的想法都将不胜感激!
这是一个完全矢量化的解决方案,基于advanced indexing:
a_perm = np.zeros_like(a)
rows, cols = np.where(a.any(axis=-1))
perm = np.random.permutation(len(rows))
a_perm[rows[perm], cols[perm]] = a[rows, cols]
我有一个 3D numpy 形状数组,例如:(500,500,3),只有一些 [i,j,:] 单元格在所有 3 个通道中都为零(想象一个所有通道都为零的 RGB 图像= 黑色像素)。执行这些值的就地排列的最快方法是什么,以便 'all zero' [i,j] 单元格保持 post-排列(在图像示例中,黑色像素保持黑色,所有其余排列)。
这是这样一个数组的示例,以及一个可行的解决方案(但我希望它尽可能快):
# make the numpy array
a = np.zeros((500,500,3))
a[100:200,100:200] = 1
a[200:300,200:300] = 2
# extract (i,j) indices and corresponding RGB values for indices that are not all zero RGB
idx_to_val = {idx[:-1]: a[idx[:-1]] for idx, _ in np.ndenumerate(a) if sum(a[idx[:-1]]) > 0}
idx, vals = list(idx_to_val.keys()), list(idx_to_val.values())
# shuffle the (i,j) indices
np.random.shuffle(idx)
# fill in a new numpy array at these not-all-zero indices with the non-shuffled values
a_perm = np.zeros(a.shape)
a_perm[tuple(zip(*idx))] = vals
任何关于更快解决方案的想法都将不胜感激!
这是一个完全矢量化的解决方案,基于advanced indexing:
a_perm = np.zeros_like(a)
rows, cols = np.where(a.any(axis=-1))
perm = np.random.permutation(len(rows))
a_perm[rows[perm], cols[perm]] = a[rows, cols]