import numpy as np
import cv2, cv
import os
from common import splitfn

USAGE = '''
USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<image mask>] 
'''

if __name__ == '__main__':
    import sys, getopt
    from glob import glob

    args, img_mask = getopt.getopt(sys.argv[1:], '', ['save=', 'debug=', 'square_size='])
    args = dict(args)
    try: img_mask = img_mask[0]
    except:
        img_mask = '../cpp/left*.jpg'
        img_mask_right = '../cpp/right*.jpg'
    img_names = glob(img_mask)
    img_names_right = glob(img_mask_right)

    debug_dir = args.get('--debug')
    square_size = float(args.get('--square_size', 1.0))

    pattern_size = (9, 6)
    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

    obj_points = []
    img_points = []

    pattern_points_right = np.zeros( (np.prod(pattern_size), 3), np.float32 )
    pattern_points_right[:,:2] = np.indices(pattern_size).T.reshape(-1, 2)
    pattern_points_right *= square_size

    obj_points_right = []
    img_points_right = []
    h, w = 0, 0
    for fn in img_names:
        print 'processing %s...' % fn,
        img = cv2.imread(fn, 0)
        h, w = img.shape[:2]
        found, corners = cv2.findChessboardCorners(img, pattern_size)
        
        if found:
            term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 )
            cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term)
        if debug_dir:
            vis = cv2.cvtColor(img, cv.CV_GRAY2BGR)
            cv2.drawChessboardCorners(vis, pattern_size, corners, found)
            path, name, ext = splitfn(fn)
            cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name), vis)
        if not found:
            print 'chessboard not found'
            continue
        img_points.append(corners.reshape(-1, 2))
        obj_points.append(pattern_points)
        
        print 'ok left'
    for fn in img_names_right:
        print 'processing right  %s...' % fn,
        img_right = cv2.imread(fn, 0)
        h, w = img_right.shape[:2]
        found_right, corners_right = cv2.findChessboardCorners(img_right, pattern_size)
        
        if found:
            term = ( cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1 )
            cv2.cornerSubPix(img_right, corners_right, (5, 5), (-1, -1), term)
        if debug_dir:
            vis_right = cv2.cvtColor(img_right, cv.CV_GRAY2BGR)
            cv2.drawChessboardCorners(vis_right, pattern_size, corners_right, found_right)
            path, name_right, ext = splitfn(fn)
            cv2.imwrite('%s/%s_chess.bmp' % (debug_dir, name_right), vis)
        if not found:
            print 'chessboard not found'
            continue
        img_points_right.append(corners_right.reshape(-1, 2))
        obj_points_right.append(pattern_points_right)
        
        print 'ok right'

  #  print '-------------', type(corners), len(corners)
    cv.WaitKey()
    camera_matrix = np.zeros((3, 3))
    dist_coefs = np.zeros(4)
    img_n = len(img_points)
    rms, camera_matrix, dist_coefs, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), camera_matrix, dist_coefs)
    print "RMS:", rms
    print "camera matrix:\n", camera_matrix
    print "distortion coefficients: ", dist_coefs.ravel()

    print "#now use left/right images to find fundmenatla matrix"
    print len(img_points), type(img_points), type(corners),  corners.shape
    print corners.shape, corners_right.dtype, corners
    
    print '----find fundamental matrixs------------'
    fundamental = cv.CreateMat(3, 3, cv.CV_32FC1)
    cv.FindFundamentalMat(corners, corners_right, fundamental)
    print fundamental, type (fundamental), fundamental.tostring()

    a = np.asarray(fundamental) # a way to print out a cvMat, np=numpy, see line 1
    print a

    
    
