728x90
using OpenCvSharp;
using System;
using System.Collections.Generic;
class CameraCalibration
{
static void Main()
{
TermCriteria criteria = new TermCriteria(CriteriaTypes.Eps | CriteriaTypes.MaxIter, 30, 0.001);
Size patternSize = new Size(7, 6);
double squareSize = 20.0; // Assuming millimeters
List<Point3f[]> objectPoints = new List<Point3f[]>();
List<Point2f[]> imagePoints = new List<Point2f[]>();
Point3f[] objp = new Point3f[patternSize.Width * patternSize.Height];
for (int y = 0; y < patternSize.Height; y++)
{
for (int x = 0; x < patternSize.Width; x++)
{
objp[y * patternSize.Width + x] = new Point3f(x * squareSize, y * squareSize, 0);
}
}
string[] images = System.IO.Directory.GetFiles("calibration_images", "*.jpg");
foreach (string fname in images)
{
using Mat img = Cv2.ImRead(fname, ImreadModes.Color);
using Mat gray = new Mat();
Cv2.CvtColor(img, gray, ColorConversionCodes.BGR2GRAY);
Point2f[] corners;
bool found = Cv2.FindChessboardCorners(gray, patternSize, out corners);
if (found)
{
objectPoints.Add(objp);
Cv2.CornerSubPix(gray, corners, new Size(11, 11), new Size(-1, -1), criteria);
imagePoints.Add(corners);
}
}
Mat cameraMatrix = new Mat(3, 3, MatType.CV_64FC1);
Mat distCoeffs = new Mat(8, 1, MatType.CV_64FC1);
Vec3d[] rotationVectors;
Vec3d[] translationVectors;
double error = Cv2.CalibrateCamera(objectPoints, imagePoints, gray.Size(), cameraMatrix, distCoeffs, out rotationVectors, out translationVectors);
Console.WriteLine($"Reprojection error: {error}");
}
}
728x90
728x90