python
"""
dahua 相机
120张样本的内参结果
internal matrix:
[[1.67718566e+03 0.00000000e+00 1.30574747e+03]
[0.00000000e+00 1.66563629e+03 1.02422126e+03]
[0.00000000e+00 0.00000000e+00 1.00000000e+00]]
distortion cofficients:
[[-0.37982045 0.20745996 0.00073598 0.0021865 -0.07472313]]
Average Error of Reproject: 0.05167174586350024
"""
import os
import numpy as np
import cv2
import glob
def dedistortion( img_dir, img_type, save_dir, inter_corner_shape, mat_inter, coff_dis):
w,h = inter_corner_shape
images = glob.glob(img_dir + os.sep + '**.' + img_type)
for fname in images:
img_name = fname.split(os.sep)[-1]
img = cv2.imread(fname)
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mat_inter,coff_dis,(w,h),0,(w,h))
dst = cv2.undistort(img, mat_inter, coff_dis, None, newcameramtx)
cv2.imwrite(save_dir + os.sep + img_name, dst)
print('Dedistorted images have been saved to: %s successfully.' %save_dir)
def save_cam_param(cameraMatrix, distCoeffs, file_path):
file_yaml = file_path + "cam_param.yaml"
fs = cv2.FileStorage(file_yaml, cv2.FileStorage_WRITE)
fs.write("cameraMatrix", cameraMatrix)
fs.write("distCoeffs", distCoeffs)
fs.release()
def calib(inter_corner_shape, size_per_grid, img_dir, img_type, cam_param_path):
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
w, h = inter_corner_shape
cp_int = np.zeros((w * h, 3), np.float32)
cp_int[:, :2] = np.mgrid[0:w, 0:h].T.reshape(-1, 2)
cp_world = cp_int * size_per_grid
obj_points = []
img_points = []
images = glob.glob(img_dir + os.sep + '**.' + img_type)
for fname in images:
gray_img = cv2.imread(fname, cv2.IMREAD_GRAYSCALE)
ret, cp_img = cv2.findChessboardCorners(gray_img, (w, h), None)
if ret == True:
cv2.cornerSubPix(gray_img,cp_img,(11,11),(-1,-1),criteria)
obj_points.append(cp_world)
img_points.append(cp_img)
ret, mat_inter, coff_dis, v_rot, v_trans = cv2.calibrateCamera(obj_points, img_points, gray_img.shape[::-1], None, None)
print(("ret:"), ret)
print(("internal matrix:\n"), mat_inter)
print(("distortion cofficients:\n"), coff_dis)
print(("rotation vectors:\n"), v_rot)
print(("translation vectors:\n"), v_trans)
save_cam_param(mat_inter, coff_dis, cam_param_path)
total_error = 0
for i in range(len(obj_points)):
img_points_repro, _ = cv2.projectPoints(obj_points[i], v_rot[i], v_trans[i], mat_inter, coff_dis)
error = cv2.norm(img_points[i], img_points_repro, cv2.NORM_L2) / len(img_points_repro)
total_error += error
print(("Average Error of Reproject: "), total_error / len(obj_points))
return mat_inter, coff_dis
if __name__ == '__main__':
inter_corner_shape = (12, 8)
size_per_grid = 0.02
img_dir = "..\pic_sample"
img_type = "bmp"
cam_param_path = "F:\Project\Calibrate_Cam\cam_param\"
# 求取相机参数,主要关注内参
calib(inter_corner_shape, size_per_grid, img_dir, img_type, cam_param_path)
# 校正
# 读取相机内参
fs2 = cv2.FileStorage('../cam_param/cam_param.yaml', cv2.FileStorage_READ)
cameraMatrix = fs2.getNode('cameraMatrix').mat()
distCoeffs = fs2.getNode('distCoeffs').mat()
fs2.release()
# 校正图片
inter_corner_shape = (12, 8)
img_type = "bmp"
distortion_path = "F:\Project\Calibrate_Cam\pic_distortion"
correct_path = "F:\Project\Calibrate_Cam\pic_correct"
dedistortion(distortion_path, img_type, correct_path, inter_corner_shape, cameraMatrix, distCoeffs)
C++
#include <iostream>
#include <sstream>
#include <time.h>
#include <stdio.h>
#include <fstream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
#define calibration
int main()
{
#ifdef calibration
ifstream fin("right_img.txt");
ofstream fout("caliberation_result_right.txt");
int image_count = 0;
Size image_size;
Size board_size = Size(11,8);
vector<Point2f> image_points_buf;
vector<vector<Point2f>> image_points_seq;
string filename;
vector<string> filenames;
while (getline(fin, filename))
{
++image_count;
Mat imageInput = imread(filename);
filenames.push_back(filename);
if (image_count == 1)
{
image_size.width = imageInput.cols;
image_size.height = imageInput.rows;
}
if (0 == findChessboardCorners(imageInput, board_size, image_points_buf))
{
cout << "**" << filename << "** can not find chessboard corners!\n";
exit(1);
}
else
{
Mat view_gray;
cvtColor(imageInput, view_gray, CV_RGB2GRAY);
cornerSubPix(view_gray, image_points_buf, Size(5, 5), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1));
image_points_seq.push_back(image_points_buf);
drawChessboardCorners(view_gray, board_size, image_points_buf, false);
imshow("Camera Calibration", view_gray);
waitKey(500);
}
}
int CornerNum = board_size.width * board_size.height;
Size square_size = Size(60, 60);
vector<vector<Point3f>> object_points;
Mat cameraMatrix = Mat(3, 3, CV_32FC1, Scalar::all(0));
vector<int> point_counts;
Mat distCoeffs = Mat(1, 5, CV_32FC1, Scalar::all(0));
vector<Mat> tvecsMat;
vector<Mat> rvecsMat;
int i, j, t;
for (t = 0; t<image_count; t++)
{
vector<Point3f> tempPointSet;
for (i = 0; i<board_size.height; i++)
{
for (j = 0; j<board_size.width; j++)
{
Point3f realPoint;
realPoint.x = i * square_size.width;
realPoint.y = j * square_size.height;
realPoint.z = 0;
tempPointSet.push_back(realPoint);
}
}
object_points.push_back(tempPointSet);
}
for (i = 0; i<image_count; i++)
{
point_counts.push_back(board_size.width * board_size.height);
}
calibrateCamera(object_points, image_points_seq, image_size, cameraMatrix, distCoeffs, rvecsMat, tvecsMat, 0);
double total_err = 0.0;
double err = 0.0;
vector<Point2f> image_points2;
fout << "每幅图像的标定误差:\n";
for (i = 0; i<image_count; i++)
{
vector<Point3f> tempPointSet = object_points[i];
projectPoints(tempPointSet, rvecsMat[i], tvecsMat[i], cameraMatrix, distCoeffs, image_points2);
vector<Point2f> tempImagePoint = image_points_seq[i];
Mat tempImagePointMat = Mat(1, tempImagePoint.size(), CV_32FC2);
Mat image_points2Mat = Mat(1, image_points2.size(), CV_32FC2);
for (int j = 0; j < tempImagePoint.size(); j++)
{
image_points2Mat.at<Vec2f>(0, j) = Vec2f(image_points2[j].x, image_points2[j].y);
tempImagePointMat.at<Vec2f>(0, j) = Vec2f(tempImagePoint[j].x, tempImagePoint[j].y);
}
err = norm(image_points2Mat, tempImagePointMat, NORM_L2);
total_err += err /= point_counts[i];
fout << "第" << i + 1 << "幅图像的平均误差:" << err << "像素" << endl;
}
fout << "总体平均误差:" << total_err / image_count << "像素" << endl << endl;
Mat rotation_matrix = Mat(3, 3, CV_32FC1, Scalar::all(0));
fout << "相机内参数矩阵:" << endl;
fout << cameraMatrix << endl << endl;
fout << "畸变系数:\n";
fout << distCoeffs << endl << endl << endl;
for (int i = 0; i<image_count; i++)
{
fout << "第" << i + 1 << "幅图像的旋转向量:" << endl;
fout << tvecsMat[i] << endl;
Rodrigues(tvecsMat[i], rotation_matrix);
fout << "第" << i + 1 << "幅图像的旋转矩阵:" << endl;
fout << rotation_matrix << endl;
fout << "第" << i + 1 << "幅图像的平移向量:" << endl;
fout << rvecsMat[i] << endl << endl;
}
fout << endl;
Mat mapx = Mat(image_size, CV_32FC1);
Mat mapy = Mat(image_size, CV_32FC1);
Mat R = Mat::eye(3, 3, CV_32F);
string imageFileName;
std::stringstream StrStm;
for (int i = 0; i != image_count; i++)
{
initUndistortRectifyMap(cameraMatrix, distCoeffs, R, cameraMatrix, image_size, CV_32FC1, mapx, mapy);
Mat imageSource = imread(filenames[i]);
Mat newimage = imageSource.clone();
remap(imageSource, newimage, mapx, mapy, INTER_LINEAR);
StrStm.clear();
imageFileName.clear();
StrStm << i + 1;
StrStm >> imageFileName;
imageFileName += "_d.jpg";
imwrite(imageFileName, newimage);
}
fin.close();
fout.close();
#else
Mat src = imread("F:\\lane_line_detection\\left_img\\1.jpg");
Mat distortion = src.clone();
Mat camera_matrix = Mat(3, 3, CV_32FC1);
Mat distortion_coefficients;
FileStorage file_storage("F:\\lane_line_detection\\left_img\\Intrinsic.xml", FileStorage::READ);
file_storage["CameraMatrix"] >> camera_matrix;
file_storage["Dist"] >> distortion_coefficients;
file_storage.release();
cv::undistort(src, distortion, camera_matrix, distortion_coefficients);
cv::imshow("img", src);
cv::imshow("undistort", distortion);
cv::imwrite("undistort.jpg", distortion);
cv::waitKey(0);
#endif
return 0;
}