-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcamera_calibration.py
More file actions
128 lines (95 loc) · 4.67 KB
/
camera_calibration.py
File metadata and controls
128 lines (95 loc) · 4.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# This file was obtained from this tutorial https://automaticaddison.com/how-to-perform-pose-estimation-using-an-aruco-marker/
# it was modified to properly run as there were previous issues with the calibration
# This file is based heavily off this tutorial on the official openCV file https://docs.opencv.org/4.x/dc/dbb/tutorial_py_calibration.html
'''
Welcome to the Camera Calibration Program!
This program:
- Performs camera calibration using a chessboard.
'''
from __future__ import print_function # Python 2/3 compatibility
import cv2 # Import the OpenCV library to enable computer vision
import numpy as np # Import the NumPy scientific computing library
import glob # Used to get retrieve files that have a specified pattern
import sys
# Project: Camera Calibration Using Python and OpenCV
# Date created: 12/19/2021
# Python version: 3.8
# Chessboard dimensions
number_of_squares_X = 10 # Number of chessboard squares along the x-axis
number_of_squares_Y = 7 # Number of chessboard squares along the y-axis
nX = number_of_squares_X - 1 # Number of interior corners along x-axis
nY = number_of_squares_Y - 1 # Number of interior corners along y-axis
square_size = 0.025 # Size, in meters, of a square side
# Set termination criteria. We stop either when an accuracy is reached or when
# we have finished a certain number of iterations.
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Define real world coordinates for points in the 3D coordinate frame
# Object points are (0,0,0), (1,0,0), (2,0,0) ...., (5,8,0)
object_points_3D = np.zeros((nX * nY, 3), np.float32)
# These are the x and y coordinates
object_points_3D[:,:2] = np.mgrid[0:nY, 0:nX].T.reshape(-1, 2)
object_points_3D = object_points_3D * square_size
# Store vectors of 3D points for all chessboard images (world coordinate frame)
object_points = []
# Store vectors of 2D points for all chessboard images (camera coordinate frame)
image_points = []
# Get the file path for images in the current directory
images = glob.glob('BoardImages/*.jpg')
# Check that we have refernce images
if len(images) <= 10:
print("Not enough samples that are jpgs! " + str(len(images)))
sys.exit()
# Get image size for reference during calibration later
imageSize = cv2.cvtColor(cv2.imread(images[0]), cv2.COLOR_BGR2GRAY).shape[::1]
def main():
# Go through each chessboard image, one by one
for image_file in images:
# Load the image
image = cv2.imread(image_file)
# Convert the image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Find the corners on the chessboard
success, corners = cv2.findChessboardCorners(gray, (nY, nX), None)
print("Status of image parsed " + str(success))
# If the corners are found by the algorithm, draw them
if success == True:
# Append object points
object_points.append(object_points_3D)
# Find more exact corner pixels
corners_2 = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
# Append image points
image_points.append(corners_2)
# Draw the corners
cv2.drawChessboardCorners(image, (nY, nX), corners_2, success)
# Display the image. Used for testing.
cv2.imshow("Image", image)
# Display the window for a short period. Used for testing.
cv2.waitKey(1000)
# Perform camera calibration to return the camera matrix, distortion coefficients, rotation and translation vectors etc
print(len(object_points))
print(len(image_points))
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(object_points,
image_points,
imageSize,
None,
None)
# Save parameters to a file
cv_file = cv2.FileStorage('calibration_chessboard.yaml', cv2.FILE_STORAGE_WRITE)
cv_file.write('K', mtx)
cv_file.write('D', dist)
cv_file.release()
# Load the parameters from the saved file
cv_file = cv2.FileStorage('calibration_chessboard.yaml', cv2.FILE_STORAGE_READ)
mtx = cv_file.getNode('K').mat()
dst = cv_file.getNode('D').mat()
cv_file.release()
# Display key parameter outputs of the camera calibration process
print("Camera matrix:")
print(mtx)
print("\n Distortion coefficient:")
print(dist)
# Close all windows
cv2.destroyAllWindows()
if __name__ == '__main__':
print(__doc__)
main()