python:处理超出范围的numpy索引

时间:2018-01-31 23:21:47

标签: python numpy indexing

我使用以下代码沿着它的y轴旋转图像。

y, x = np.indices(im1.shape[:2])
return im1[y, ((x-im1.shape[1]/2)/math.cos(t*math.pi/2)+im1.shape[1]/2).astype(np.int)]

有些值是故意超出范围的。我希望超出范围的像素为黑色(0,0,0)。如何让in范围索引起作用,同时用黑色替换超出范围?

1 个答案:

答案 0 :(得分:1)

掩饰他们:

# transform
>>> x2 = ((x-im1.shape[1]/2)/np.cos(t*np.pi/2)+im1.shape[1]/2).astype(np.int)
# check bounds
>>> allowed = np.where((x2>=0) & (x2<im1.shape[1]))
# preallocate with zeros
>>> res = np.zeros_like(im1)
# fill in within-bounds pixels
>>> res[allowed] = im1[y[allowed],x2[allowed]]
>>> 
# one possible economy I left out for clarity
>>> np.all(y[allowed] == allowed[0])
True