how to get all undistorted image with opencv

8.8k views Asked by At

I'm unsing cv::undistort but it crops the image. I'd like to have all the undistorted image, so that the undistorted size is bigger then the original one, like this:

enter image description here

I think I need to use cv::getOptimalNewCameraMatrix but I had no luck with my trials.. some help?

3

There are 3 answers

0
Josep Bosch On

Just for the record: You should use cv::getOptimalNewCameraMatrix and set the alpha parameter to 1. Alpha 0 only shows valid points on the image, alpha 1 shows all the original points as well as black regions. cv::getOptimalNewCameraMatrix aslo gives you a ROI to crop the result from cv::undistort.

0
madduci On

the best would be subclass OpenCV's class and overload the method undistort(), in order to access all the images you need.

0
andrewmkeller On

This code would do the trick:

void loadUndistortedImage(std::string fileName, Mat & outputImage, 
    Mat & cameraMatrix, Mat & distCoeffs) {

    Mat image = imread(fileName, CV_LOAD_IMAGE_GRAYSCALE);

    // setup enlargement and offset for new image
    double y_shift = 60;
    double x_shift = 70;
    Size imageSize = image.size();
    imageSize.height += 2*y_shift;
    imageSize.width += 2*x_shift;

    // create a new camera matrix with the principal point 
    // offest according to the offset above
    Mat newCameraMatrix = cameraMatrix.clone();
    newCameraMatrix.at<double>(0, 2) += x_shift; //adjust c_x by x_shift
    newCameraMatrix.at<double>(1, 2) += y_shift; //adjust c_y by y_shift

    // create undistortion maps
    Mat map1;
    Mat map2;
    initUndistortRectifyMap(cameraMatrix, distCoeffs, Mat(), 
        newCameraMatrix, imageSize, CV_16SC2, map1, map2);

    //remap
    remap(image, outputImage, map1, map2, INTER_LINEAR);
}

See http://docs.opencv.org/2.4/modules/calib3d/doc/camera_calibration_and_3d_reconstruction.html and http://docs.opencv.org/2.4/modules/imgproc/doc/geometric_transformations.html