# Co-ordinate system followed in cv2.warpAffine()

I was trying to implement a naive version of the warpAffine function to understand how it works. This is my implementation

def custom_warpaffine(image, matrix, shape):
'''
clone of cv2.warpAffine()
Follows nearest-neighbour interpolation

@Params:

image - numpy array - 1 channel, source image
matrix - numpy array of size (2, 3), affine transform matrix
shape - int tuple, shape of source image

@returns:

output - numpy array - 1 channel, image after affine transform
'''
output = np.zeros_like(image, dtype=np.float32)

for x in range(shape):
for y in range(shape):
transformed_x = int(matrix[0,0]*x + matrix[0,1]*y + matrix[0,2])
transformed_y = int(matrix[1,0]*x + matrix[1,1]*y + matrix[1,2])
if transformed_x >=shape or transformed_y >=shape:
pass
else:
output[x, y] = image[transformed_x, transformed_y]

return output


I followed the mapping given in the [documentation](https://docs.opencv.or..., but my output is different from that of the inbuilt function.

my affine transform matrix is [[1, 0, 100], [0, 1, 50]],

i.e dst[x, y] = scr[x+100, y+50]

but the output was different.

The output matched the inbuilt cv2.warpAffine(.., flags=cv2.WARP_INVERSE_MAP,..) function output only when the mapping was changed from

output[x, y] = image[transformed_x, transformed_y]

to

output[y, x] = image[transformed_y, transformed_x]

I am confused as to why this is the case. Thanks for any help!

edit retag close merge delete

Have a look at the indexing in Numpy. In short, it is img[row, col] or img[y,x].