Co-ordinate system followed in cv2.warpAffine()

asked 2019-09-04 04:51:25 -0600

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.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 flag offensive close merge delete

Comments

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

Eduardo gravatar imageEduardo ( 2019-09-04 09:33:34 -0600 )edit

Afaik, here x is rows and y is column.

blockchainmen gravatar imageblockchainmen ( 2019-09-04 16:21:09 -0600 )edit