Skip to content

Instantly share code, notes, and snippets.

@fritzfrancisco
Created October 11, 2021 12:40
Show Gist options
  • Save fritzfrancisco/5a5de81d479576cf1e39de0a5d75c6d9 to your computer and use it in GitHub Desktop.
Save fritzfrancisco/5a5de81d479576cf1e39de0a5d75c6d9 to your computer and use it in GitHub Desktop.
Single camera calibration using OpenCV
#!/usr/bin/env python3
# input video file:
input_file = 'input_video.mp4'
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# change this to your checkerboard dimensions:
width_number_of_squares = 14
height_number_of_squares = 9
# change this to own preference:
numer_of_calibration_images = 200
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((height_number_of_squares*width_number_of_squares,3), np.float32)
objp[:,:2] = np.mgrid[0:width_number_of_squares,0:height_number_of_squares].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.
# initiate video capture
cap = cv2.VideoCapture(input_file)
frame_idx = 0
calibration_images = 0
# create empty window
cv2.namedWindow('img',cv2.WINDOW_NORMAL)
while(cap.isOpened()):
ret, img = cap.read()
if calibration_images >= numer_of_calibration_images:
print('frame count: ',frame_idx)
break
if ret == True:
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Find the chess board corners
check_ret, corners = cv2.findChessboardCornersSB(gray, (width_number_of_squares,height_number_of_squares),None)
# If found, add object points, image points (after refining them)
if check_ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners2)
calibration_images += 1
# Draw and display the corners
img = cv2.drawChessboardCorners(img, (width_number_of_squares,height_number_of_squares), corners2, check_ret)
cv2.imshow('img',img)
# close window by pressing 'q'
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
if frame_idx % 5 == 0:
print('frame count: ',frame_idx)
frame_idx += 1
else:
continue
cv2.destroyAllWindows()
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
print(ret, mtx, dist, rvecs, tvecs)
print('Finished calibration!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment