def matlab2PointCorrespondences(filename): '''Loads and converts the point correspondences saved by the matlab camera calibration tool''' from numpy.lib.io import loadtxt, savetxt from numpy.lib.function_base import append points = loadtxt(filename, delimiter=',') savetxt(utils.removeExtension(filename)+'-point-correspondences.txt',append(points[:,:2].T, points[:,3:].T, axis=0))
def cameraIntrinsicCalibration(path, checkerBoardSize=[6,7], secondPassSearch=False, display=False): ''' Camera calibration searches through all the images (jpg or png) located in _path_ for matches to a checkerboard pattern of size checkboardSize. These images should all be of the same camera with the same resolution. For best results, use an asymetric board and ensure that the image has very high contrast, including the background. Suitable checkerboard: http://ftp.isr.ist.utl.pt/pub/roswiki/attachments/camera_calibration(2f)Tutorials(2f)StereoCalibration/check-108.png The code below is based off of: https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_calib3d/py_calibration/py_calibration.html Modified by Paul St-Aubin ''' from numpy import zeros, mgrid, float32, savetxt import glob, os # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = zeros((checkerBoardSize[0]*checkerBoardSize[1],3), float32) objp[:,:2] = mgrid[0:checkerBoardSize[1],0:checkerBoardSize[0]].T.reshape(-1,2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. ## Loop throuhg all images in _path_ images = glob.glob(os.path.join(path,'*.[jJ][pP][gG]'))+glob.glob(os.path.join(path,'*.[jJ][pP][eE][gG]'))+glob.glob(os.path.join(path,'*.[pP][nN][gG]')) for fname in images: img = cv2.imread(fname) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(gray, (checkerBoardSize[1],checkerBoardSize[0]), None) # If found, add object points, image points (after refining them) if ret: print 'Found pattern in '+fname if(secondPassSearch): corners = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria) objpoints.append(objp) imgpoints.append(corners) # Draw and display the corners if(display): img = cv2.drawChessboardCorners(img, (checkerBoardSize[1],checkerBoardSize[0]), corners, ret) if(img): cv2.imshow('img',img) cv2.waitKey(0) ## Close up image loading and calibrate cv2.destroyAllWindows() if len(objpoints) == 0 or len(imgpoints) == 0: return False try: ret, camera_matrix, dist_coeffs, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None) except NameError: return False savetxt('intrinsic-camera.txt', camera_matrix) return camera_matrix, dist_coeffs