I have the cameraMatrix
and the distCoeff
needed to undistort an image or a vector of points. Now I\'d like to distort them back.
Is it poss
The initUndistortRectifyMap
linked in one of the answers of the question you mention does indeed what you want. Since it is used in Remap
to build the full undistorted image, it gives, for each location in the destination image (undistorted), where to find the corresponding pixel in the distorted image so they can use its color. So it's really an f(undistorted) = distorted
map.
However, using this map will only allow for input positions that are integer and within the image rectangle. Thankfully, the documentation gives the full equations.
It is mostly what you have, except that there is a preliminary step that you are missing. Here is my version (it is C# but should be the same):
public PointF Distort(PointF point)
{
// To relative coordinates <- this is the step you are missing.
double x = (point.X - cx) / fx;
double y = (point.Y - cy) / fy;
double r2 = x*x + y*y;
// Radial distorsion
double xDistort = x * (1 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2);
double yDistort = y * (1 + k1 * r2 + k2 * r2 * r2 + k3 * r2 * r2 * r2);
// Tangential distorsion
xDistort = xDistort + (2 * p1 * x * y + p2 * (r2 + 2 * x * x));
yDistort = yDistort + (p1 * (r2 + 2 * y * y) + 2 * p2 * x * y);
// Back to absolute coordinates.
xDistort = xDistort * fx + cx;
yDistort = yDistort * fy + cy;
return new PointF((float)xDistort, (float)yDistort);
}