使用 x,y 数组作为图像数组中的索引



我有一张图片:

>> img.shape
(720,1280)

我已经确定了一组我想要的 x,y 坐标,如果它们是真的,将一致性图像的值设置为 255。

这就是我的意思。 形成索引是我vals

>>> vals.shape
(720, 2)
>>> vals[0]
array([  0, 186]) # the x is 0, the y is 186, I'd like to set value at img[0][186]=255
>>> vals[719]
array([719, 207]) # the x is 719, the y is 207, I'd like to set value at img[719][207]=255

vals的第一个维度与range(719)冗余。

我首先创建一个与 img 形状相同的图像:

>>> out = np.zeros_like(img)
>>> out.shape
(720, 1280)

但从这里开始,我对out的索引似乎不起作用:

>>> out[vals] = 255
>>> out.shape
(720, 1280)
>>> out
array([[255, 255, 255, ..., 255, 255, 255],
       [255, 255, 255, ..., 255, 255, 255],
       [255, 255, 255, ..., 255, 255, 255],
>>> out.min()
255

这使得/all/out值为 255,而不仅仅是索引为 out == vals 的值

我期望:

>>> out[0][0]
0
>>> out[0][186]
255
>>> out[719][207]
255

我做错了什么?

这有效,但真的很丑陋:

# out[(vals[:][:,0],vals[:][:,1])]=255
out[(vals[:,0],vals[:,1])]=255

还有更好的吗?

我认为这应该有所帮助:

import numpy as np
img = np.random.rand(100, 200) # sample image, e.g. grayscaled.
where_to_change = [(20,10), (3, 4)]  # in (x, y)-fashion
#So, you need to set: `img[20, 10] = 1`, `img[3, 4]= 1` etc.... 
img[list(zip(*where))] = 1 

最新更新