我有四个属性的数据。两个是坐标
xs
和ys
;另外两个是时间戳 ts
和极性 ps
。
我需要用最新的极性设置每个位置(x,y)
的图像值。
我可以使用 for 循环来完成它,如下所示,我需要一种矢量化的方式:
import numpy as np
color_p = (0, 0, 255)
color_n = (255, 0, 0)
H, W = 128, 128
n_p = 100
xs, ys = np.random.randint(0, W, n_p), np.random.randint(0, H, n_p)
ts = np.random.rand(n_p)
ts.sort()
ps = np.random.randint(0, 2, n_p)
img = np.zeros((H, W, 3), dtype=np.uint8)
for i in range(n_p):
x, y, p = xs[i], ys[i], ps[i]
img[y, x] = color_p if p > 0 else color_n
你可以这样做:
img2 = np.zeros((H, W, 3), dtype=np.uint8)
m = ps.astype(bool)
img2[ys[m], xs[m]] = color_p
img2[ys[~m], xs[~m]] = color_n
检查:
>>> np.all(img == img2)
True