calibrate.py 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  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. usage:
  6. calibrate.py [--debug <output path>] [--square_size] [<image mask>]
  7. default values:
  8. --debug: ./output/
  9. --square_size: 1.0
  10. <image mask> defaults to ../data/left*.jpg
  11. '''
  12. # Python 2/3 compatibility
  13. from __future__ import print_function
  14. import numpy as np
  15. import cv2
  16. # local modules
  17. from common import splitfn
  18. # built-in modules
  19. import os
  20. if __name__ == '__main__':
  21. import sys
  22. import getopt
  23. from glob import glob
  24. args, img_mask = getopt.getopt(sys.argv[1:], '', ['debug=', 'square_size='])
  25. args = dict(args)
  26. args.setdefault('--debug', './output/')
  27. args.setdefault('--square_size', 1.0)
  28. if not img_mask:
  29. img_mask = '../data/left*.jpg' # default
  30. else:
  31. img_mask = img_mask[0]
  32. img_names = glob(img_mask)
  33. debug_dir = args.get('--debug')
  34. if not os.path.isdir(debug_dir):
  35. os.mkdir(debug_dir)
  36. square_size = float(args.get('--square_size'))
  37. pattern_size = (9, 6)
  38. pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
  39. pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
  40. pattern_points *= square_size
  41. obj_points = []
  42. img_points = []
  43. h, w = 0, 0
  44. img_names_undistort = []
  45. for fn in img_names:
  46. print('processing %s... ' % fn, end='')
  47. img = cv2.imread(fn, 0)
  48. if img is None:
  49. print("Failed to load", fn)
  50. continue
  51. h, w = img.shape[:2]
  52. found, corners = cv2.findChessboardCorners(img, pattern_size)
  53. if found:
  54. term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
  55. cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
  56. if debug_dir:
  57. vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
  58. cv2.drawChessboardCorners(vis, pattern_size, corners, found)
  59. path, name, ext = splitfn(fn)
  60. outfile = debug_dir + name + '_chess.png'
  61. cv2.imwrite(outfile, vis)
  62. if found:
  63. img_names_undistort.append(outfile)
  64. if not found:
  65. print('chessboard not found')
  66. continue
  67. img_points.append(corners.reshape(-1, 2))
  68. obj_points.append(pattern_points)
  69. print('ok')
  70. # calculate camera distortion
  71. rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
  72. print("\nRMS:", rms)
  73. print("camera matrix:\n", camera_matrix)
  74. print("distortion coefficients: ", dist_coefs.ravel())
  75. # undistort the image with the calibration
  76. print('')
  77. for img_found in img_names_undistort:
  78. img = cv2.imread(img_found)
  79. h, w = img.shape[:2]
  80. newcameramtx, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))
  81. dst = cv2.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)
  82. # crop and save the image
  83. x, y, w, h = roi
  84. dst = dst[y:y+h, x:x+w]
  85. outfile = img_found + '_undistorted.png'
  86. print('Undistorted image written to: %s' % outfile)
  87. cv2.imwrite(outfile, dst)
  88. cv2.destroyAllWindows()