Path: blob/master/modules/python/test/test_calibration.py
16337 views
#!/usr/bin/env python12'''3camera calibration for distorted images with chess board samples4reads distorted images, calculates the calibration and write undistorted images5'''67# Python 2/3 compatibility8from __future__ import print_function910import numpy as np11import cv2 as cv1213from tests_common import NewOpenCVTests1415class calibration_test(NewOpenCVTests):1617def test_calibration(self):18img_names = []19for i in range(1, 15):20if i < 10:21img_names.append('samples/data/left0{}.jpg'.format(str(i)))22elif i != 10:23img_names.append('samples/data/left{}.jpg'.format(str(i)))2425square_size = 1.026pattern_size = (9, 6)27pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)28pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)29pattern_points *= square_size3031obj_points = []32img_points = []33h, w = 0, 034for fn in img_names:35img = self.get_sample(fn, 0)36if img is None:37continue3839h, w = img.shape[:2]40found, corners = cv.findChessboardCorners(img, pattern_size)41if found:42term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1)43cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term)4445if not found:46continue4748img_points.append(corners.reshape(-1, 2))49obj_points.append(pattern_points)5051# calculate camera distortion52rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), None, None, flags = 0)5354eps = 0.0155normCamEps = 10.056normDistEps = 0.055758cameraMatrixTest = [[ 532.80992189, 0., 342.4952186 ],59[ 0., 532.93346422, 233.8879292 ],60[ 0., 0., 1. ]]6162distCoeffsTest = [ -2.81325576e-01, 2.91130406e-02,631.21234330e-03, -1.40825372e-04, 1.54865844e-01]6465self.assertLess(abs(rms - 0.196334638034), eps)66self.assertLess(cv.norm(camera_matrix - cameraMatrixTest, cv.NORM_L1), normCamEps)67self.assertLess(cv.norm(dist_coefs - distCoeffsTest, cv.NORM_L1), normDistEps)68697071if __name__ == '__main__':72NewOpenCVTests.bootstrap()737475