我应该使用字典来存储非零像素的位置吗?

时间:2019-01-24 15:05:29

标签: python-3.x numpy

我有一个二进制图像。我想存储所有非零像素的位置(x,y),以便将来用于搜索。

import numpy as np
I = np.random.randint(2, size=(128,128))
pos_nonzero = np.where(I==1)

将来,我会随机选择一个非零像素的位置来使用。我应该在这里使用哪种方法(字典或列表)?谢谢

1 个答案:

答案 0 :(得分:1)

您可以使用np.argwhere获取二维位置数组,以后可以使用np.random.choice从其中进行采样:

indices = np.argwhere(image)
sample_indices = np.random.choice(len(indices), size=5, replace=False)
pixels = image[tuple(indices[sample_indices].T)]