defbilinear_interp_vectorized(a:np.ndarray,b:np.ndarray)->np.ndarray:""" This is the vectorized implementation of bilinear interpolation. - a is a ND array with shape [N, H1, W1, C], dtype = int64 - b is a ND array with shape [N, H2, W2, 2], dtype = float64 - return a ND array with shape [N, H2, W2, C], dtype = int64 """# get axis size from ndarray shapeN,H1,W1,C=a.shapeN1,H2,W2,_=b.shapeassetsN==N1# Do iterationb=b.transpose(0,3,1,2)res=np.empty((N,H2,W2,C),dtype=int64)forninrange(N):X,Y=b[n]X_idx,Y_idx=np.floor(X).astype(int64),np.floor(Y).astype(int64)_X,_Y=X-X_idx,Y-Y_idxA00=a[n,X_idx,Y_idx].transpose(2,0,1)A01=a[n,X_idx,Y_idx+1].transpose(2,0,1)A10=a[n,X_idx+1,Y_idx].transpose(2,0,1)A11=a[n,X_idx+1,Y_idx+1].transpose(2,0,1)res00=A00*(1-_X)*(1-_Y)res10=A10*_X*(1-_Y)res01=A01*(1-_X)*_Yres11=A11*_X*_Yres[n]=res00.transpose(1,2,0)+res01.transpose(1,2,0)+ \
res10.transpose(1,2,0)+res11.transpose(1,2,0)returnres
Note
代码中使用了 np.transpose 函数进行矩阵转置,使得 X, Y 能容易地从 b 中取出,并且使得在进行矩阵逐元素乘法时能满足广播规则,同时对 C 个通道的信息进行处理。
defbilinear_interp_vectorized(a:np.ndarray,b:np.ndarray)->np.ndarray:""" This is the vectorized implementation of bilinear interpolation. - a is a ND array with shape [N, H1, W1, C], dtype = int64 - b is a ND array with shape [N, H2, W2, 2], dtype = float64 - return a ND array with shape [N, H2, W2, C], dtype = int64 """# get axis size from ndarray shapeN,_,_,C=a.shapeN1,H2,W2,_=b.shapeassetsN==N1# Do iterationres=np.empty((N,H2,W2,C),dtype=int64)# Get the matrices of coordinatesX,Y=b.transpose(3,0,1,2)X_idx,Y_idx=np.floor(X).astype(int64),np.floor(Y).astype(int64)_X,_Y=X-X_idx,Y-Y_idx# Generate the indices arrayN_idx=np.arange(N).reshape(N,1,1)A00=a[N_idx,X_idx,Y_idx].transpose(3,0,1,2)A01=a[N_idx,X_idx,Y_idx+1].transpose(3,0,1,2)A10=a[N_idx,X_idx+1,Y_idx].transpose(3,0,1,2)A11=a[N_idx,X_idx+1,Y_idx+1].transpose(3,0,1,2)res=A00*(1-_X)*(1-_Y)+A01*(1-_X)*_Y+ \
A10*_X*(1-_Y)+A11*_X*_Yreturnres.transpose(1,2,3,0).astype(int64)