calibration.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import cv2
  2. import os
  3. import numpy as np
  4. import sys
  5. import os
  6. sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
  7. from default_config import *
  8. # LỰa chọn độ phân giải bằng cách thay đổi set_resolution
  9. resolution = 'original'
  10. # Checker board size
  11. CHESS_BOARD_DIM = (9, 6)
  12. # termination criteria
  13. criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  14. calib_data_path = f"camera_calibration/calib_data/{resolution}"
  15. if not os.path.exists(calib_data_path):
  16. os.makedirs(calib_data_path)
  17. # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
  18. obj_3D = np.zeros((CHESS_BOARD_DIM[0] * CHESS_BOARD_DIM[1], 3), np.float32)
  19. obj_3D[:, :2] = np.mgrid[0 : CHESS_BOARD_DIM[0], 0 : CHESS_BOARD_DIM[1]].T.reshape(
  20. -1, 2
  21. )
  22. obj_3D *= SQUARE_SIZE
  23. print(obj_3D)
  24. # Arrays to store object points and image points from all the images.
  25. obj_points_3D = [] # 3d point in real world space
  26. img_points_2D = [] # 2d points in image plane.
  27. # The images directory path
  28. image_dir_path = f"camera_calibration/images/{resolution}"
  29. files = os.listdir(image_dir_path)
  30. for file in files:
  31. print(file)
  32. imagePath = os.path.join(image_dir_path, file)
  33. image = cv2.imread(imagePath)
  34. grayScale = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  35. ret, corners = cv2.findChessboardCorners(image, CHESS_BOARD_DIM, None)
  36. if ret == True:
  37. obj_points_3D.append(obj_3D)
  38. corners2 = cv2.cornerSubPix(grayScale, corners, (3, 3), (-1, -1), criteria)
  39. img_points_2D.append(corners2)
  40. img = cv2.drawChessboardCorners(image, CHESS_BOARD_DIM, corners2, ret)
  41. cv2.destroyAllWindows()
  42. ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
  43. obj_points_3D, img_points_2D, grayScale.shape[::-1], None, None
  44. )
  45. print("calibrated")
  46. np.savez(
  47. f"{calib_data_path}/MultiMatrix",
  48. camMatrix=mtx,
  49. distCoef=dist,
  50. rVector=rvecs,
  51. tVector=tvecs,
  52. )
  53. print(f'saved to {calib_data_path}/MultiMatrix')