int main(int argc, char** argv) { video_resource cam(0); calibrationParameters par = calibrateCamera(10, 7, 5 , cam); par.saveToFile("calibration.xml"); return 0; }
double CustomPattern::calibrate(InputArrayOfArrays objectPoints, InputArrayOfArrays imagePoints, Size imageSize, InputOutputArray cameraMatrix, InputOutputArray distCoeffs, OutputArrayOfArrays rvecs, OutputArrayOfArrays tvecs, int flags, TermCriteria criteria) { return calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags, criteria); }
void stereoCalibThread::monoCalibration(const vector<string>& imageList, int boardWidth, int boardHeight, Mat &K, Mat &Dist) { vector<vector<Point2f> > imagePoints; Size boardSize, imageSize; boardSize.width=boardWidth; boardSize.height=boardHeight; int flags=0; int i; float squareSize = 1.f, aspectRatio = 1.f; Mat view, viewGray; for(i = 0; i<(int)imageList.size();i++) { view = cv::imread(imageList[i], 1); imageSize = view.size(); vector<Point2f> pointbuf; cvtColor(view, viewGray, CV_BGR2GRAY); bool found = false; if(boardType == "CIRCLES_GRID") { found = findCirclesGridDefault(view, boardSize, pointbuf, CALIB_CB_SYMMETRIC_GRID | CALIB_CB_CLUSTERING); } else if(boardType == "ASYMMETRIC_CIRCLES_GRID") { found = findCirclesGridDefault(view, boardSize, pointbuf, CALIB_CB_ASYMMETRIC_GRID | CALIB_CB_CLUSTERING); } else { found = findChessboardCorners( view, boardSize, pointbuf, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FAST_CHECK | CV_CALIB_CB_NORMALIZE_IMAGE); } if(found) { drawChessboardCorners( view, boardSize, Mat(pointbuf), found ); imagePoints.push_back(pointbuf); } } std::vector<Mat> rvecs, tvecs; std::vector<float> reprojErrs; double totalAvgErr = 0; K = Mat::eye(3, 3, CV_64F); if( flags & CV_CALIB_FIX_ASPECT_RATIO ) K.at<double>(0,0) = aspectRatio; Dist = Mat::zeros(4, 1, CV_64F); std::vector<std::vector<Point3f> > objectPoints(1); calcChessboardCorners(boardSize, squareSize, objectPoints[0]); objectPoints.resize(imagePoints.size(),objectPoints[0]); double rms = calibrateCamera(objectPoints, imagePoints, imageSize, K, Dist, rvecs, tvecs,CV_CALIB_FIX_K3); printf("RMS error reported by calibrateCamera: %g\n", rms); cout.flush(); }
void ofxMapaMok::update(){ if( setupMode == SETUP_SELECT ) { cam.enableMouseInput(); } else { // Generate camera matrix given aov guess // cv::Size2i imageSize(width, height); float f = imageSize.width * ofDegToRad(aov); // i think this is wrong, but it's optimized out anyway cv::Point2f c = cv::Point2f(imageSize) * (1. / 2); cv::Mat1d cameraMatrix = (cv::Mat1d(3, 3) << f, 0, c.x, 0, f, c.y, 0, 0, 1); // Generate flags // int flags = CV_CALIB_USE_INTRINSIC_GUESS | //CV_CALIB_FIX_PRINCIPAL_POINT | CV_CALIB_FIX_ASPECT_RATIO | CV_CALIB_FIX_K1 | CV_CALIB_FIX_K2 | CV_CALIB_FIX_K3 | CV_CALIB_ZERO_TANGENT_DIST; vector<cv::Mat> rvecs, tvecs; cv::Mat distCoeffs; vector<vector<cv::Point3f> > referenceObjectPoints(1); vector<vector<cv::Point2f> > referenceImagePoints(1); int n = referencePoints.size(); for(int i = 0; i < n; i++) { if(referencePoints[i]) { referenceObjectPoints[0].push_back(objectPoints[i]); referenceImagePoints[0].push_back(imagePoints[i]); } } const static int minPoints = 6; if(referenceObjectPoints[0].size() >= minPoints) { calibrateCamera(referenceObjectPoints, referenceImagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flags); rvec = rvecs[0]; tvec = tvecs[0]; intrinsics.setup(cameraMatrix, imageSize); modelMatrix = ofxCv::makeMatrix(rvec, tvec); calibrationReady = true; } else { calibrationReady = false; } cam.disableMouseInput(); } }
double CameraCalibrator::calibrate(cv::Size &imageSize) { std::vector<cv::Mat> rvecs, tvecs; return calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs, flag); }
// Calibrate the camera // returns the re-projection error double CameraCalibrator::calibrate(cv::Size &imageSize) { // undistorter must be reinitialized mustInitUndistort= true; // start calibration return calibrateCamera(objectPoints, // the 3D points imagePoints, // the image points imageSize, // image size cameraMatrix, // output camera matrix distCoeffs, // output distortion matrix rvecs, tvecs, // Rs, Ts flag); // set options // ,CV_CALIB_USE_INTRINSIC_GUESS); }
// 进行标定,返回重投影误差 double CameraCalibrator::calibrate(cv::Size &imageSize) { // 必须重新进行去畸变 mustInitUndistort = true; //输出旋转和平移 std::vector<cv::Mat> rvecs, tvecs; // 开始标定 return calibrateCamera(objectPoints, // 3D点 imagePoints, // 图像点 imageSize, // 图像尺寸 cameraMatrix, // 图像尺寸 distCoeffs, // 输出的相机矩阵 rvecs, tvecs, // 旋转和平移 flag); // 额外选项 // ,CV_CALIB_USE_INTRINSIC_GUESS); }
bool Calibration::calibrate() { Mat cameraMatrix = Mat::eye(3, 3, CV_64F); distCoeffs = Mat::zeros(8, 1, CV_64F); updateObjectPoints(); int calibFlags = 0; float rms = calibrateCamera(objectPoints, imagePoints, addedImageSize, cameraMatrix, distCoeffs, boardRotations, boardTranslations, calibFlags); ofLog(OF_LOG_VERBOSE, "calibrateCamera() reports RMS error of " + ofToString(rms)); bool _isReady = checkRange(cameraMatrix) && checkRange(distCoeffs); if(!_isReady) { ofLog(OF_LOG_ERROR, "Calibration::calibrate() failed to calibrate the camera"); } distortedIntrinsics.setup(cameraMatrix, addedImageSize); updateReprojectionError(); updateUndistortion(); return _isReady; }
int main() { printf("beginning camera calibration pgm\n"); create_connect(); enable_servos(); camera_open(LOW_RES); printf("1.0 after initialization\n"); //place create for camera recognition of cube positions forward(9); rightAngle(LEFT); forward(15); rightAngle(RIGHT); calibrateCamera(); printf("the end...\n"); camera_close(); create_disconnect(); return 0; }
void QCvCameraCalibration::calibrate() { this->setEnable(false); QString msg; if (imagePoints.size() >= s.minNumSamples) { // compute board geometry vector<vector<cv::Point3f> > objectPoints(1); calcBoardCornerPositions(s.boardSize, s.squareSize, objectPoints[0]); objectPoints.resize(imagePoints.size(),objectPoints[0]); rmsError = calibrateCamera(objectPoints, imagePoints, imgSize, cameraMatrix, distCoeffs, rvecs, tvecs, CV_CALIB_FIX_K4|CV_CALIB_FIX_K5); msg = "updated object points successfully, RMS = "+QString::number(rmsError); s.bCALIBRATED=true; saveCameraParams(); } else { msg = "Insufficient number of samples taken!"; } emit statusUpdate(msg); this->setEnable(true); }
void CameraCalibration::StereoCalibration() { vector<vector<Point2f> > ImagePoints[2]; vector<vector<Point3f> > ObjectPoints(1); for(int i=0; i<BoardSize.height; i++) for(int j=0; j<BoardSize.width; j++) ObjectPoints.at(0).push_back(Point3f(float( j*SquareSize ), float( i*SquareSize ), 0)); ObjectPoints.resize(NumFrames, ObjectPoints[0]); vector<Mat> RVecs[2], TVecs[2]; double rms; for(int c_idx=0; c_idx<2; c_idx++) { for(int i=0; i < NumFrames; i++) { Mat img = imread(data_path+"/"+calib_params[c_idx].ImageList.at(i), CV_LOAD_IMAGE_COLOR); vector<Point2f> pointBuf; bool found = false; found = findChessboardCorners(img, BoardSize, pointBuf, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE); if(found) { Mat viewGray; cvtColor(img, viewGray, CV_BGR2GRAY); cornerSubPix(viewGray, pointBuf, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 100, 0.01)); //drawChessboardCorners(img, BoardSize, Mat(pointBuf), found); //namedWindow("Image View", CV_WINDOW_AUTOSIZE); //imshow("Image View", img); //waitKey(); } else { cerr << i << "th image cannot be found a pattern." << endl; exit(EXIT_FAILURE); } ImagePoints[c_idx].push_back(pointBuf); } calib_params[c_idx].DistCoeffs = Mat::zeros(8, 1, CV_64F); calib_params[c_idx].CameraMatrix = initCameraMatrix2D(ObjectPoints, ImagePoints[c_idx], ImageSize, 0); rms = calibrateCamera(ObjectPoints, ImagePoints[c_idx], ImageSize, calib_params[c_idx].CameraMatrix, calib_params[c_idx].DistCoeffs, RVecs[c_idx], TVecs[c_idx], CV_CALIB_USE_INTRINSIC_GUESS | CV_CALIB_FIX_K3 | CV_CALIB_FIX_K4 | CV_CALIB_FIX_K5 | CV_CALIB_FIX_K6); cout << c_idx << " camera re-projection error reported by calibrateCamera: "<< rms << endl; } rms = stereoCalibrate(ObjectPoints, ImagePoints[0], ImagePoints[1], calib_params[0].CameraMatrix, calib_params[0].DistCoeffs, calib_params[1].CameraMatrix, calib_params[1].DistCoeffs, ImageSize, stereo_params->R, stereo_params->T, stereo_params->E, stereo_params->F, TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5)); cout << "Stereo re-projection error reported by stereoCalibrate: " << rms << endl; cout << "Fundamental Matrix reprojection error: " << FundamentalMatrixQuality(ImagePoints[0], ImagePoints[1], calib_params[0].CameraMatrix, calib_params[1].CameraMatrix, calib_params[0].DistCoeffs, calib_params[1].DistCoeffs, stereo_params->F) << endl; // Transfer matrix from OpenCV Mat to Pangolin matrix CvtCameraExtrins(RVecs, TVecs); Timer PangolinTimer; // Stereo rectification stereoRectify(calib_params[0].CameraMatrix, calib_params[0].DistCoeffs, calib_params[1].CameraMatrix, calib_params[1].DistCoeffs, ImageSize, stereo_params->R, stereo_params->T, rect_params->LeftRot, rect_params->RightRot, rect_params->LeftProj, rect_params->RightProj, rect_params->Disp2DepthReProjMat, CALIB_ZERO_DISPARITY, // test later 1, // test later ImageSize, &rect_params->LeftRoi, &rect_params->RightRoi); cout << "\nStereo rectification using calibration spent: " << PangolinTimer.getElapsedTimeInMilliSec() << "ms." << endl; rect_params->isVerticalStereo = fabs(rect_params->RightProj.at<double>(1, 3)) > fabs(rect_params->RightProj.at<double>(0, 3)); // Get the rectification re-map index initUndistortRectifyMap(calib_params[0].CameraMatrix, calib_params[0].DistCoeffs, rect_params->LeftRot, rect_params->LeftProj, ImageSize, CV_16SC2, rect_params->LeftRMAP[0], rect_params->LeftRMAP[1]); initUndistortRectifyMap(calib_params[1].CameraMatrix, calib_params[1].DistCoeffs, rect_params->RightRot, rect_params->RightProj, ImageSize, CV_16SC2, rect_params->RightRMAP[0], rect_params->RightRMAP[1]); }
void CameraCalibration::MonoCalibration() { vector<vector<Point2f> > ImagePoints; for(int i=0; i < NumFrames; i++) { Mat img = imread(calib_params[0].ImageList.at(i), CV_LOAD_IMAGE_COLOR); vector<Point2f> pointBuf; bool found = false; found = findChessboardCorners(img, BoardSize, pointBuf, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE); if(found) { Mat viewGray; cvtColor(img, viewGray, CV_BGR2GRAY); cornerSubPix(viewGray, pointBuf, Size(11, 11), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 100, 0.01)); // drawChessboardCorners(img_left, calib_params.BoardSize, Mat(left_pointBuf), found_left); // imshow("Left Image View", img_left); // drawChessboardCorners(img_right, calib_params.BoardSize, Mat(right_pointBuf), found_right); // imshow("Right Image View", img_right); // waitKey(); } else { cerr << i << "th image cannot be found a pattern." << endl; exit(EXIT_FAILURE); } ImagePoints.push_back(pointBuf); } vector<vector<Point3f> > ObjectPoints(1); for(int i=0; i<BoardSize.height; i++) for(int j=0; j<BoardSize.width; j++) ObjectPoints.at(0).push_back(Point3f(float( j*SquareSize ), float( i*SquareSize ), 0)); ObjectPoints.resize(ImagePoints.size(), ObjectPoints[0]); vector<Mat> RVecs, TVecs; calib_params->DistCoeffs = Mat::zeros(8, 1, CV_64F); calib_params->CameraMatrix = initCameraMatrix2D(ObjectPoints, ImagePoints, ImageSize, 0); double rms = calibrateCamera(ObjectPoints, ImagePoints, ImageSize, calib_params->CameraMatrix, calib_params->DistCoeffs, RVecs, TVecs, CV_CALIB_USE_INTRINSIC_GUESS | CV_CALIB_FIX_K3 | CV_CALIB_FIX_K4 | CV_CALIB_FIX_K5 | CV_CALIB_FIX_K6); cout << "Camera re-projection error reported by calibrateCamera: "<< rms << endl; // Transfer matrix from OpenCV Mat to Pangolin matrix CvtCameraExtrins(&RVecs, &TVecs); }
int main( int argc, char** argv ){ CvCapture* capture = NULL; IplImage* src = NULL; IplImage* src2 = NULL; IplImage* gray = NULL; IplImage* output = NULL; CvMat* cornerPoints; CvMat* objectPoints; CvMat pointsNumMat; CvPoint2D32f* points; int pointsNum[1]; ChessBoard chess; int pointsPerScene; int detectedPointsNum; int allPointsFound; int i, j; char key; int camID; char* windowName = "extrinsic calibration"; capture = cvCreateCameraCapture(0); if(!capture) { fprintf(stderr, "ERROR: capture is NULL \n"); return(-1); } chess.dx = CHESS_ROW_DX; chess.dy = CHESS_COL_DY; chess.patternSize.width = CHESS_ROW_NUM; chess.patternSize.height = CHESS_COL_NUM; pointsPerScene = chess.patternSize.width * chess.patternSize.height; cornerPoints = cvCreateMat(pointsPerScene, 2, CV_32F); objectPoints = cvCreateMat(pointsPerScene, 3, CV_32F); pointsNum[0] = pointsPerScene; pointsNumMat = cvMat(1, 1, CV_32S, pointsNum); points = (CvPoint2D32f*)malloc( sizeof(CvPoint2D32f) * pointsPerScene ) ; src = cvQueryFrame(capture); if(src == NULL){ fprintf(stderr, "Could not grab and retrieve frame...\n"); return(-1); } src2 = cvCreateImage(cvSize(src->width, src->height), src->depth, 3); output = cvCreateImage(cvSize(src->width, src->height), src->depth, 3); cvCopy( src, src2, NULL ); gray = cvCreateImage(cvSize(src2->width, src2->height), src2->depth, 1); cvNamedWindow( windowName, CV_WINDOW_AUTOSIZE ); while( 1 ){ src = cvQueryFrame(capture); if( !src ) { break; } cvCopy( src, src2, NULL ); cvCopy( src2, output, NULL ); cvCvtColor(src2, gray, CV_BGR2GRAY); if( cvFindChessboardCorners( gray, chess.patternSize, points, &detectedPointsNum, CV_CALIB_CB_ADAPTIVE_THRESH ) ){ cvFindCornerSubPix(gray, points, detectedPointsNum, cvSize(5, 5), cvSize(-1, -1), cvTermCriteria(CV_TERMCRIT_ITER, 100, 0.1)); allPointsFound = 1; } else { allPointsFound = 0; } cvDrawChessboardCorners( src2, chess.patternSize, points, detectedPointsNum, allPointsFound ); cvShowImage(windowName, src2); key = cvWaitKey( 20 ); if(key == RETURN && allPointsFound ){ store2DCoordinates( cornerPoints, points, chess, 0 ); store3DCoordinates( objectPoints, chess, 0 ); calibrateCamera("intrinsic_param_ref.txt", "extrinsic_param.txt", cornerPoints, objectPoints ); cvSaveImage( "board.jpg", output, 0 ); break; } else if(key == ESCAPE) { break; } } cvDestroyWindow( windowName ); cvReleaseCapture(&capture); free(points); cvReleaseMat(&cornerPoints); cvReleaseMat(&objectPoints); cvReleaseImage(&gray); cvReleaseImage(&src2); return(0); }
Calib::Calib() { Size boardSize(6,5); // Chessboard' size in corners with both color (nb of squares -1) int widthSquare = 40; // Width of a square in mm int heightSquare = 27; vector <Mat> images; // Getting the four images of the chessboard string imageFileName = "../src/mire1.jpg"; images.push_back(imread(imageFileName, 1)); imageFileName = "../src/mire2.jpg"; images.push_back(imread(imageFileName, 1)); imageFileName = "../src/mire3.jpg"; images.push_back(imread(imageFileName, 1)); imageFileName = "../src/mire4.jpg"; images.push_back(imread(imageFileName, 1)); Size imageSize = images.at(0).size(); // Find chessboard's corners in the scene for the 4 images vector<vector<Point2f> > cornersScene(1); vector<Mat> imagesGray; imagesGray.resize(4); for (int i=0; i<4; i++) { if(images.at(i).empty()) { cerr << "Image not read correctly!" << endl; exit(-1); } bool patternFound = findChessboardCorners(images.at(i), boardSize, cornersScene[0]); if(!patternFound) { cerr << "Could not find chess board!" << endl; exit(-1); } // Improve corner's coordinate accuracy cvtColor(images.at(i), imagesGray.at(i), CV_RGB2GRAY); cornerSubPix(imagesGray.at(i), cornersScene[0], Size(3,2), Size(-1,-1), TermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, 30, 0.1)); // Drawing the corners drawChessboardCorners(images.at(i), boardSize, Mat(cornersScene[0]), patternFound ); imshow("Corners find", images.at(i)); int keyPressed; /*do { keyPressed = waitKey(0); } while (keyPressed != 27);*/ } // Getting the chessboard's corners on the mire's image vector<vector<Point3f> > cornersMire(1); for( int y = 0; y < boardSize.height; y++ ) { for( int x = 0; x < boardSize.width; x++ ) { cornersMire[0].push_back(cv::Point3f(float(x*widthSquare), float(y*heightSquare), 0)); } } // Getting the camera's parameters Mat distortionCoefficients = Mat::zeros(8, 1, CV_64F); Mat cameraMatrix = Mat::eye(3, 3, CV_64F); calibrateCamera(cornersMire, cornersScene, imageSize, cameraMatrix, distortionCoefficients, rotationVectors, translationVectors); //cout << "Camera matrix: " << cameraMatrix << endl; //cout << "Distortion _coefficients: " << distortionCoefficients << endl; cout << rotationVectors.at(0) << endl; cout << translationVectors.at(0) << endl; }
bool CSingleCalib::ExSingleCalib() { string *strImageName1 = m_strImageName; string *strImageName2 = m_strImageName; string *strImageName3 = m_strImageName; bool bRet = false; do{ cout << "ExSingleCalib !" << endl; /**************************************************************** * test ****************************************************************/ // vector<Point2f> imageCorners; // Size boardSize(ChessBoardSize_w, ChessBoardSize_h); // Mat img = imread(*m_strImageName); // if (!img.data) // { // cout << "no img" << endl; // break; // } // bool found = findChessboardCorners(img, boardSize, imageCorners); // drawChessboardCorners(img, boardSize, imageCorners, found); // namedWindow("test"); // imshow("test", img); // waitKey(); /* vector<Point3f> imgPoint; for (int rowIndex = 0; rowIndex < ChessBoardSize_h; ++rowIndex) { for (int colIndex = 0; colIndex < ChessBoardSize_w; ++colIndex) { imgPoint.push_back(Point3f(rowIndex * SquareWidth, colIndex * SquareWidth, 0)); } } for (int imgIndex = 0; imgIndex < NImage; ++imgIndex) { objRealPoints.push_back(imgPoint); } */ //从棋盘格添加角点 if (!addChessBoardPoints(strImageName2)) { cout << "add chessBoard Points failed! " << endl; } //标定相机 // setCalibrationFlag(true, true); // calibrate(Size(CAMERA_WIDTH, CAMERA_HEIGHT)); calibrateCamera(objectPoints, imagePoints, Size(CAMERA_WIDTH, CAMERA_HEIGHT), cameraMatrix, distCoeffs, rvecs, tvecs, flag); ////////////////////////////////////////////////////////// ////// 这里可以矫正图片 ///////////////////////////////////////////////////////// // Mat image = cv::imread(*(strImageName3 + 8)); // cv::Mat uImage = remap(image); // imshow("Orginal Image", image); // imshow("Undistored Image", uImage); bRet = true; } while (false); return bRet; }
bool Camera::runCalibration( vector<vector<Point2f> > imagePoints, Size imageSize, Size boardSize, float squareSize, float aspectRatio, int flags, Mat& cameraMatrix, Mat& distCoeffs, vector<Mat>& rvecs, vector<Mat>& tvecs, vector<float>& reprojErrs, double& totalAvgErr) { cameraMatrix = Mat::eye(3, 3, CV_64F); if( flags & CV_CALIB_FIX_ASPECT_RATIO ) cameraMatrix.at<double>(0,0) = aspectRatio; distCoeffs = Mat::zeros(4, 1, CV_64F); vector<vector<Point3f> > objectPoints(1); calcChessboardCorners(boardSize, squareSize, objectPoints[0]); objectPoints.resize(imagePoints.size(),objectPoints[0]); double rms = calibrateCamera(objectPoints, imagePoints, imageSize, cameraMatrix, distCoeffs, rvecs, tvecs,CV_CALIB_FIX_K3); printf("RMS error reported by calibrateCamera: %g\n", rms); bool ok = checkRange(cameraMatrix) && checkRange(distCoeffs); totalAvgErr = computeReprojectionErrors(objectPoints, imagePoints, rvecs, tvecs, cameraMatrix, distCoeffs, reprojErrs); return ok; }