public static void Calibrate() { objectPoints = new MCvPoint3D32f[frames][]; imgPoints = new VectorOfPointF[frames]; rVecs = new Mat[frames]; tVecs = new Mat[frames]; width = 5; height = 5; patternSize = new Size(width, height); var files = Directory.GetFiles(@"--location--"); for (int k = 0; k < frames; k++) { grayFrame = CvInvoke.Imread(files[k], ImreadModes.Grayscale); found = CvInvoke.FindChessboardCorners(grayFrame, patternSize, cornerPoints, CalibCbType.AdaptiveThresh); if (found) { //read more about its use and last 3 arguments CvInvoke.CornerSubPix(grayFrame, cornerPoints, new Size(11, 11), new Size(-1, -1), new MCvTermCriteria(30, 0.1)); var objectList = new List <MCvPoint3D32f> (); // populating real world coordinates of the chess board corners for (int i = 0; i < patternSize.Height; i++) { for (int j = 0; j < patternSize.Width; j++) { objectList.Add(new MCvPoint3D32f(j * squareSize, i * squareSize, 0.0f)); } } objectPoints[k] = objectList.ToArray(); imgPoints[k] = cornerPoints; } } // Calibrate Camera double error = CalibrateCamera(objectPoints, imgPoints.Select(a => a.ToArray()).ToArray(), grayFrame.Size, cameraMatrix, distCoeffs, CalibType.RationalModel, new MCvTermCriteria(30, 0.1), out rVecs, out tVecs); // Get Optimal new Camera Matrix var imgSize = CvInvoke.Imread(files[4], ImreadModes.Grayscale).Size; Rectangle ROI = new Rectangle(); newMatrix = CvInvoke.GetOptimalNewCameraMatrix(cameraMatrix, distCoeffs, imgSize, 1, imgSize, ref ROI); Mat dupFrame = grayFrame.Clone(); // Undistort CvInvoke.Undistort(grayFrame, dupFrame, newMatrix, distCoeffs); var frame = dupFrame.Clone(); CvInvoke.Imwrite("undistorted.png", frame); // Region of Interest //var buffer_im = _frame.ToImage<Bgr, byte> (); //buffer_im.ROI = ROI; //Image<Bgr, byte> cropped_im = buffer_im.Copy (); //cropped_im.Save ("cropped.png"); // Drawing detected chessboard corners CvInvoke.DrawChessboardCorners(grayFrame, patternSize, cornerPoints, found); //CvInvoke.Imwrite ("chessboard.png", _frame); CvInvoke.Imwrite("distorted.png", grayFrame); Console.WriteLine(MeanError()); }