If you have found yourself using the OpenCV remap function, you may have noticed a reference to a convertMaps function.

This function converts map matrices to fixed-point, in order to improve the remap performance.

And it does. Back in the remap function post, we measured the time it takes to perform the remap in python. It was about 1.49ms.

The map parameters were float32 matrices. Converting them to fixed-point numbers, changed the remap time to about 1.04ms. It is great improvement. I did not get the 2x improvement advertised by OpenCV, but if I average the numbers I believe I will get more than 50% improvement (>1.5x). I was just a bit lazy.

Of course, there is the overhead of the conversion itself, which is about 1.12ms. But if these maps are to be used multiple times, then the benefits are obvious.

Here is how to use the convertMaps function

dstMap1, dstMap2 = cv2.convertMaps(mapX.astype(np.float32),
 mapY.astype(np.float32), cv2.CV_16SC2)

Here, we assume that we have mapX and mapY mapping matrices, with elements of type float64 (double). I used this data type to stress that your input to convertMaps cannot be float64 matrices and in case you have float64 matrices you have to convert them to float32.

cv2.CV_16SC2 is the most frequently used conversion target. This means 16 bit signed two channel integer. Why two channels? One for the X coordinate conversion and one for the Y. We no longer have separate matrices for each dimension.

The result matrices are dstMap1 and dstMap2. The first one is the two channel matrix described in the previous paragraph, of the same size as the input matrices. Its elements are rounded coordinates.

The second map, dstMap2, holds interpolation coefficient table indexes.

Actually, the above two matrices are better described in the OpenCV remap documentation itself: “In the converted case, map1 contains pairs (cvFloor(x),cvFloor(y)) and map2 contains indices in a table of interpolation coefficients”.

Finally, to call remap with the converted matrices we simply do:

cv2.remap(inputImage, dstMap1, dstMap2, 
        cv2.INTER_LINEAR, outputImage, cv2.BORDER_REPLICATE)

Thanks for following!