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

python:处理超出范围的numpy索引,python,numpy,indexing,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。如何允许范围内索引工作,同时用黑色替换范围外索引?只需屏蔽它们: # transform >>> x2 = ((x-im1.shape[1

我正在使用以下代码沿图像的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。如何允许范围内索引工作,同时用黑色替换范围外索引?

只需屏蔽它们:

# 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

我看到两种可能的方法:条件语句或三元运算符。我宁愿使用条件。可以使用try/except索引器块,并在捕获索引错误时设置黑色值。