Path: blob/master/CameraCalibration/cameraCalibration.py
3118 views
#!/usr/bin/env python12import cv23import numpy as np4import os5import glob67# Defining the dimensions of checkerboard8CHECKERBOARD = (6,9)9criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)1011# Creating vector to store vectors of 3D points for each checkerboard image12objpoints = []13# Creating vector to store vectors of 2D points for each checkerboard image14imgpoints = []151617# Defining the world coordinates for 3D points18objp = np.zeros((1, CHECKERBOARD[0]*CHECKERBOARD[1], 3), np.float32)19objp[0,:,:2] = np.mgrid[0:CHECKERBOARD[0], 0:CHECKERBOARD[1]].T.reshape(-1, 2)20prev_img_shape = None2122# Extracting path of individual image stored in a given directory23images = glob.glob('./images/*.jpg')24for fname in images:25img = cv2.imread(fname)26gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)27# Find the chess board corners28# If desired number of corners are found in the image then ret = true29ret, corners = cv2.findChessboardCorners(gray, CHECKERBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH+30cv2.CALIB_CB_FAST_CHECK+cv2.CALIB_CB_NORMALIZE_IMAGE)3132"""33If desired number of corner are detected,34we refine the pixel coordinates and display35them on the images of checker board36"""37if ret == True:38objpoints.append(objp)39# refining pixel coordinates for given 2d points.40corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)4142imgpoints.append(corners2)4344# Draw and display the corners45img = cv2.drawChessboardCorners(img, CHECKERBOARD, corners2,ret)4647cv2.imshow('img',img)48cv2.waitKey(0)4950cv2.destroyAllWindows()5152h,w = img.shape[:2]5354"""55Performing camera calibration by56passing the value of known 3D points (objpoints)57and corresponding pixel coordinates of the58detected corners (imgpoints)59"""60ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)6162print("Camera matrix : \n")63print(mtx)64print("dist : \n")65print(dist)66print("rvecs : \n")67print(rvecs)68print("tvecs : \n")69print(tvecs)707172