1+ import cv2
2+ import numpy as np
3+ import copy
4+ import yaml
5+
6+ input = "data/chessboard.avi"
7+
8+ board_pattern = (10 , 7 )
9+ select_images = True
10+
11+ capture = cv2 .VideoCapture (input )
12+
13+ if capture .isOpened () == False : raise Exception ("No video" )
14+
15+ images = []
16+
17+ while True :
18+ ret1 , image = capture .read ()
19+ if not ret1 : break
20+ if select_images :
21+ cv2 .imshow ("3DV Tutorial: Camera Calibration" , image )
22+ key = cv2 .waitKey (1 )
23+ if key == 27 : break # 'ESC' key: Exit
24+ elif key == 32 : # 'Space' key: Pause
25+ ret2 , pts = cv2 .findChessboardCorners (image , board_pattern , None ) # No flags
26+
27+ # display = image.clone()
28+ display = copy .deepcopy (image )
29+ display = cv2 .drawChessboardCorners (display , board_pattern , pts , ret2 )
30+ cv2 .imshow ("3DV Tutorial: Camera Calibration" , display )
31+ key = cv2 .waitKey ()
32+ if key == 27 : break
33+ elif key == 13 : images .append (image ) # 'Enter' key: Save
34+ else :
35+ images .append (image )
36+
37+ capture .release ()
38+
39+ if (len (images )) == 0 :
40+ print ("no images" )
41+ raise Exception ("There is no captured images!" )
42+
43+ # Find 2D corner points from given images
44+ img_points = []
45+ h , w = 0 ,0
46+ for image in images :
47+ gray = cv2 .cvtColor (image , cv2 .COLOR_BGR2GRAY )
48+ h , w = gray .shape
49+ ret3 , corners = cv2 .findChessboardCorners (gray , board_pattern ) # No flags
50+ if ret3 == True :
51+ img_points .append (corners )
52+
53+ if len (img_points ) == 0 :
54+ raise Exception ("No 2d Corner pts" )
55+
56+ # Prepare 3D points of the chess board
57+ objp = np .zeros ((10 * 7 , 3 ), np .float32 )
58+ objp [:, :2 ] = np .mgrid [0 :7 , 0 :10 ].T .reshape (- 1 , 2 )
59+ obj_points = []
60+ for _ in images :
61+ obj_points .append (objp )
62+
63+ # Calibrate Camera
64+ K = np .eye (3 ,3 , dtype = np .float32 )
65+ dist_coeff = np .zeros ((4 ,1 ))
66+ rms , K , dist_coeff , rvecs , tvecs = cv2 .calibrateCamera (obj_points , img_points , (h ,w ), None , None )
67+
68+ # Report calibration results
69+ print ("## Camera Calibration Results" )
70+ print (f"* The number of applied images = { w } x{ h } " )
71+ print (f"* RMS error = { rms } " )
72+ print (f"* Camera matrix (K) = \n { K } " )
73+ print (f"* Distortion coefficient (k1, k2, p1, p2, k3, ...) = { dist_coeff } " )
74+
75+ # Save as cam_config.yaml
76+ file_name = "cfg/cam_config.yaml"
77+ cam_dict = {
78+ "Intrinsic" : K .flatten ().tolist (),
79+ "Distortion" : dist_coeff .flatten ().tolist (),
80+ "RMS" : rms ,
81+ }
82+ with open (file_name , 'w' ) as f :
83+ yaml .dump (cam_dict , f , sort_keys = False , default_flow_style = False )
84+
85+ print ("End!" )
0 commit comments