calibration.py 1.9 KB

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