discorpy icon indicating copy to clipboard operation
discorpy copied to clipboard

Can we use cv2 undistort function for fast undistortion results using the backward coefficients?

Open severecoder opened this issue 3 years ago • 3 comments

Can we use cv2 undistort function for fast undistortion results using the backward coefficients instead of using the unwarp_image_backward function?

Or do you recommend some other solution?

For context, I am trying to fasten the final unwarping process.

Thanks a lot in advance.

severecoder avatar Apr 24 '23 06:04 severecoder

Also from my understanding, forward coefficients list should contain k1, k2, k3, k4 and k5, am I correct?

severecoder avatar Apr 24 '23 06:04 severecoder

Yes you can. Actually, Discorpy in the first version (old name Vounwarp) used the function remap in Opencv. However for packaging Discorpy, it would be unwise to use Opencv as a dependency but using only 1 function. It's the main reason we changed to use scipy.mapp_coordinates instead. You can copy the following code to use with opencv. I will put this in Discorpy document for later reference.

import cv2
import numpy as np

def _mapping(mat, xmat, ymat):
    """
    Apply a geometric transformation to a 2D array using Opencv
    ---------
    Parameters: - mat: 2D array.
                - xmat: 2D array of the x-coordinates.
                - ymat: 2D array of the y-coordinates.
    ---------
    Return:     - 2D array. 
    """
    mat = cv2.remap(mat, xmat, ymat, interpolation=cv2.INTER_LINEAR)
    return mat


def unwarp_image_backward_cv(mat, xcenter, ycenter, list_fact):
    """
    Unwarp a 2D array using the backward model. Use Opencv library
    for fast performance.
    ---------
    Parameters: - mat: 2D array.
                - xcenter: Center of distortion in x-direction.
                - ycenter: Center of distortion in y-direction.
                - list_fact: Polynomial coefficients of the backward model.
    ---------
    Return:     - 2D array, distortion corrected.
    """
    (height, width) = mat.shape
    xu_list = np.arange(width) - xcenter
    yu_list = np.arange(height) - ycenter
    xu_mat, yu_mat = np.meshgrid(xu_list, yu_list)
    ru_mat = np.sqrt(xu_mat**2 + yu_mat**2)
    fact_mat = np.sum(
        np.asarray([factor * ru_mat**i for i,
                    factor in enumerate(list_fact)]), axis=0)
    xd_mat = np.float32(np.clip(xcenter + fact_mat * xu_mat, 0, width - 1))
    yd_mat = np.float32(np.clip(ycenter + fact_mat * yu_mat, 0, height - 1))
    mat = _mapping(mat, xd_mat, yd_mat)
    return mat

Yes for the question -> list_fact = [k1, k2, k3, k4, k5]

nghia-vo avatar Apr 24 '23 15:04 nghia-vo

I've added demonstration how to use remap in Opencv for unwarping video here: https://discorpy.readthedocs.io/en/latest/usage/tips.html

nghia-vo avatar Apr 24 '23 20:04 nghia-vo