Below is a self-contained, heavily-commented Python script that shows the complete “logic chain” for a two–image, one-shot projector calibration:
• image 1 = photo of a PHYSICAL checkerboard that you hold against the wall
• image 2 = photo of a CHECKERBOARD PROJECTED by the beamer on the exact same wall
Both checkerboards have a 9 × 6 inner-corner pattern (i.e. 9 columns × 6 rows of inner corners = 10 × 7 squares).
The square size of the real board is known (e.g. 25 mm), the square size of the projected pattern can be any convenient pixel unit (e.g. 100 px).
What you get out:
• the camera intrinsics (so you know the camera)
• the pose of the wall in the camera coordinate system
• the pose & intrinsics of the projector (so you can later warp any picture through the projector so it lands perfectly flat on the wall)
• A 3 × 3 homography H_proj2wall that maps projector pixels → wall coordinates
Copy → paste the file, adjust the paths & constants at the top, run, and inspect the visual overlays to make sure both checkerboards were detected correctly. 🛠️
#!/usr/bin/env python3
"""
Projector ↔ wall calibration from TWO pictures:
------------------------------------------------
1) physical_checkerboard.jpg (real board held to wall)
2) projected_checkerboard.jpg (board projected by beamer)
Both patterns are 9×6 inner corners.
OpenCV ≥4.5 required.
"""
import cv2
import numpy as np
import json
from pathlib import Path
# ===================================================================
# ------------------- USER-ADJUSTABLE PARAMETERS --------------------
# ===================================================================
# Paths to the two photographs (taken from the SAME camera position)
IMG_PHYSICAL = "physical_checkerboard.jpg"
IMG_PROJECTED = "projected_checkerboard.jpg"
# Physical board parameters
PATTERN_SIZE = (9, 6) # inner corners (columns, rows)
SQUARE_SIZE_MM = 25.0 # physical square edge length
# Projector pattern parameters
PROJECTOR_RESOLUTION = (1920, 1080) # width, height in px
PROJ_SQUARE_SIZE_PX = 100.0 # square edge length you used
# in the generated projected pattern
# -- visualisation / output
DEBUG_OVERLAYS = True
OUTPUT_JSON_FILE = "projector_calibration.json"
# ===================================================================
# ------------------------- HELPER UTILS ----------------------------
# ===================================================================
def get_object_points(pattern_size, square_size):
"""
Returns (N,3) array with (x,y,z=0) world pts for a flat checkerboard.
pattern_size = (cols, rows) (# inner corners!)
square_size = physical size unit (e.g. mm or arbitrary “projector units”)
"""
cols, rows = pattern_size
objp = np.zeros((rows * cols, 3), np.float32)
objp[:, :2] = np.mgrid[0:cols, 0:rows].T.reshape(-1, 2)
objp *= square_size
return objp
def find_corners(img_gray, pattern_size):
"""
Detect checkerboard and return refined sub-pixel corners.
Raises ValueError if detection fails.
"""
flags = cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_NORMALIZE_IMAGE
ok, corners = cv2.findChessboardCorners(img_gray, pattern_size, flags)
if not ok:
raise ValueError("Checkerboard NOT found!")
# Sub-pixel refinement
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER,
30, 0.001)
cv2.cornerSubPix(img_gray, corners, (11,11), (-1,-1), criteria)
return corners
def draw_corners_bgr(image_bgr, corners, pattern_size):
vis = image_bgr.copy()
cv2.drawChessboardCorners(vis, pattern_size, corners, True)
return vis
# ===================================================================
# ---------------------- MAIN CALIBRATION --------------------------
# ===================================================================
def main():
# ----------------- 1) load images -----------------------------
img_phys_bgr = cv2.imread(IMG_PHYSICAL)
img_proj_bgr = cv2.imread(IMG_PROJECTED)
if img_phys_bgr is None:
raise FileNotFoundError(IMG_PHYSICAL)
if img_proj_bgr is None:
raise FileNotFoundError(IMG_PROJECTED)
gray_phys = cv2.cvtColor(img_phys_bgr, cv2.COLOR_BGR2GRAY)
gray_proj = cv2.cvtColor(img_proj_bgr, cv2.COLOR_BGR2GRAY)
# ----------------- 2) find corners in BOTH images -------------
corners_phys = find_corners(gray_phys, PATTERN_SIZE)
corners_proj = find_corners(gray_proj, PATTERN_SIZE)
if DEBUG_OVERLAYS:
cv2.imshow("Physical corners", draw_corners_bgr(img_phys_bgr, corners_phys, PATTERN_SIZE))
cv2.imshow("Projected corners", draw_corners_bgr(img_proj_bgr, corners_proj, PATTERN_SIZE))
cv2.waitKey(500)
# ----------------- 3) CAMERA calibration ----------------------
objp_phys_mm = get_object_points(PATTERN_SIZE, SQUARE_SIZE_MM)
imgpoints = [corners_phys] # only 1 view, still works
objpoints = [objp_phys_mm]
ret, cam_K, cam_dist, rvecs, tvecs = cv2.calibrateCamera(
objpoints, imgpoints, gray_phys.shape[::-1], None, None, flags=0)
print("\n=== Camera intrinsics ===")
print(cam_K)
print("dist:", cam_dist.ravel())
# Pose of the PHYSICAL board wrt camera
rvec_wall, tvec_wall = cv2.solvePnP(
objp_phys_mm, corners_phys, cam_K, cam_dist)[:2]
# ----------------- 4) Pose of the PROJECTED board -------------
# Same solver but using a *virtual* square size in “projector units”
objp_proj_units = get_object_points(PATTERN_SIZE, PROJ_SQUARE_SIZE_PX)
rvec_proj, tvec_proj = cv2.solvePnP(
objp_proj_units, corners_proj, cam_K, cam_dist)[:2]
# ----------------- 5) Derive the projector intrinsics ---------
# Treat the projector as an inverse camera. We have:
# wall points (in projector units) <---> projector pixels
# For a standard checkerboard the relation within the plane is a 3×3 homography.
#
# Step A: Express 3-D object points of projected board in CAMERA frame
R_proj, _ = cv2.Rodrigues(rvec_proj)
R_wall, _ = cv2.Rodrigues(rvec_wall)
# object points of projected board in its local coordinates (N,3)
P_local = objp_proj_units # shape (N,3)
# points expressed in CAMERA coordinates:
P_cam = (R_proj @ P_local.T + tvec_proj).T # (N,3)
# Step B: Projector pixel coordinates are *known* analytically:
# They are exactly the 2-D grid times square size,
# but you might have rendered the checkerboard with a margin.
# Here we assume the checkerboard was displayed full-screen and
# located at the top-left (0,0) of projector coordinates.
#
# If you rendered differently, supply the proper 2-D source coords!
px_cols, px_rows = PATTERN_SIZE
proj_pixels = np.zeros((px_rows*px_cols, 2), np.float32)
proj_pixels[:,0:2] = np.mgrid[0:px_cols,0:px_rows].T.reshape(-1,2)
proj_pixels *= PROJ_SQUARE_SIZE_PX
# Step C: Compute projector intrinsics & extrinsics
retval, proj_K, proj_dist, rvecs_P, tvecs_P = cv2.calibrateCamera(
[proj_pixels[:,:,None].astype(np.float32)],
[P_cam[:,:2].astype(np.float32)], # 2-D homogeneous? we have 3-D in plane, okay
PROJECTOR_RESOLUTION, None, None,
flags=(cv2.CALIB_ZERO_TANGENT_DIST +
cv2.CALIB_FIX_K3 + cv2.CALIB_FIX_K4 + cv2.CALIB_FIX_PRIOR))
print("\n=== Projector intrinsics ===")
print(proj_K)
print("dist:", proj_dist.ravel())
# ----------------- 6) 2-D homography projector->wall ----------
# (purely planar mapping; sufficient for most projection-mapping)
H_proj2wall, _ = cv2.findHomography(proj_pixels, objp_phys_mm[:,0:2])
print("\n=== Homography (projector px → wall mm) ===")
print(H_proj2wall)
# ----------------- 7) quick test: warp a dummy grid -----------
if DEBUG_OVERLAYS:
demo = np.zeros((PROJECTOR_RESOLUTION[1], PROJECTOR_RESOLUTION[0],3), np.uint8)
cv2.putText(demo, "TEST", (500,540), cv2.FONT_HERSHEY_DUPLEX, 6, (255,255,255), 10)
# Warp into wall-mm space (for viewing we go via camera again)
warped = cv2.warpPerspective(demo, H_proj2wall, (int(SQUARE_SIZE_MM*PATTERN_SIZE[0]*1.2),
int(SQUARE_SIZE_MM*PATTERN_SIZE[1]*1.2)))
cv2.imshow("Warped projector frame in wall coords (mm units)", warped)
cv2.waitKey(0)
# ----------------- 8) save everything -------------------------
data = {
"camera_matrix": cam_K.tolist(),
"camera_distortion": cam_dist.tolist(),
"projector_matrix": proj_K.tolist(),
"projector_distortion": proj_dist.tolist(),
"H_proj2wall": H_proj2wall.tolist(),
"pattern_size": PATTERN_SIZE,
"physical_square_mm": SQUARE_SIZE_MM,
"proj_square_px": PROJ_SQUARE_SIZE_PX
}
with open(OUTPUT_JSON_FILE, "w") as f:
json.dump(data, f, indent=2)
print(f"\n👉 Saved calibration to {OUTPUT_JSON_FILE}\n")
# ===================================================================
if __name__ == "__main__":
main()
What does the script do, step by step?
- Finds the inner corners in BOTH photos.
- Uses the PHYSICAL board to calibrate the camera (intrinsics + pose of the wall).
- Uses the same camera parameters to solve the pose of the PROJECTED board.
- From that, recovers the projector’s intrinsic matrix (treating it as an inverse camera).
- Computes a clean 3 × 3 homography H that sends projector pixels directly onto “wall millimetres.”
- Writes all data into projector_calibration.json so you can reuse it in realtime mapping code.
Tips & Notes
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
• The maths assumes both boards are perfectly planar and lie on the same wall.
• If you shot the two photos from slightly different camera positions you need to redo them: they must be from the same tripod/camera pose or all bets are off.
• In many practical “projection-mapping” jobs you don’t even need the full camera/projector intrinsics; the 3 × 3 homography you get is already enough to keystone-correct arbitrary frames you send to the projector.
Happy calibrating! 🎥🔧