calibrate.py 3.24 KB
Newer Older
1
#!/usr/bin/env python
2

flp's avatar
flp committed
3 4 5 6 7 8 9 10 11 12 13 14 15
'''
camera calibration for distorted images with chess board samples
reads distorted images, calculates the calibration and write undistorted images

usage:
    calibrate.py [--debug <output path>] [--square_size] [<image mask>]

default values:
    --debug:    ./output/
    --square_size: 1.0
    <image mask> defaults to ../data/left*.jpg
'''

16 17 18
# Python 2/3 compatibility
from __future__ import print_function

19 20
import numpy as np
import cv2
21 22

# local modules
23 24
from common import splitfn

25 26 27
# built-in modules
import os

28
if __name__ == '__main__':
29 30
    import sys
    import getopt
31 32
    from glob import glob

flp's avatar
flp committed
33
    args, img_mask = getopt.getopt(sys.argv[1:], '', ['debug=', 'square_size='])
34
    args = dict(args)
flp's avatar
flp committed
35 36 37 38 39
    args.setdefault('--debug', './output/')
    args.setdefault('--square_size', 1.0)
    if not img_mask:
        img_mask = '../data/left*.jpg'  # default
    else:
40
        img_mask = img_mask[0]
41

42 43
    img_names = glob(img_mask)
    debug_dir = args.get('--debug')
flp's avatar
flp committed
44 45 46
    if not os.path.isdir(debug_dir):
        os.mkdir(debug_dir)
    square_size = float(args.get('--square_size'))
47 48

    pattern_size = (9, 6)
flp's avatar
flp committed
49 50
    pattern_points = np.zeros((np.prod(pattern_size), 3), np.float32)
    pattern_points[:, :2] = np.indices(pattern_size).T.reshape(-1, 2)
51 52 53 54 55
    pattern_points *= square_size

    obj_points = []
    img_points = []
    h, w = 0, 0
flp's avatar
flp committed
56
    img_names_undistort = []
57
    for fn in img_names:
flp's avatar
flp committed
58
        print('processing %s... ' % fn, end='')
59
        img = cv2.imread(fn, 0)
60
        if img is None:
flp's avatar
flp committed
61 62
            print("Failed to load", fn)
            continue
63

64 65 66
        h, w = img.shape[:2]
        found, corners = cv2.findChessboardCorners(img, pattern_size)
        if found:
flp's avatar
flp committed
67
            term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1)
68
            cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
flp's avatar
flp committed
69

70 71 72 73
        if debug_dir:
            vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
            cv2.drawChessboardCorners(vis, pattern_size, corners, found)
            path, name, ext = splitfn(fn)
flp's avatar
flp committed
74 75 76 77 78
            outfile = debug_dir + name + '_chess.png'
            cv2.imwrite(outfile, vis)
            if found:
                img_names_undistort.append(outfile)

79
        if not found:
80
            print('chessboard not found')
81
            continue
flp's avatar
flp committed
82

83 84 85
        img_points.append(corners.reshape(-1, 2))
        obj_points.append(pattern_points)

86
        print('ok')
87

flp's avatar
flp committed
88
    # calculate camera distortion
89
    rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
flp's avatar
flp committed
90

flp's avatar
flp committed
91 92 93
    print("\nRMS:", rms)
    print("camera matrix:\n", camera_matrix)
    print("distortion coefficients: ", dist_coefs.ravel())
flp's avatar
flp committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111

    # undistort the image with the calibration
    print('')
    for img_found in img_names_undistort:
        img = cv2.imread(img_found)

        h,  w = img.shape[:2]
        newcameramtx, roi = cv2.getOptimalNewCameraMatrix(camera_matrix, dist_coefs, (w, h), 1, (w, h))

        dst = cv2.undistort(img, camera_matrix, dist_coefs, None, newcameramtx)

        # crop and save the image
        x, y, w, h = roi
        dst = dst[y:y+h, x:x+w]
        outfile = img_found + '_undistorted.png'
        print('Undistorted image written to: %s' % outfile)
        cv2.imwrite(outfile, dst)

112
    cv2.destroyAllWindows()