1#!/usr/bin/env python
2
3import numpy as np
4import cv2
5
6# local modules
7from common import splitfn
8
9# built-in modules
10import os
11
12
13USAGE = '''
14USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<image mask>]
15'''
16
17
18
19if __name__ == '__main__':
20    import sys
21    import getopt
22    from glob import glob
23
24    args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
25    args = dict(args)
26    try:
27        img_mask = img_mask[0]
28    except:
29        img_mask = '../data/left*.jpg'
30
31    img_names = glob(img_mask)
32    debug_dir = args.get('--debug')
33    square_size = float(args.get('--square_size', 1.0))
34
35    pattern_size = (9, 6)
36    pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
37    pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
38    pattern_points *= square_size
39
40    obj_points = []
41    img_points = []
42    h, w = 0, 0
43    for fn in img_names:
44        print 'processing %s...' % fn,
45        img = cv2.imread(fn, 0)
46        if img is None:
47          print "Failed to load", fn
48          continue
49
50        h, w = img.shape[:2]
51        found, corners = cv2.findChessboardCorners(img, pattern_size)
52        if found:
53            term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 )
54            cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
55        if debug_dir:
56            vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
57            cv2.drawChessboardCorners(vis, pattern_size, corners, found)
58            path, name, ext = splitfn(fn)
59            cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
60        if not found:
61            print 'chessboard not found'
62            continue
63        img_points.append(corners.reshape(-1, 2))
64        obj_points.append(pattern_points)
65
66        print 'ok'
67
68    rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
69    print "RMS:", rms
70    print "camera matrix:\n", camera_matrix
71    print "distortion coefficients: ", dist_coefs.ravel()
72    cv2.destroyAllWindows()
73