Does the Code now make real sense and is the logik and calculation correct this is my output: Projector Calibration Matrix (3x3):
[[0.95 0. 0.5 ]
[0. 0.98 0.5 ]
[0. 0. 1. ]] And her is the code: import cv2
import numpy as np
def load_and_detect_corners(image_path, pattern_size):
"""Load image and detect checkerboard corners."""
img = cv2.imread(image_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(gray, pattern_size, None)
if not ret:
raise ValueError(f"Checkerboard corners not found in {image_path}")
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
corners_refined = cv2.cornerSubPix(gray, corners, (11,11), (-1,-1), criteria)
return corners_refined
def main():
# Configuration
pattern_size = (9, 6) # 9x6 squares (inner corners)
physical_img_path = 'physical_checkerboard.png'
projected_img_path = 'projected_checkerboard.png'
# Detect corners in both images
physical_corners = load_and_detect_corners(physical_img_path, pattern_size)
projected_corners = load_and_detect_corners(projected_img_path, pattern_size)
# Generate object points (3D points for the physical checkerboard, assuming 1 unit per square)
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) # Z=0 for planar board
# Compute homography (maps projected points to physical points)
H, _ = cv2.findHomography(projected_corners, physical_corners, method=0)
# Decompose homography (using a simple camera matrix as reference)
K_cam = np.eye(3) # Identity for now, but in practice, use calibrated camera matrix
num_solutions, Rs, ts, ns = cv2.decomposeHomographyMat(H, K_cam)
# Select the first valid solution (positive determinant for R)
valid_solution = None
for i in range(num_solutions):
R = Rs[i]
if np.linalg.det(R) > 0: # Valid rotation
valid_solution = i
break # Use the first valid one
if valid_solution is None:
raise ValueError("No valid solution found for homography decomposition")
R = Rs[valid_solution] # Selected rotation matrix
t = ts[valid_solution].flatten() # Selected translation vector
# Now, derive a more realistic K_proj (this is still simplified)
# In a real scenario, you'd calibrate the projector separately or optimize from multiple views.
# For demonstration, let's approximate based on typical values and add some realism.
# Assume focal lengths near 1 (as per your request), but with slight variations.
K_proj = np.eye(3) # Start with identity
K_proj[0, 0] = 0.95 # fx: Slightly less than 1 for realism
K_proj[1, 1] = 0.98 # fy: Slightly less than 1
K_proj[0, 2] = 0.50 # cx: Principal point x (e.g., half of image width, scaled)
K_proj[1, 2] = 0.50 # cy: Principal point y
# Output the calibration matrix
print("Projector Calibration Matrix (3x3):")
print(K_proj)
if name == "main":
main()