Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

camera_calibration.py 5.7 KB

You have to be logged in to leave a comment. Sign In
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
  1. import os
  2. import cv2
  3. import click
  4. import numpy as np
  5. from tqdm import tqdm
  6. from typing import List
  7. from pathlib import Path
  8. # start point for images extraction
  9. START_POINT = 60
  10. # termination criteria
  11. CRITERIA = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
  12. @click.group()
  13. def main():
  14. """Entrypoint for scripts"""
  15. pass
  16. def save_coefficients(width: int, height: int, mtx: List[List], dist: List, path: str):
  17. """
  18. Save the camera matrix and the distortion coefficients to given path/file.
  19. :param width: image width
  20. :param height: image height
  21. :param mtx: camera matrix
  22. :param dist: distortion coefficients
  23. :param path:path to save camera.txt file
  24. :return: None
  25. """
  26. list_of_lines = [
  27. "# Camera list with one line of data per camera:",
  28. "# CAMERA_ID, MODEL, WIDTH, HEIGHT, fl_x, fl_y, cx, cy, k1, k2, p1, p2",
  29. ]
  30. os.makedirs(path, exist_ok=True)
  31. fl_x, fl_y, cx, cy = mtx[0][0], mtx[1][1], mtx[0][2], mtx[1][2]
  32. k1, k2, p1, p2, k3 = dist
  33. # we are doing crop procedure
  34. # so we have to adjust principal point parameters respectively
  35. cx_new = cx - 710
  36. cy_new = cy - 170
  37. # then we are doing resize procedures
  38. # so we have to adjust such parameters as fl_x, fl_y, cx, cy
  39. fl_x_new = fl_x * (800 / 500)
  40. fl_y_new = fl_y * (800 / 500)
  41. cx_new = cx_new * (800 / 500)
  42. cy_new = cy_new * (800 / 500)
  43. main_line = " ".join([
  44. "1", "OPENCV", str(800), str(800),
  45. str(fl_x_new), str(fl_y_new), str(cx_new), str(cy_new),
  46. str(k1), str(k2), str(p1), str(p2)
  47. ])
  48. list_of_lines.append(main_line)
  49. with open(str(Path(path) / "cameras.txt"), "w") as text_file:
  50. for line in list_of_lines:
  51. text_file.write(line + "\n")
  52. @main.command()
  53. @click.option("--video_dir", type=str, required=True, help="video directory path")
  54. @click.option(
  55. "--amount_of_frames",
  56. type=int,
  57. required=True,
  58. help="amount of frames to extract"
  59. )
  60. @click.option(
  61. "--path_to_images_folder",
  62. type=str,
  63. required=True,
  64. help="path to save frames"
  65. )
  66. def extract_calibration_images(
  67. video_dir: str,
  68. amount_of_frames: int,
  69. path_to_images_folder: str
  70. ):
  71. """
  72. Extract frames from video
  73. :param path_to_video: path to video file
  74. :param amount_of_frames: amount of frames to extract
  75. :param path_to_images_folder: path to save frames
  76. :return: None
  77. """
  78. os.makedirs(path_to_images_folder, exist_ok=True)
  79. # Read the video from specified path
  80. cam = cv2.VideoCapture(video_dir)
  81. frame_count = int(cam.get(cv2.CAP_PROP_FRAME_COUNT))
  82. reducer = (frame_count - START_POINT) // amount_of_frames
  83. # frame
  84. frame_number = 0
  85. frame_to_write_number = 0
  86. with tqdm(total=frame_count - START_POINT) as pbar:
  87. while True:
  88. # reading from frame
  89. ret, frame = cam.read()
  90. if not ret:
  91. break
  92. if not START_POINT <= frame_number:
  93. frame_number += 1
  94. continue
  95. if (frame_number - START_POINT) % reducer == 0:
  96. name = Path(path_to_images_folder) / f"{frame_to_write_number:03d}.jpg"
  97. cv2.imwrite(str(name), frame)
  98. frame_to_write_number += 1
  99. frame_number += 1
  100. pbar.update()
  101. @main.command()
  102. @click.option("--image_dir", type=str, required=True, help="image directory path")
  103. @click.option("--image_format", type=str, required=True, help="image format, png/jpg")
  104. @click.option("--square_size", type=float, required=True, help="chessboard square size")
  105. @click.option(
  106. "--width",
  107. type=int,
  108. required=True,
  109. default=13,
  110. help="Number of intersection points of squares in the long side",
  111. )
  112. @click.option(
  113. "--height",
  114. type=int,
  115. required=True,
  116. default=9,
  117. help="Number of intersection points of squares in the short side",
  118. )
  119. @click.option(
  120. "--output_path",
  121. type=str,
  122. required=True,
  123. default="data/processed/colmap_db/colmap_text",
  124. help="YML file to save calibration matrices",
  125. )
  126. def calibrate(
  127. image_dir,
  128. image_format,
  129. square_size,
  130. width,
  131. height,
  132. output_path
  133. ):
  134. """Apply camera calibration operation for images in the given directory path."""
  135. # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(8,6,0)
  136. objp = np.zeros((height * width, 3), np.float32)
  137. objp[:, :2] = np.mgrid[0:width, 0:height].T.reshape(-1, 2)
  138. objp = objp * square_size
  139. # Arrays to store object points and image points from all the images.
  140. objpoints = [] # 3d point in real world space
  141. imgpoints = [] # 2d points in image plane.
  142. images = [x.as_posix() for x in Path(image_dir).glob("*." + image_format)]
  143. for fname in images:
  144. img = cv2.imread(fname)
  145. gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  146. # Find the chess board corners
  147. ret, corners = cv2.findChessboardCorners(gray, (width, height), None)
  148. # If found, add object points, image points (after refining them)
  149. if ret:
  150. objpoints.append(objp)
  151. corners2 = cv2.cornerSubPix(gray, corners, (11, 11), (-1, -1), CRITERIA)
  152. imgpoints.append(corners2)
  153. # Draw and display the corners
  154. img = cv2.drawChessboardCorners(img, (width, height), corners2, ret)
  155. height, width = img.shape[:2]
  156. ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(
  157. objpoints, imgpoints, gray.shape[::-1], None, None
  158. )
  159. print("ret:", ret)
  160. print("mtx:", mtx)
  161. print("dist:", dist)
  162. print("rvecs:", rvecs)
  163. print("tvecs:", tvecs)
  164. save_coefficients(width, height, mtx, dist[0], output_path)
  165. print("Calibration is finished. RMS: ", ret)
  166. if __name__ == "__main__":
  167. main()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...