-
Notifications
You must be signed in to change notification settings - Fork 0
/
calibration.py
86 lines (61 loc) · 2.81 KB
/
calibration.py
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
'''
Sample Usage:-
python calibration.py --dir calibration_checkerboard/ --square_size 0.024
'''
import numpy as np
import cv2
import os
import argparse
def calibrate(dirpath, square_size, width, height, visualize=False):
""" Apply camera calibration operation for images in the given directory path. """
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(8,6,0)
objp = np.zeros((height*width, 3), np.float32)
objp[:, :2] = np.mgrid[0:width, 0:height].T.reshape(-1, 2)
objp = objp * square_size
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
images = os.listdir(dirpath)
print(images)
for fname in images:
img = cv2.imread(os.path.join(dirpath, fname))
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (width, height), None)
# If found, add object points, image points (after refining them)
if ret:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners2)
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (width, height), corners2, ret)
if visualize:
cv2.imshow('img',img)
cv2.waitKey(0)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
return [ret, mtx, dist, rvecs, tvecs]
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dir", required=True, help="Path to folder containing checkerboard images for calibration")
ap.add_argument("-w", "--width", type=int, help="Width of checkerboard (default=9)", default=9)
ap.add_argument("-t", "--height", type=int, help="Height of checkerboard (default=6)", default=6)
ap.add_argument("-s", "--square_size", type=float, default=1, help="Length of one edge (in metres)")
ap.add_argument("-v", "--visualize", type=str, default="False", help="To visualize each checkerboard image")
args = vars(ap.parse_args())
dirpath = args['dir']
# 2.4 cm == 0.024 m
# square_size = 0.024
square_size = args['square_size']
width = args['width']
height = args['height']
if args["visualize"].lower() == "true":
visualize = True
else:
visualize = False
ret, mtx, dist, rvecs, tvecs = calibrate(dirpath, square_size, visualize=visualize, width=width, height=height)
print(mtx)
print(dist)
np.save("calibration_matrix", mtx)
np.save("distortion_coefficients", dist)