import numpy as np
import cv2 as cv
import sys


# armar el patron
pattern_size = (9, 6)
square_size = 25.0
pattern_points = np.zeros( (np.prod(pattern_size), 3), np.float32 )
pattern_points[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
pattern_points *= square_size

cv.namedWindow("calibrate", 1)

obj_points = []
img_points = []
img_names= sys.argv[1:]
for fn in img_names:
    print 'processing %s...' % fn,
    img = cv.imread(fn, 0)
    cv.imshow("calibrate", img)
    found, corners = cv.findChessboardCorners(img, pattern_size)
    if found:
        vis = cv.cvtColor(img, cv.COLOR_GRAY2BGR)
        cv.drawChessboardCorners(vis, pattern_size, corners, found)
        cv.imshow("calibrate", vis)
        cv.waitKey()
    if not found:
        print 'chessboard not found'
        continue
    img_points.append(corners.reshape(-1, 2))
    obj_points.append(pattern_points)
    print 'ok'

h, w = img.shape[:2]
rms, camera_matrix, dist_coefs, rvecs, tvecs = cv.calibrateCamera(obj_points, img_points, (w, h))
print "camera matrix:\n", camera_matrix
print "distortion coefficients: ", dist_coefs.ravel()
print 'r vecs', rvecs
print 't vecs', tvecs

aw, ah = (w*6e-3,h*6e-3)
fovx, fovy, focalLength, principalPoint, aspectRatio = cv.calibrationMatrixValues( camera_matrix, (w, h), aw, ah)

print 'fovx, fovy,:', fovx, fovy
print 'focalLength: ', focalLength
print 'principalPoint:', principalPoint
print 'aspectRatio:', aspectRatio

cv.destroyWindow('calibrate')
for fn in img_names:
    print 'undistorting %s...' % fn,
    img = cv.imread(fn, 0)
    warped_img = cv.undistort(img, camera_matrix, dist_coefs)
    cv.imshow("undistort", warped_img)
    cv.waitKey()
    cv.imwrite('u_'+fn, warped_img)
    print 'ok'

cv.destroyAllWindows()

