test_calibration.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. #!/usr/bin/env python
  2. '''
  3. camera calibration for distorted images with chess board samples
  4. reads distorted images, calculates the calibration and write undistorted images
  5. '''
  6. # Python 2/3 compatibility
  7. from __future__ import print_function
  8. import numpy as np
  9. import cv2 as cv
  10. from tests_common import NewOpenCVTests
  11. class calibration_test(NewOpenCVTests):
  12. def test_calibration(self):
  13. img_names = []
  14. for i in range(1, 15):
  15. if i < 10:
  16. img_names.append('samples/data/left0{}.jpg'.format(str(i)))
  17. elif i != 10:
  18. img_names.append('samples/data/left{}.jpg'.format(str(i)))
  19. square_size = 1.0
  20. pattern_size = (9, 6)
  21. pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
  22. pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
  23. pattern_points *= square_size
  24. obj_points = []
  25. img_points = []
  26. h, w = 0, 0
  27. for fn in img_names:
  28. img = self.get_sample(fn, 0)
  29. if img is None:
  30. continue
  31. h, w = img.shape[:2]
  32. found, corners = cv.findChessboardCorners(img, pattern_size)
  33. if found:
  34. term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1)
  35. cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
  36. if not found:
  37. continue
  38. img_points.append(corners.reshape(-1, 2))
  39. obj_points.append(pattern_points)
  40. # calculate camera distortion
  41. rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), None, None, flags = 0)
  42. eps = 0.01
  43. normCamEps = 10.0
  44. normDistEps = 0.05
  45. cameraMatrixTest = [[ 532.80992189, 0., 342.4952186 ],
  46. [ 0., 532.93346422, 233.8879292 ],
  47. [ 0., 0., 1. ]]
  48. distCoeffsTest = [ -2.81325576e-01, 2.91130406e-02,
  49. 1.21234330e-03, -1.40825372e-04, 1.54865844e-01]
  50. self.assertLess(abs(rms - 0.196334638034), eps)
  51. self.assertLess(cv.norm(camera_matrix - cameraMatrixTest, cv.NORM_L1), normCamEps)
  52. self.assertLess(cv.norm(dist_coefs - distCoeffsTest, cv.NORM_L1), normDistEps)
  53. if __name__ == '__main__':
  54. NewOpenCVTests.bootstrap()