Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/python/test/test_calibration.py
16337 views
1
#!/usr/bin/env python
2
3
'''
4
camera calibration for distorted images with chess board samples
5
reads distorted images, calculates the calibration and write undistorted images
6
'''
7
8
# Python 2/3 compatibility
9
from __future__ import print_function
10
11
import numpy as np
12
import cv2 as cv
13
14
from tests_common import NewOpenCVTests
15
16
class calibration_test(NewOpenCVTests):
17
18
def test_calibration(self):
19
img_names = []
20
for i in range(1, 15):
21
if i < 10:
22
img_names.append('samples/data/left0{}.jpg'.format(str(i)))
23
elif i != 10:
24
img_names.append('samples/data/left{}.jpg'.format(str(i)))
25
26
square_size = 1.0
27
pattern_size = (9, 6)
28
pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
29
pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
30
pattern_points *= square_size
31
32
obj_points = []
33
img_points = []
34
h, w = 0, 0
35
for fn in img_names:
36
img = self.get_sample(fn, 0)
37
if img is None:
38
continue
39
40
h, w = img.shape[:2]
41
found, corners = cv.findChessboardCorners(img, pattern_size)
42
if found:
43
term = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_COUNT, 30, 0.1)
44
cv.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
45
46
if not found:
47
continue
48
49
img_points.append(corners.reshape(-1, 2))
50
obj_points.append(pattern_points)
51
52
# calculate camera distortion
53
rms, camera_matrix, dist_coefs, _rvecs, _tvecs = cv.calibrateCamera(obj_points, img_points, (w, h), None, None, flags = 0)
54
55
eps = 0.01
56
normCamEps = 10.0
57
normDistEps = 0.05
58
59
cameraMatrixTest = [[ 532.80992189, 0., 342.4952186 ],
60
[ 0., 532.93346422, 233.8879292 ],
61
[ 0., 0., 1. ]]
62
63
distCoeffsTest = [ -2.81325576e-01, 2.91130406e-02,
64
1.21234330e-03, -1.40825372e-04, 1.54865844e-01]
65
66
self.assertLess(abs(rms - 0.196334638034), eps)
67
self.assertLess(cv.norm(camera_matrix - cameraMatrixTest, cv.NORM_L1), normCamEps)
68
self.assertLess(cv.norm(dist_coefs - distCoeffsTest, cv.NORM_L1), normDistEps)
69
70
71
72
if __name__ == '__main__':
73
NewOpenCVTests.bootstrap()
74
75