OpenCV Camera Calibration with a cv2 CalibrateCamera Example
cv2 calibrateCamera example using OpenCV demonstrates estimating camera intrinsics and distortion from chessboard images. Step-by-step data prep, calibration, and validation in Python for robust camera models in robotics and computer vision.

cv2.calibrateCamera estimates the camera intrinsic matrix and distortion coefficients from multiple calibration images. It relies on 3D-2D point correspondences gathered from a chessboard, then refines the camera model through optimization. This cv2 calibratecamera example shows a standard, end-to-end workflow for reliable calibration.
cv2 calibratecamera example
In this cv2 calibratecamera example, we'll walk through a standard chessboard calibration pipeline using Python and OpenCV. The goal is to estimate the camera intrinsic matrix and distortion coefficients from multiple images. The approach is widely used in robotics and computer vision to achieve accurate depth and measurement. We’ll outline data prep, corner detection, sub-pixel refinement, and the final optimization that yields the camera model. This tutorial uses a common 9x6 chessboard pattern to illustrate the end-to-end workflow.
import cv2
import numpy as np
# Chessboard size (columns x rows)
pattern_size = (9, 6)
# Termination criteria for cornerSubPix
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Prepare object points: (0,0,0), (1,0,0), ..., (8,5,0)
objp = np.zeros((pattern_size[0]*pattern_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2)
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image planeDetecting corners and preparing data
First, collect your calibration images and define the board size. The following snippet initializes the object points and sets a termination criterion for corner refinement. The detected corners are later appended to imgpoints along with corresponding objpoints.
# Chessboard size (columns x rows)
pattern_size = (9, 6)
# Termination criteria for cornerSubPix
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# Prepare object points: (0,0,0), (1,0,0), ..., (8,5,0)
objp = np.zeros((pattern_size[0]*pattern_size[1], 3), np.float32)
objp[:, :2] = np.mgrid[0:pattern_size[0], 0:pattern_size[1]].T.reshape(-1, 2)
objpoints = [] # 3d points in real world space
imgpoints = [] # 2d points in image planeRunning calibration and interpreting results
With corners detected in multiple images, run the calibration to compute the camera matrix and distortion coefficients. The code prints the re-projection error and returns mtx, dist, rvecs, tvecs. Use these to undistort images and evaluate accuracy.
# Suppose objpoints and imgpoints are collected and gray is the 2D grayscale image
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)
print("Camera matrix:\n", mtx)
print("Distortion coefficients:\n", dist.ravel())
# Optional: save calibration results
np.savez("calibration_outputs.npz", mtx=mtx, dist=dist, rvecs=rvecs, tvecs=tvecs)
# Undistort a tested image
h, w = gray.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 1, (w,h))
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)Validation, tips, and common pitfalls
Assess calibration quality by computing the re-projection error across all training images. A low mean error indicates good calibration. Also consider using getOptimalNewCameraMatrix for undistortion, and remember to capture varied poses to improve robustness. Common pitfalls include blurry images, repeated patterns, and inconsistent board sizes.
# Reprojection error calculation (example)
mean_error = 0
for i in range(len(objpoints)):
imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist)
error = cv2.norm(imgpoints[i], imgpoints2, cv2.NORM_L2)/len(imgpoints2)
mean_error += error
print("Mean reprojection error:", mean_error/len(objpoints))# Batch calibration script example
python calibrate_batch.py --images-folder ./calib_images --pattern-size 9 6Steps
Estimated time: 60-90 minutes
- 1
Prepare chessboard and images
Choose a board size (e.g., 9x6) and collect 15–25 diverse images showing corners from different angles, distances, and lighting. This step builds robust data for calibration.
Tip: Avoid blurry frames; ensure corners are clearly visible. - 2
Create object and image point containers
Initialize objpoints and imgpoints arrays to accumulate 3D-2D correspondences across all images.
Tip: Objpoints stay constant for a given board; image points vary per image. - 3
Detect and refine chessboard corners
Detect corners with findChessboardCorners and refine with cornerSubPix to sub-pixel accuracy.
Tip: Refinement improves calibration stability. - 4
Run cv2.calibrateCamera
Call calibrateCamera with all point correspondences and image sizes to obtain mtx, dist, rvecs, tvecs.
Tip: Check internal consistency by inspecting reprojection error. - 5
Validate results and undistort
Compute reprojection error, save parameters, and test undistortion on sample images.
Tip: Use getOptimalNewCameraMatrix for better remapping. - 6
Document and reuse calibration
Store results in a file for reuse in future runs and applications.
Tip: Document board size, pattern, and number of images used.
Prerequisites
Required
- Required
- Required
- Required
- Calibration chessboard images (e.g., 9x6 or 8x7)Required
Optional
- Optional
Keyboard Shortcuts
| Action | Shortcut |
|---|---|
| CopyIn code blocks or terminal | Ctrl+C |
| PasteIn code blocks or editor | Ctrl+V |
| Run current Python fileIn VS Code or PyCharm | Ctrl+F5 |
Questions & Answers
What is the cv2.calibrateCamera function used for?
cv2.calibrateCamera computes the camera matrix and distortion coefficients by minimizing the reprojection error across several calibration images. It yields intrinsic parameters useful for undistortion and 3D pose estimation.
It computes the camera model from multiple images, giving you intrinsic parameters you can use to correct distortion.
How many calibration images are enough?
Aim for 15 to 25 good-quality images showing the chessboard from different angles and distances. More diverse viewpoints generally improve calibration robustness.
Typically 15 to 25 well-spread images provide a solid calibration.
Which chessboard size should I choose?
Choose a board with a clear, high-contrast pattern and enough corners. Common sizes are 9x6 or 8x7; ensure your code matches the actual pattern.
Pick a board size that offers many well-spaced corners and is easy to detect.
Can I calibrate without a chessboard?
Calibration can be done with other patterns or datasets, but a chessboard is widely used due to its regular corner layout and ease of detection. Alternative targets require different corner extraction steps.
A chessboard is the easiest path; other targets require different detection logic.
How do I validate calibration results?
Check the mean reprojection error across all images; a lower value indicates better calibration. Also verify undistorted image quality visually and via re-projection checks.
Look at the reprojection error and test undistortion on sample images.
Key Takeaways
- Capture diverse chessboard images
- Compute intrinsic and distortion with cv2.calibrateCamera
- Evaluate accuracy using reprojection error
- Undistort with the obtained parameters
- Save calibration results for reuse