# Tactiverge Academy — companion code for "Camera geometry and the pinhole model"
# Lesson: https://tactiverge.win/academy/computational-engineering/introduction-to-computer-vision/camera-geometry/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
f = 600.0              # focal length, pixels
cx, cy = 320.0, 240.0  # principal point (image centre), pixels

def project(X, Y, Z):
    """Pinhole projection of a point in camera coordinates (metres)."""
    u = f * X / Z + cx
    v = f * Y / Z + cy
    return round(u, 1), round(v, 1)

print(project(0.10, 0.05, 1.0))   # 10 cm right, 5 cm down, 1 m away
print(project(0.10, 0.05, 2.0))   # same offset, twice as far
print(project(0.20, 0.10, 2.0))   # twice the offset, twice as far


# ── Example 2 ────────────────────────────────────────
import math

def focal_pixels(image_width_px, horizontal_fov_deg):
    half = math.radians(horizontal_fov_deg / 2)
    return (image_width_px / 2) / math.tan(half)

print(f"{focal_pixels(640, 60):.1f} px")
print(f"{focal_pixels(640, 90):.1f} px")


# ── Example 3 ────────────────────────────────────────
f = 600.0          # focal length, pixels
H = 0.065          # real height of a tennis-ball-sized object, metres

for h_pixels in [78, 39, 20]:
    Z = f * H / h_pixels
    print(f"{h_pixels:3d} px tall -> about {Z:.2f} m away")

# How much does a 1-pixel mistake matter?
Z_true = f * H / 20
Z_off  = f * H / 19
print(f"1 px error at 20 px changes the estimate by {(Z_off - Z_true) * 100:.1f} cm")
print(f"Each pixel spans {Z_true / f * 1000:.1f} mm at {Z_true:.2f} m")
