Ask Your Question

Revision history [back]

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[0]):
        for y in range(shape[1]):
            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[0] or transformed_y >=shape[1]:
                pass
            else:
                output[x, y] = image[transformed_x, transformed_y]

    return output

I followed the mapping given in the [documentation](https://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html?highlight=warpaffine#void%20warpAffine(InputArray%20src,%20OutputArray%20dst,%20InputArray%20M,%20Size%20dsize,%20int%20flags,%20int%20borderMode,%20const%20Scalar&%20borderValue), 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!