calibrate.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # Calibrate the fisheye lens
  2. # From https://medium.com/@kennethjiang/calibrate-fisheye-lens-using-opencv-333b05afa0b0
  3. import cv2
  4. assert cv2.__version__[0] == '3', 'The fisheye module requires opencv version >= 3.0.0'
  5. import numpy as np
  6. import os
  7. import glob
  8. CHECKERBOARD = (6,9)
  9. subpix_criteria = (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 0.1)
  10. calibration_flags = cv2.fisheye.CALIB_RECOMPUTE_EXTRINSIC+cv2.fisheye.CALIB_CHECK_COND+cv2.fisheye.CALIB_FIX_SKEW
  11. objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)
  12. objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)
  13. _img_shape = None
  14. objpoints = [] # 3d point in real world space
  15. imgpoints = [] # 2d points in image plane.
  16. images = glob.glob('*.jpg')
  17. for fname in images:
  18. img = cv2.imread(fname)
  19. if _img_shape == None:
  20. _img_shape = img.shape[:2]
  21. else:
  22. assert _img_shape == img.shape[:2], "All images must share the same size."
  23. gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
  24. # Find the chess board corners
  25. ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)
  26. # If found, add object points, image points (after refining them)
  27. if ret == True:
  28. objpoints.append(objp)
  29. cv2.cornerSubPix(gray,corners,(3,3),(-1,-1),subpix_criteria)
  30. imgpoints.append(corners)
  31. N_OK = len(objpoints)
  32. K = np.zeros((3, 3))
  33. D = np.zeros((4, 1))
  34. rvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
  35. tvecs = [np.zeros((1, 1, 3), dtype=np.float64) for i in range(N_OK)]
  36. rms, _, _, _, _ = \
  37. cv2.fisheye.calibrate(
  38. objpoints,
  39. imgpoints,
  40. gray.shape[::-1],
  41. K,
  42. D,
  43. rvecs,
  44. tvecs,
  45. calibration_flags,
  46. (cv2.TERM_CRITERIA_EPS+cv2.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
  47. )
  48. print("Found " + str(N_OK) + " valid images for calibration")
  49. print("DIM=" + str(_img_shape[::-1]))
  50. print("K=np.array(" + str(K.tolist()) + ")")
  51. print("D=np.array(" + str(D.tolist()) + ")")