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))
cv.destroyWindow('calibrate')

cap = cv.VideoCapture(0)

cv.namedWindow('video', 1)
cv.namedWindow('undistort video', 1)

while True:
    ret, im = cap.read()
    warped_im = cv.undistort(im, camera_matrix, dist_coefs)
    cv.imshow('video', im)
    cv.imshow('undistort video', warped_im)
    
    key = cv.waitKey(33)
    if key == 1048603:
        break

cv.destroyAllWindows()

