├── .gitignore
├── 01-01_calibrateCamera.py
├── 01-02_undistort.py
├── 02-01_fisheyeCalibrateCamera.py
├── 02-02_fisheyeUndistort.py
├── 03-01_omnidirCalibrateCamera.py
├── 03-02_omnidirUndistort.py
├── LICENSE
├── README.md
└── chesspattern_7x10.pdf
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/01-01_calibrateCamera.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import argparse
4 |
5 | import cv2 as cv
6 | import numpy as np
7 |
8 |
9 | def get_args():
10 | parser = argparse.ArgumentParser()
11 |
12 | parser.add_argument("--device", type=int, default=0)
13 | parser.add_argument("--file", type=str, default=None)
14 | parser.add_argument("--width", type=int, default=640)
15 | parser.add_argument("--height", type=int, default=360)
16 |
17 | parser.add_argument("--square_len", type=float, default=23.0)
18 | parser.add_argument("--grid_size", type=str, default="10,7")
19 |
20 | parser.add_argument("--k_filename", type=str, default="K.csv")
21 | parser.add_argument("--d_filename", type=str, default="d.csv")
22 |
23 | parser.add_argument("--interval_time", type=int, default=500)
24 | parser.add_argument('--use_autoappend', action='store_true')
25 |
26 | args = parser.parse_args()
27 |
28 | return args
29 |
30 |
31 | def main():
32 | # コマンドライン引数
33 | args = get_args()
34 |
35 | cap_device = args.device
36 | filepath = args.file
37 | cap_width = args.width
38 | cap_height = args.height
39 |
40 | # カメラ準備
41 | cap = None
42 | if filepath is None:
43 | cap = cv.VideoCapture(cap_device, cv.CAP_DSHOW)
44 | cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)
45 | cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)
46 | else:
47 | cap = cv.VideoCapture(filepath)
48 |
49 | square_side_length = args.square_len # チェスボード内の正方形の1辺のサイズ(mm)
50 | grid_intersection_size = eval(args.grid_size) # チェスボード内の格子数
51 |
52 | k_filename = args.k_filename
53 | d_filename = args.d_filename
54 |
55 | interval_time = args.interval_time
56 | use_autoappend = args.use_autoappend
57 | if use_autoappend is False:
58 | interval_time = 10
59 |
60 | # チェスボードコーナー検出情報 保持用変数
61 | pattern_points = np.zeros((np.prod(grid_intersection_size), 3), np.float32)
62 | pattern_points[:, :2] = np.indices(grid_intersection_size).T.reshape(-1, 2)
63 | pattern_points *= square_side_length
64 | object_points = []
65 | image_points = []
66 |
67 | camera_mat, dist_coef = [], []
68 |
69 | capture_count = 0
70 | while (True):
71 | ret, frame = cap.read()
72 |
73 | # チェスボードのコーナーを検出
74 | found, corner = cv.findChessboardCorners(frame, grid_intersection_size)
75 |
76 | if found:
77 | print('findChessboardCorners() : True')
78 | cv.drawChessboardCorners(frame, grid_intersection_size, corner,
79 | found)
80 | else:
81 | print('findChessboardCorners() : False')
82 |
83 | cv.putText(frame,
84 | "Enter:Capture Chessboard(" + str(capture_count) + ")",
85 | (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
86 | cv.putText(frame, "ESC :Completes Calibration Photographing", (10, 55),
87 | cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
88 | cv.imshow('original', frame)
89 |
90 | key = cv.waitKey(interval_time) & 0xFF
91 | if ((use_autoappend is True) and found) or (
92 | (use_autoappend is False and key == 13) and found): # Enter
93 | # チェスボードコーナー検出情報を追加
94 | image_points.append(corner)
95 | object_points.append(pattern_points)
96 | capture_count += 1
97 | if key == 27: # ESC
98 | cap.release()
99 | cv.destroyAllWindows()
100 | break
101 |
102 | if len(image_points) > 0:
103 | # カメラ内部パラメータを計算
104 | print('calibrateCamera()')
105 | rms, K, d, r, t = cv.calibrateCamera(object_points, image_points,
106 | (frame.shape[1], frame.shape[0]),
107 | None, None)
108 | print("RMS = " + str(rms))
109 | print("K = \n", K)
110 | print("d = " + str(d.ravel()))
111 | np.savetxt(k_filename, K, delimiter=',', fmt="%0.14f") # 半径方向の歪み係数の保存
112 | np.savetxt(d_filename, d, delimiter=',', fmt="%0.14f") # 円周方向の歪み係数の保存
113 |
114 | camera_mat = K
115 | dist_coef = d
116 |
117 | # 再投影誤差による評価
118 | mean_error = 0
119 | for i in range(len(object_points)):
120 | image_points2, _ = cv.projectPoints(object_points[i], r[i], t[i],
121 | camera_mat, dist_coef)
122 | error = cv.norm(image_points[i], image_points2,
123 | cv.NORM_L2) / len(image_points2)
124 | mean_error += error
125 | print("total error: " +
126 | str(mean_error / len(object_points))) # 0に近い値が望ましい
127 | else:
128 | print("findChessboardCorners() not be successful once")
129 |
130 | cap.release()
131 | cv.destroyAllWindows()
132 |
133 |
134 | if __name__ == '__main__':
135 | main()
136 |
--------------------------------------------------------------------------------
/01-02_undistort.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import argparse
4 |
5 | import cv2 as cv
6 | import numpy as np
7 |
8 |
9 | def get_args():
10 | parser = argparse.ArgumentParser()
11 |
12 | parser.add_argument("--device", type=int, default=0)
13 | parser.add_argument("--file", type=str, default=None)
14 | parser.add_argument("--width", type=int, default=640)
15 | parser.add_argument("--height", type=int, default=360)
16 |
17 | parser.add_argument("--k_new_param", type=float, default=1.0)
18 |
19 | parser.add_argument("--k_filename", type=str, default="K.csv")
20 | parser.add_argument("--d_filename", type=str, default="d.csv")
21 |
22 | args = parser.parse_args()
23 |
24 | return args
25 |
26 |
27 | def main():
28 | # コマンドライン引数
29 | args = get_args()
30 |
31 | cap_device = args.device
32 | filepath = args.file
33 | cap_width = args.width
34 | cap_height = args.height
35 |
36 | k_new_param = args.k_new_param
37 |
38 | k_filename = args.k_filename
39 | d_filename = args.d_filename
40 |
41 | # カメラ準備
42 | cap = None
43 | if filepath is None:
44 | cap = cv.VideoCapture(cap_device)
45 | cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)
46 | cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)
47 | else:
48 | cap = cv.VideoCapture(filepath)
49 |
50 | # キャリブレーションデータの読み込み
51 | camera_mat = np.loadtxt(k_filename, delimiter=',')
52 | dist_coef = np.loadtxt(d_filename, delimiter=',')
53 |
54 | new_camera_mat = camera_mat.copy()
55 | new_camera_mat[(0, 1), (0, 1)] = k_new_param * new_camera_mat[(0, 1),
56 | (0, 1)]
57 |
58 | while (True):
59 | ret, frame = cap.read()
60 | undistort_image = cv.undistort(
61 | frame,
62 | camera_mat,
63 | dist_coef,
64 | new_camera_mat,
65 | )
66 |
67 | cv.imshow('original', frame)
68 | cv.imshow('undistort', undistort_image)
69 |
70 | key = cv.waitKey(1) & 0xFF
71 | if key == 27: # ESC
72 | cap.release()
73 | cv.destroyAllWindows()
74 | break
75 |
76 | cap.release()
77 | cv.destroyAllWindows()
78 |
79 |
80 | if __name__ == '__main__':
81 | main()
82 |
--------------------------------------------------------------------------------
/02-01_fisheyeCalibrateCamera.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import argparse
4 |
5 | import cv2 as cv
6 | import numpy as np
7 |
8 |
9 | def get_args():
10 | parser = argparse.ArgumentParser()
11 |
12 | parser.add_argument("--device", type=int, default=0)
13 | parser.add_argument("--file", type=str, default=None)
14 | parser.add_argument("--width", type=int, default=640)
15 | parser.add_argument("--height", type=int, default=360)
16 |
17 | parser.add_argument("--square_len", type=float, default=23.0)
18 | parser.add_argument("--grid_size", type=str, default="10,7")
19 |
20 | parser.add_argument("--k_filename", type=str, default="K_fisheye.csv")
21 | parser.add_argument("--d_filename", type=str, default="d_fisheye.csv")
22 |
23 | parser.add_argument("--interval_time", type=int, default=500)
24 | parser.add_argument('--use_autoappend', action='store_true')
25 |
26 | args = parser.parse_args()
27 |
28 | return args
29 |
30 |
31 | def main():
32 | # コマンドライン引数
33 | args = get_args()
34 |
35 | cap_device = args.device
36 | filepath = args.file
37 | cap_width = args.width
38 | cap_height = args.height
39 |
40 | # カメラ準備
41 | cap = None
42 | if filepath is None:
43 | cap = cv.VideoCapture(cap_device)
44 | cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)
45 | cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)
46 | else:
47 | cap = cv.VideoCapture(filepath)
48 |
49 | square_side_length = args.square_len # チェスボード内の正方形の1辺のサイズ(mm)
50 | grid_intersection_size = eval(args.grid_size) # チェスボード内の格子数
51 |
52 | k_filename = args.k_filename
53 | d_filename = args.d_filename
54 |
55 | interval_time = args.interval_time
56 | use_autoappend = args.use_autoappend
57 | if use_autoappend is False:
58 | interval_time = 10
59 |
60 | # チェスボードコーナー検出情報 保持用変数
61 | pattern_points = np.zeros((1, np.prod(grid_intersection_size), 3),
62 | np.float32)
63 | pattern_points[0, :, :2] = np.indices(grid_intersection_size).T.reshape(
64 | -1, 2)
65 | pattern_points *= square_side_length
66 | object_points = []
67 | image_points = []
68 |
69 | subpix_criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30,
70 | 0.1)
71 |
72 | capture_count = 0
73 | while (True):
74 | ret, frame = cap.read()
75 |
76 | # チェスボードのコーナーを検出
77 | found, corner = cv.findChessboardCorners(frame, grid_intersection_size)
78 |
79 | if found:
80 | print('findChessboardCorners() : True')
81 | cv.drawChessboardCorners(frame, grid_intersection_size, corner,
82 | found)
83 | else:
84 | print('findChessboardCorners() : False')
85 |
86 | cv.putText(frame,
87 | "Enter:Capture Chessboard(" + str(capture_count) + ")",
88 | (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
89 | cv.putText(frame, "ESC :Completes Calibration Photographing", (10, 55),
90 | cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
91 | cv.imshow('original', frame)
92 |
93 | key = cv.waitKey(interval_time) & 0xFF
94 | if ((use_autoappend is True) and found) or (
95 | (use_autoappend is False and key == 13) and found): # Enter
96 | # チェスボードコーナー検出情報を追加
97 | gray_image = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
98 | cv.cornerSubPix(gray_image, corner, (3, 3), (-1, -1),
99 | subpix_criteria)
100 | image_points.append(corner)
101 | object_points.append(pattern_points)
102 | capture_count += 1
103 | if key == 27: # ESC
104 | cap.release()
105 | cv.destroyAllWindows()
106 | break
107 |
108 | if len(image_points) > 0:
109 | # カメラ内部パラメータを計算
110 | print('fisheye.calibrate()')
111 |
112 | # calibration_flags = cv.fisheye.CALIB_RECOMPUTE_EXTRINSIC + cv.fisheye.CALIB_CHECK_COND + cv.fisheye.CALIB_FIX_SKEW
113 | calibration_flags = cv.fisheye.CALIB_RECOMPUTE_EXTRINSIC + cv.fisheye.CALIB_FIX_SKEW
114 |
115 | K = np.zeros((3, 3))
116 | d = np.zeros((4, 1))
117 | rvecs = [
118 | np.zeros((1, 1, 3), dtype=np.float64)
119 | for i in range(len(image_points))
120 | ]
121 | tvecs = [
122 | np.zeros((1, 1, 3), dtype=np.float64)
123 | for i in range(len(image_points))
124 | ]
125 | rms, K, d, r, t = \
126 | cv.fisheye.calibrate(
127 | object_points,
128 | image_points,
129 | gray_image.shape[::-1],
130 | K,
131 | d,
132 | rvecs,
133 | tvecs,
134 | calibration_flags,
135 | (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30, 1e-6)
136 | )
137 | print("RMS = " + str(rms))
138 | print("Shape=" + str((frame.shape[:2])[::-1]))
139 | print("K = \n", K)
140 | print("d = " + str(d.ravel()))
141 | np.savetxt(k_filename, K, delimiter=',', fmt="%0.14f") # 半径方向の歪み係数の保存
142 | np.savetxt(d_filename, d, delimiter=',', fmt="%0.14f") # 円周方向の歪み係数の保存
143 | else:
144 | print("findChessboardCorners() not be successful once")
145 |
146 | cap.release()
147 | cv.destroyAllWindows()
148 |
149 |
150 | if __name__ == '__main__':
151 | main()
152 |
--------------------------------------------------------------------------------
/02-02_fisheyeUndistort.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import argparse
4 |
5 | import cv2 as cv
6 | import numpy as np
7 |
8 |
9 | def get_args():
10 | parser = argparse.ArgumentParser()
11 |
12 | parser.add_argument("--device", type=int, default=0)
13 | parser.add_argument("--file", type=str, default=None)
14 | parser.add_argument("--width", type=int, default=640)
15 | parser.add_argument("--height", type=int, default=360)
16 |
17 | parser.add_argument("--k_new_param", type=float, default=0.9)
18 |
19 | parser.add_argument("--k_filename", type=str, default="K_fisheye.csv")
20 | parser.add_argument("--d_filename", type=str, default="d_fisheye.csv")
21 |
22 | args = parser.parse_args()
23 |
24 | return args
25 |
26 |
27 | def main():
28 | # コマンドライン引数
29 | args = get_args()
30 |
31 | cap_device = args.device
32 | filepath = args.file
33 | cap_width = args.width
34 | cap_height = args.height
35 |
36 | k_new_param = args.k_new_param
37 |
38 | k_filename = args.k_filename
39 | d_filename = args.d_filename
40 |
41 | # カメラ準備
42 | cap = None
43 | if filepath is None:
44 | cap = cv.VideoCapture(cap_device)
45 | cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)
46 | cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)
47 | else:
48 | cap = cv.VideoCapture(filepath)
49 |
50 | # キャリブレーションデータの読み込み
51 | camera_mat = np.loadtxt(k_filename, delimiter=',')
52 | dist_coef = np.loadtxt(d_filename, delimiter=',')
53 |
54 | new_camera_mat = camera_mat.copy()
55 | new_camera_mat[(0, 1), (0, 1)] = k_new_param * new_camera_mat[(0, 1),
56 | (0, 1)]
57 |
58 | while (True):
59 | ret, frame = cap.read()
60 | undistort_image = cv.fisheye.undistortImage(
61 | frame,
62 | camera_mat,
63 | D=dist_coef,
64 | Knew=new_camera_mat,
65 | )
66 |
67 | cv.imshow('original', frame)
68 | cv.imshow('undistort', undistort_image)
69 |
70 | key = cv.waitKey(1) & 0xFF
71 | if key == 27: # ESC
72 | cap.release()
73 | cv.destroyAllWindows()
74 | break
75 |
76 | cap.release()
77 | cv.destroyAllWindows()
78 |
79 |
80 | if __name__ == '__main__':
81 | main()
82 |
--------------------------------------------------------------------------------
/03-01_omnidirCalibrateCamera.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import argparse
4 |
5 | import cv2 as cv
6 | import numpy as np
7 |
8 |
9 | def get_args():
10 | parser = argparse.ArgumentParser()
11 |
12 | parser.add_argument("--device", type=int, default=0)
13 | parser.add_argument("--file", type=str, default=None)
14 | parser.add_argument("--width", type=int, default=640)
15 | parser.add_argument("--height", type=int, default=360)
16 |
17 | parser.add_argument("--square_len", type=float, default=23.0)
18 | parser.add_argument("--grid_size", type=str, default="10,7")
19 |
20 | parser.add_argument("--k_filename", type=str, default="K_omni.csv")
21 | parser.add_argument("--d_filename", type=str, default="d_omni.csv")
22 | parser.add_argument("--xi_filename", type=str, default="xi_omni.csv")
23 |
24 | parser.add_argument("--interval_time", type=int, default=500)
25 | parser.add_argument('--use_autoappend', action='store_true')
26 |
27 | args = parser.parse_args()
28 |
29 | return args
30 |
31 |
32 | def main():
33 | # コマンドライン引数
34 | args = get_args()
35 |
36 | cap_device = args.device
37 | filepath = args.file
38 | cap_width = args.width
39 | cap_height = args.height
40 |
41 | # カメラ準備
42 | cap = None
43 | if filepath is None:
44 | cap = cv.VideoCapture(cap_device)
45 | cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)
46 | cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)
47 | else:
48 | cap = cv.VideoCapture(filepath)
49 |
50 | square_side_length = args.square_len # チェスボード内の正方形の1辺のサイズ(mm)
51 | grid_intersection_size = eval(args.grid_size) # チェスボード内の格子数
52 |
53 | k_filename = args.k_filename
54 | d_filename = args.d_filename
55 | xi_filename = args.xi_filename
56 |
57 | interval_time = args.interval_time
58 | use_autoappend = args.use_autoappend
59 | if use_autoappend is False:
60 | interval_time = 10
61 |
62 | # チェスボードコーナー検出情報 保持用変数
63 | pattern_points = np.zeros((1, np.prod(grid_intersection_size), 3),
64 | np.float32)
65 | pattern_points[0, :, :2] = np.indices(grid_intersection_size).T.reshape(
66 | -1, 2)
67 | pattern_points *= square_side_length
68 | object_points = []
69 | image_points = []
70 |
71 | subpix_criteria = (cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 30,
72 | 0.1)
73 |
74 | capture_count = 0
75 | while (True):
76 | ret, frame = cap.read()
77 |
78 | # チェスボードのコーナーを検出
79 | found, corner = cv.findChessboardCorners(frame, grid_intersection_size)
80 |
81 | if found:
82 | print('findChessboardCorners() : True')
83 | cv.drawChessboardCorners(frame, grid_intersection_size, corner,
84 | found)
85 | else:
86 | print('findChessboardCorners() : False')
87 |
88 | cv.putText(frame,
89 | "Enter:Capture Chessboard(" + str(capture_count) + ")",
90 | (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
91 | cv.putText(frame, "ESC :Completes Calibration Photographing", (10, 55),
92 | cv.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
93 | cv.imshow('original', frame)
94 |
95 | key = cv.waitKey(interval_time) & 0xFF
96 | if ((use_autoappend is True) and found) or (
97 | (use_autoappend is False and key == 13) and found): # Enter
98 | # チェスボードコーナー検出情報を追加
99 | gray_image = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
100 | cv.cornerSubPix(gray_image, corner, (3, 3), (-1, -1),
101 | subpix_criteria)
102 | image_points.append(corner)
103 | object_points.append(pattern_points)
104 | capture_count += 1
105 | if key == 27: # ESC
106 | cap.release()
107 | cv.destroyAllWindows()
108 | break
109 |
110 | if len(image_points) > 0:
111 | # カメラ内部パラメータを計算
112 | print('omnidir.calibrate()')
113 |
114 | calibration_flags = cv.omnidir.CALIB_USE_GUESS + cv.omnidir.CALIB_FIX_SKEW + cv.omnidir.CALIB_FIX_CENTER
115 |
116 | rms, K, xi, d, rvecs, tvecs, idx = \
117 | cv.omnidir.calibrate(
118 | object_points,
119 | image_points,
120 | gray_image.shape[::-1],
121 | K=None,
122 | xi=None,
123 | D=None,
124 | flags=calibration_flags,
125 | criteria=(cv.TERM_CRITERIA_EPS + cv.TERM_CRITERIA_MAX_ITER, 200, 1e-8)
126 | )
127 | print("RMS = " + str(rms))
128 | print("Shape=" + str((frame.shape[:2])[::-1]))
129 | print("K = \n", K)
130 | print("d = " + str(d.ravel()))
131 | np.savetxt(k_filename, K, delimiter=',', fmt="%0.14f") # 半径方向の歪み係数の保存
132 | np.savetxt(d_filename, d, delimiter=',', fmt="%0.14f") # 円周方向の歪み係数の保存
133 | np.savetxt(xi_filename, xi, delimiter=',', fmt="%0.14f") # xiの保存
134 | else:
135 | print("findChessboardCorners() not be successful once")
136 |
137 | cap.release()
138 | cv.destroyAllWindows()
139 |
140 |
141 | if __name__ == '__main__':
142 | main()
143 |
--------------------------------------------------------------------------------
/03-02_omnidirUndistort.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 | import argparse
4 |
5 | import cv2 as cv
6 | import numpy as np
7 |
8 |
9 | def get_args():
10 | parser = argparse.ArgumentParser()
11 |
12 | parser.add_argument("--device", type=int, default=0)
13 | parser.add_argument("--file", type=str, default=None)
14 | parser.add_argument("--width", type=int, default=640)
15 | parser.add_argument("--height", type=int, default=360)
16 |
17 | parser.add_argument("--k_new_param", type=float, default=0.5)
18 |
19 | parser.add_argument("--k_filename", type=str, default="K_omni.csv")
20 | parser.add_argument("--d_filename", type=str, default="d_omni.csv")
21 | parser.add_argument("--xi_filename", type=str, default="xi_omni.csv")
22 |
23 | parser.add_argument(
24 | "--flag",
25 | type=int,
26 | help=
27 | '1:RECTIFY_PERSPECTIVE 2:RECTIFY_CYLINDRICAL 3:RECTIFY_LONGLATI 4:RECTIFY_STEREOGRAPHIC',
28 | default=1)
29 |
30 | args = parser.parse_args()
31 |
32 | return args
33 |
34 |
35 | def main():
36 | # コマンドライン引数
37 | args = get_args()
38 |
39 | cap_device = args.device
40 | filepath = args.file
41 | cap_width = args.width
42 | cap_height = args.height
43 |
44 | k_new_param = args.k_new_param
45 |
46 | k_filename = args.k_filename
47 | d_filename = args.d_filename
48 | xi_filename = args.xi_filename
49 |
50 | flag = args.flag
51 |
52 | # カメラ準備
53 | cap = None
54 | if filepath is None:
55 | cap = cv.VideoCapture(cap_device)
56 | cap.set(cv.CAP_PROP_FRAME_WIDTH, cap_width)
57 | cap.set(cv.CAP_PROP_FRAME_HEIGHT, cap_height)
58 | else:
59 | cap = cv.VideoCapture(filepath)
60 |
61 | # キャリブレーションデータの読み込み
62 | camera_mat = np.loadtxt(k_filename, delimiter=',')
63 | dist_coef = np.loadtxt(d_filename, delimiter=',')
64 | xi = np.loadtxt(xi_filename, delimiter=',')
65 |
66 | new_camera_mat = camera_mat.copy()
67 | new_camera_mat[(0, 1), (0, 1)] = k_new_param * new_camera_mat[(0, 1),
68 | (0, 1)]
69 |
70 | # 参考:https://docs.opencv.org/master/dd/d12/tutorial_omnidir_calib_main.html
71 | if flag == 1:
72 | flags = cv.omnidir.RECTIFY_PERSPECTIVE
73 | elif flag == 2:
74 | flags = cv.omnidir.RECTIFY_CYLINDRICAL
75 | elif flag == 3:
76 | flags = cv.omnidir.RECTIFY_LONGLATI
77 | elif flag == 4:
78 | flags = cv.omnidir.RECTIFY_STEREOGRAPHIC
79 | else:
80 | flags = cv.omnidir.RECTIFY_PERSPECTIVE
81 |
82 | while (True):
83 | ret, frame = cap.read()
84 | unconstraint_image = cv.omnidir.undistortImage(
85 | frame,
86 | camera_mat,
87 | D=dist_coef,
88 | xi=xi,
89 | Knew=new_camera_mat,
90 | flags=flags,
91 | )
92 |
93 | cv.imshow('original', frame)
94 | cv.imshow('unConstraint', unconstraint_image)
95 |
96 | key = cv.waitKey(1) & 0xFF
97 | if key == 27: # ESC
98 | cap.release()
99 | cv.destroyAllWindows()
100 | break
101 |
102 | cap.release()
103 | cv.destroyAllWindows()
104 |
105 |
106 | if __name__ == '__main__':
107 | main()
108 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # OpenCV-CameraCalibration-Example
2 | https://user-images.githubusercontent.com/37477845/122794701-8086b900-d2f7-11eb-8651-ce4e300e8a83.mp4
3 |
4 | OpenCVを用いたカメラキャリブレーションのサンプルです
5 | 2021/06/21時点でPython実装のある以下3種類について用意しています。
6 | * 通常カメラ向け
7 | * 魚眼レンズ向け(fisheyeモジュール)
8 | * 全方位カメラ向け(omnidirモジュール)
9 | 全方位カメラは以下のような構造のカメラを想定しています。
10 | 
11 | 画像はWikipediaの[Omnidirectional (360-degree) camera](https://en.wikipedia.org/wiki/Omnidirectional_(360-degree)_camera)から引用
12 |
13 |
14 |
15 | # Requirement
16 | * opencv-python 4.5.2.54 or later
17 | * opencv-contrib-python 4.5.2.54 or later ※omnidirモジュールを使用する場合のみ
18 |
19 | # Calibration Pattern
20 | サンプルでは以下の7×10のチェスボード型のキャリブレーションパターンを使用します。
21 | * http://opencv.jp/sample/pics/chesspattern_7x10.pdf
22 |
23 | 他の行列数のキャリブレーションパターンを使用したい場合は、以下を参照して作成or入手してください。
24 | * https://docs.opencv.org/master/da/d0d/tutorial_camera_calibration_pattern.html
25 | * https://github.com/opencv/opencv/blob/master/doc/pattern.png
26 |
27 | また、以下のようなサークル型のパターンやセクターベース型のパターンのサンプルは用意していません。
28 | * https://github.com/opencv/opencv/blob/master/doc/acircles_pattern.png
29 | * https://docs.opencv.org/4.5.2/checkerboard_radon.png
30 |
31 | # Usage
32 |
33 | calibrateCameraのサンプルでキャリブレーションパラメータをcsvに保存し、
34 | undistortのサンプルで歪み補正を実施してください。
35 |
36 | #### 01.calibrateCamera
37 | ```bash
38 | python 01-01_calibrateCamera.py
39 | python 02-01_fisheyeCalibrateCamera.py
40 | python 03-01_omnidirCalibrateCamera.py
41 | ```
42 | キャリブレーションパターン検出時にEnterを押すことで撮影します。
43 | ESCを押すことでプログラムを終了し、キャリブレーションパラメータを保存します。
44 |
45 | 実行時には、以下のオプションが指定可能です。
46 |
47 | オプション指定
48 |
49 | * --device
50 | カメラデバイス番号の指定
51 | デフォルト:
52 | * 01-01_calibrateCamera:0
53 | * 02-01_fisheyeCalibrateCamera.py:0
54 | * 03-01_omnidirCalibrateCamera.py:0
55 | * --file
56 | 動画ファイル名の指定 ※指定時はカメラデバイスより優先し動画を読み込む
57 | デフォルト:
58 | * 01-01_calibrateCamera:None
59 | * 02-01_fisheyeCalibrateCamera.py:None
60 | * 03-01_omnidirCalibrateCamera.py:None
61 | * --width
62 | カメラキャプチャ時の横幅
63 | デフォルト:
64 | * 01-01_calibrateCamera:640
65 | * 02-01_fisheyeCalibrateCamera.py:640
66 | * 03-01_omnidirCalibrateCamera.py:640
67 | * --height
68 | カメラキャプチャ時の縦幅
69 | デフォルト:
70 | * 01-01_calibrateCamera:360
71 | * 02-01_fisheyeCalibrateCamera.py:360
72 | * 03-01_omnidirCalibrateCamera.py:360
73 | * --square_len
74 | キャリブレーションパターン(チェスボード)の1辺の長さ(mm)
75 | デフォルト:
76 | * 01-01_calibrateCamera:23.0
77 | * 02-01_fisheyeCalibrateCamera.py:23.0
78 | * 03-01_omnidirCalibrateCamera.py:23.0
79 | * --grid_size
80 | キャリブレーションパターン(チェスボード)の行列数(カンマ区切り指定)
81 | デフォルト:
82 | * 01-01_calibrateCamera:10,7
83 | * 02-01_fisheyeCalibrateCamera.py:10,7
84 | * 03-01_omnidirCalibrateCamera.py:10,7
85 | * --k_filename
86 | 半径方向の歪み係数の保存ファイル名(csv)
87 | デフォルト:
88 | * 01-01_calibrateCamera:K.csv
89 | * 02-01_fisheyeCalibrateCamera.py:K_fisheye.csv
90 | * 03-01_omnidirCalibrateCamera.py:K_omni.csv
91 | * --d_filename
92 | 円周方向の歪み係数の保存ファイル名(csv)
93 | デフォルト:
94 | * 01-01_calibrateCamera:d.csv
95 | * 02-01_fisheyeCalibrateCamera.py:d_fisheye.csv
96 | * 03-01_omnidirCalibrateCamera.py:d_omni.csv
97 | * --xi_filename
98 | Mei'sモデルパラメータxiの保存ファイル名(csv)
99 | デフォルト:
100 | * 03-01_omnidirCalibrateCamera.py:xi_omni.csv
101 | * --use_autoappend
102 | キャリブレーションパターン検出時に自動で撮影するか否か(指定しない場合はEnterで明示的に撮影)
103 | デフォルト:
104 | * 01-01_calibrateCamera:指定なし
105 | * 02-01_fisheyeCalibrateCamera.py:指定なし
106 | * 03-01_omnidirCalibrateCamera.py:指定なし
107 | * --interval_time
108 | use_autoappend指定時の撮影間隔(ms)
109 | デフォルト:
110 | * 01-01_calibrateCamera:500
111 | * 02-01_fisheyeCalibrateCamera.py:500
112 | * 03-01_omnidirCalibrateCamera.py:500
113 |
114 |
115 | #### 02.undistort
116 | ```bash
117 | python 01-02_undistort.py
118 | python 02-02_fisheyeUndistort.py
119 | python 03-02_omnidirUndistort.py
120 | ```
121 |
122 | 実行時には、以下のオプションが指定可能です。
123 |
124 | オプション指定
125 |
126 | * --device
127 | カメラデバイス番号の指定
128 | デフォルト:
129 | * 01-01_calibrateCamera:0
130 | * 02-01_fisheyeCalibrateCamera.py:0
131 | * 03-01_omnidirCalibrateCamera.py:0
132 | * --file
133 | 動画ファイル名の指定 ※指定時はカメラデバイスより優先し動画を読み込む
134 | デフォルト:
135 | * 01-01_calibrateCamera:None
136 | * 02-01_fisheyeCalibrateCamera.py:None
137 | * 03-01_omnidirCalibrateCamera.py:None
138 | * --width
139 | カメラキャプチャ時の横幅
140 | デフォルト:
141 | * 01-01_calibrateCamera:640
142 | * 02-01_fisheyeCalibrateCamera.py:640
143 | * 03-01_omnidirCalibrateCamera.py:640
144 | * --height
145 | カメラキャプチャ時の縦幅
146 | デフォルト:
147 | * 01-01_calibrateCamera:360
148 | * 02-01_fisheyeCalibrateCamera.py:360
149 | * 03-01_omnidirCalibrateCamera.py:360
150 | * --k_filename
151 | 半径方向の歪み係数の読み込みファイル名(csv)
152 | デフォルト:
153 | * 01-01_calibrateCamera:K.csv
154 | * 02-01_fisheyeCalibrateCamera.py:K_fisheye.csv
155 | * 03-01_omnidirCalibrateCamera.py:K_omni.csv
156 | * --d_filename
157 | 円周方向の歪み係数の読み込みファイル名(csv)
158 | デフォルト:
159 | * 01-01_calibrateCamera:d.csv
160 | * 02-01_fisheyeCalibrateCamera.py:d_fisheye.csv
161 | * 03-01_omnidirCalibrateCamera.py:d_omni.csv
162 | * --xi_filename
163 | Mei'sモデルパラメータxiの読み込みファイル名(csv)
164 | デフォルト:
165 | * 03-01_omnidirCalibrateCamera.py:xi_omni.csv
166 | * --k_new_param
167 | Knewパラメータ指定時のスケール
168 | デフォルト:
169 | * 01-01_calibrateCamera:1.0
170 | * 02-01_fisheyeCalibrateCamera.py:0.9
171 | * 03-01_omnidirCalibrateCamera.py:0.5
172 |
173 |
174 | # Reference
175 | * [OpenCV Camera Calibration Tutorial](https://docs.opencv.org/master/dc/dbb/tutorial_py_calibration.html)
176 | * [OpenCV Camera Calibration and 3D Reconstruction](https://docs.opencv.org/master/d9/d0c/group__calib3d.html)
177 | * [OpenCV Fisheye camera model](https://docs.opencv.org/master/db/d58/group__calib3d__fisheye.html)
178 | * [OpenCV Omnidirectional Camera Calibration](https://docs.opencv.org/master/dd/d12/tutorial_omnidir_calib_main.html)
179 |
180 | # Author
181 | 高橋かずひと(https://twitter.com/KzhtTkhs)
182 |
183 | # License
184 | OpenCV-CameraCalibration-Example is under [Apache-2.0 License](LICENSE).
185 |
--------------------------------------------------------------------------------
/chesspattern_7x10.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Kazuhito00/OpenCV-CameraCalibration-Example/d4805c706ebcd88b24ee1dfe29f7fd9a7c1a9690/chesspattern_7x10.pdf
--------------------------------------------------------------------------------