LovelessIsma

python_calibrate_fisheye.py

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