brokkr_reference: planes are solved and say so; the exact gates are one constant with a test at the gate
Follow-up reference-camera-s2-lows. World points in one plane seen obliquely decide the lens, so they are
solved: the record's 'plane' is the degrees between the line of sight and square-on, auto leaves the free
model untried (a plane never decides the centre), and what a near square-on view leaves open is the band's
to say. Refused before solving: a plane with the model free, and a plane seen exactly square-on with no
lens held ('may not decide the lens').
core.EXACT (1e-9) is the one tolerance of the four exact tests; marks at 3.16e-10 are refused and at
3.16e-9 pass, so a gate ten times looser or tighter fails.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
c9f290bb90
commit
8d5e01325b
2 changed files with 101 additions and 19 deletions
|
|
@ -205,24 +205,45 @@ def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot):
|
|||
return float(np.sqrt(np.mean(np.square(miss))))
|
||||
|
||||
|
||||
def _decidable(names, W, P, plane_will_do):
|
||||
EXACT = 1e-9 # of the marks' extent: under this a set of marks is exactly degenerate (true lines and planes read 1e-16); marks placed by hand are never within 1e-3
|
||||
|
||||
|
||||
def _square_on(Q, P):
|
||||
"""How far pixels are from a turned and scaled copy of the points' own plane (Q, their two coordinates in it),
|
||||
mirrored or not, as a share of the pixels' extent: nothing, when the plane is seen square-on."""
|
||||
b = (P - P.mean(0)).T.ravel()
|
||||
miss = []
|
||||
for hand in (1.0, -1.0):
|
||||
x, y = Q[:, 0], hand * Q[:, 1]
|
||||
A = np.r_[np.c_[x, -y], np.c_[y, x]]
|
||||
miss.append(np.linalg.norm(b - A @ np.linalg.lstsq(A, b, rcond=None)[0]))
|
||||
return min(miss) / np.linalg.norm(b)
|
||||
|
||||
|
||||
def _decidable(names, W, P, model, lens_held):
|
||||
"""Refuses marks that cannot decide a camera, by which they are, before anything is solved: the place is solved
|
||||
in units of the marks' extent, so marks of no extent have no solve at all (a logarithm of zero, a record of
|
||||
NaN). These are exact degeneracies, to nine digits of the marks' extent; points nearly in a line or a plane are
|
||||
solved, and what they leave undecided is the band's to say."""
|
||||
NaN). These are exact degeneracies, to EXACT of the marks' extent; points nearly in a line or a plane are
|
||||
solved, and what they leave undecided is the band's to say. Returns the unit normal of the plane the world
|
||||
points all lie in, or None."""
|
||||
for what, A in (("world point", W), ("pixel", P)):
|
||||
first = {}
|
||||
twins = [(first[row], k) for k, row in zip(names, map(tuple, A.tolist())) if row in first or first.setdefault(row, k) is None]
|
||||
if len(first) < 6:
|
||||
raise ReferenceFitError(f"{len(first)} different {what}s are marked; six are needed ({twins[0][0]!r} and {twins[0][1]!r} share one)")
|
||||
flat = lambda A: np.linalg.svd(A - A.mean(0), compute_uv=False) # noqa: E731 the marks' extents along their own axes, widest first
|
||||
w, p = flat(W), flat(P)
|
||||
if p[1] <= 1e-9 * p[0]:
|
||||
(_, w, axes), p = np.linalg.svd(W - W.mean(0), full_matrices=False), np.linalg.svd(P - P.mean(0), compute_uv=False) # the marks' extents along their own axes, widest first
|
||||
if p[1] <= EXACT * p[0]:
|
||||
raise ReferenceFitError("the pixels lie on one line: marks along a line of the image cannot say how the camera is turned about it")
|
||||
if w[1] <= 1e-9 * w[0]:
|
||||
if w[1] <= EXACT * w[0]:
|
||||
raise ReferenceFitError("the world points lie on one line: the camera could stand anywhere round it")
|
||||
if w[2] <= 1e-9 * w[0] and not plane_will_do:
|
||||
raise ReferenceFitError("the world points lie in one plane, which does not decide the lens or the centre: mark a point off the plane, or hold `lens` and name a model other than free")
|
||||
if w[2] > EXACT * w[0]:
|
||||
return None
|
||||
if model == "free":
|
||||
raise ReferenceFitError("the world points lie in one plane, which does not decide the centre: mark a point off the plane, or name a model other than free")
|
||||
if not lens_held and _square_on((W - W.mean(0)) @ axes[:2].T, P) <= EXACT:
|
||||
raise ReferenceFitError("the world points lie in one plane seen square-on, which may not decide the lens: every lens draws them so from its own distance. "
|
||||
"Mark a point off the plane, or hold `lens`")
|
||||
return axes[2]
|
||||
|
||||
|
||||
def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)):
|
||||
|
|
@ -245,11 +266,16 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.
|
|||
"lens_at_bound" (None, or "short" or "long" when the solve stopped at an end of LENS_MM), "rms", "median"
|
||||
(pixels), "worst" [name, pixels], "left_out" (the leave-one-out rms), "model", "tried" {model: rms, left_out,
|
||||
lens}, "azimuth", "elevation" (degrees: where the camera stands round the points' middle), "distance", "roll",
|
||||
"twist" (degrees), "residuals" {name: [du, dv]}}. Every number in it is finite.
|
||||
"twist" (degrees), "plane" (None, or when the world points all lie in one plane the degrees between the line
|
||||
of sight and square-on to it), "residuals" {name: [du, dv]}}. Every number in it is finite.
|
||||
|
||||
World points in one plane may not decide the lens: seen obliquely they do, by the plane's foreshortening; the
|
||||
nearer square-on, the less, and the band says how little (a headline lens then sits anywhere in it, often at
|
||||
an end of LENS_MM). The centre they never decide, so "auto" leaves "free" untried.
|
||||
|
||||
Refuses with ReferenceFitError, before solving, what cannot decide a camera: fewer than six shared names, or
|
||||
fewer than six different world points or different pixels among them; pixels on one line; world points on one
|
||||
line; world points in one plane, unless `lens` is held and the model is upright, rolled or square."""
|
||||
line; world points in one plane with the model "free", or seen exactly square-on with no `lens` held."""
|
||||
if model != "auto" and model not in MODELS:
|
||||
raise ReferenceFitError(f"unknown model {model!r}: one of auto, {', '.join(MODELS)}")
|
||||
box = [float(v) for v in box]
|
||||
|
|
@ -265,13 +291,13 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.
|
|||
if len(world[k]) != 3 or len(pixels[k]) != 2 or not all(math.isfinite(v) for v in (*world[k], *pixels[k])):
|
||||
raise ReferenceFitError(f"point {k!r} is not three finite world numbers and two finite pixel numbers: {list(world[k])}, {list(pixels[k])}")
|
||||
W, P = np.array([world[k] for k in names], float), np.array([pixels[k] for k in names], float)
|
||||
_decidable(names, W, P, lens is not None and model not in ("auto", "free"))
|
||||
normal = _decidable(names, W, P, model, lens is not None)
|
||||
T = np.array([k in turned for k in names])
|
||||
c0 = [(box[0] + box[2]) / 2, (box[1] + box[3]) / 2]
|
||||
logf = (math.log(LENS_MM[0] * width / SENSOR), math.log(LENS_MM[1] * width / SENSOR))
|
||||
fixed = None if lens is None else lens * width / SENSOR
|
||||
tried = {}
|
||||
for m in (("upright", "rolled", "free") if model == "auto" else (model,)):
|
||||
for m in ((("upright", "rolled", "free") if normal is None else ("upright", "rolled")) if model == "auto" else (model,)):
|
||||
rms, p, cam, X, angle = _fit(W, P, c0, m, logf, f_fixed=fixed, turned=T, pivot=pivot)
|
||||
tried[m] = (rms, p, cam, X, angle, _left_out(W, P, c0, m, logf, fixed, p, T, pivot))
|
||||
kind = min(tried, key=lambda k: tried[k][5])
|
||||
|
|
@ -302,6 +328,7 @@ def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.
|
|||
"left_out": left, "model": kind, "tried": {k: {"rms": float(v[0]), "left_out": v[5], "lens": float(mm(v[2]["f"]))} for k, v in tried.items()},
|
||||
"azimuth": float(math.degrees(math.atan2(-off[0], off[1]))), "elevation": float(math.degrees(math.atan2(off[2], math.hypot(off[0], off[1])))),
|
||||
"distance": float(np.linalg.norm(off)), "roll": float(math.degrees(p[5])) if "roll" in MODELS[kind] else 0.0, "twist": float(math.degrees(angle)),
|
||||
"plane": None if normal is None else float(math.degrees(math.acos(min(1.0, abs(float(cam["R"][2] @ normal)))))),
|
||||
"residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}}
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ tolerances round a known truth that no mutant claims. The mutants, each run once
|
|||
M6 the turned group is not turned test_a_turned_torso_is_recovered_as_twist
|
||||
M7 square holds the yaw along y only test_square_solves_elevations_along_both_axes
|
||||
M13 the walk stops after 20 steps each way test_a_wide_band_is_walked_to_its_end
|
||||
G10, G01 core.EXACT ten times looser, ten tighter test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
|
@ -211,31 +212,85 @@ class SolveTests(unittest.TestCase):
|
|||
self.assertTrue(issubclass(core.ReferenceFitError, ValueError))
|
||||
|
||||
def test_marks_that_decide_no_camera_are_refused(self):
|
||||
"""refusals: marks with no extent, in a line or in a plane are refused by which they are before any solve
|
||||
(one pixel for every name was a bare ValueError, one world point a record of NaN). A plane is enough once
|
||||
the lens is held and the centre is not solved."""
|
||||
"""refusals: marks with no extent or in a line, a plane asked for its centre and a plane seen square-on
|
||||
with no lens held are refused by which they are before any solve (one pixel for every name was a bare
|
||||
ValueError, one world point a record of NaN)."""
|
||||
solved, lm = [], core.lm
|
||||
core.lm = lambda *args, **kwargs: solved.append(1) or lm(*args, **kwargs)
|
||||
self.addCleanup(setattr, core, "lm", lm)
|
||||
plane = np.c_[self.points[:, :2], np.zeros(13)]
|
||||
on_plane = dict(zip(NAMES, plane.tolist())), dict(zip(NAMES, core.project(self.oblique, plane).tolist()))
|
||||
square_on = on_plane[0], dict(zip(NAMES, core.project(camera(plane, 35, 90, 50), plane).tolist()))
|
||||
line = dict(zip(NAMES, np.outer(np.arange(13.0), [1.0, 2.0, 0.5]).tolist()))
|
||||
cases = (((self.world, {k: [500.0, 400.0] for k in NAMES}), {}, "1 different pixels"),
|
||||
(({k: [1.0, 2.0, 3.0] for k in NAMES}, self.pixels), {}, "1 different world points"),
|
||||
((self.world, {**self.pixels, **{k: self.pixels["p0"] for k in NAMES[:9]}}), {}, "5 different pixels are marked; six are needed ('p0' and 'p1'"),
|
||||
((self.world, {k: [100.0 + 10 * i, 200.0 + 5 * i] for i, k in enumerate(NAMES)}), {}, "pixels lie on one line"),
|
||||
((line, self.pixels), {}, "world points lie on one line"),
|
||||
(on_plane, {}, "one plane"), (on_plane, {"model": "upright"}, "one plane"), (on_plane, {"model": "free", "lens": 50.0}, "one plane"))
|
||||
(on_plane, {"model": "free"}, "one plane, which does not decide the centre"), (on_plane, {"model": "free", "lens": 50.0}, "does not decide the centre"),
|
||||
(square_on, {}, "seen square-on, which may not decide the lens"), (square_on, {"model": "upright"}, "may not decide the lens"),
|
||||
(square_on, {"model": "square"}, "may not decide the lens"))
|
||||
for args, kwargs, said in cases:
|
||||
with self.assertRaises(core.ReferenceFitError) as caught:
|
||||
core.solve(*args, BOX, **kwargs)
|
||||
self.assertIn(said, str(caught.exception))
|
||||
self.assertEqual(solved, [])
|
||||
held = core.solve(*on_plane, BOX, model="upright", lens=50.0)
|
||||
held = core.solve(*square_on, BOX, model="upright", lens=50.0) # with the lens held a plane decides the rest, square-on too
|
||||
self.assertLess(held["rms"], 1e-3)
|
||||
self.assertAlmostEqual(held["azimuth"], 35.0, delta=0.01)
|
||||
self.assertAlmostEqual(held["elevation"], 90.0, delta=0.01)
|
||||
self.assertAlmostEqual(held["plane"], 0.0, delta=0.01)
|
||||
self.assertNotIn("NaN", json.dumps(held))
|
||||
|
||||
def test_a_plane_seen_obliquely_decides_the_lens_and_says_it_is_a_plane(self):
|
||||
"""plane-honest: world points in one plane are solved, not refused: the plane's foreshortening decides the
|
||||
lens (Zhang's calibration from a plane), "plane" says how far from square-on the view is, and auto leaves
|
||||
the free model untried, since a plane never decides the centre. Seen within a pixel's noise of square-on
|
||||
the marks decide no lens, and the record says so by its band rather than by a refusal: the headline lens
|
||||
sits at an end of the range."""
|
||||
plane = np.c_[self.points[:, :2], np.zeros(13)]
|
||||
world = dict(zip(NAMES, plane.tolist()))
|
||||
solved = core.solve(world, dict(zip(NAMES, core.project(self.oblique, plane).tolist())), BOX)
|
||||
self.assertAlmostEqual(solved["lens"], 50.0, delta=0.01)
|
||||
self.assertAlmostEqual(solved["plane"], 70.0, delta=0.01)
|
||||
self.assertEqual(sorted(solved["tried"]), ["rolled", "upright"])
|
||||
self.assertLess(place_error(solved, self.oblique), 1e-3)
|
||||
self.assertIsNone(self.auto["plane"])
|
||||
noisy = core.project(camera(plane, 35, 90, 50), plane) + np.random.default_rng(5).normal(0, 1.0, (13, 2))
|
||||
open_ = core.solve(world, dict(zip(NAMES, noisy.tolist())), BOX, model="upright")
|
||||
self.assertEqual((open_["lens_band"], open_["lens_at_bound"]), ([4.0, 4000.0], "short"))
|
||||
self.assertLess(open_["plane"], 0.1)
|
||||
self.assertNotIn("NaN", json.dumps(open_))
|
||||
|
||||
def test_the_exact_gates_sit_at_a_billionth_of_the_marks_extent(self):
|
||||
"""exact-gate: each of _decidable's four tests reads a ratio (the marks' thinnest extent over their widest,
|
||||
or their misfit to a square-on copy of their plane) against core.EXACT, 1e-9. Marks at 3.16e-10 are refused
|
||||
and marks at 3.16e-9 pass: the geometric means of the shipped gate with a gate ten times tighter and ten
|
||||
times looser, the least mutants claimed (separation 3.16 each side)."""
|
||||
r = np.random.default_rng(7)
|
||||
bump = r.normal(0, 1, 13)
|
||||
plane = np.c_[self.points[:, :2], np.zeros(13)]
|
||||
line = np.outer(np.linspace(-2, 2, 13), [1.0, 2.0, 0.5])
|
||||
across = np.cross([1.0, 2.0, 0.5], [0.0, 0.0, 1.0])
|
||||
flat_px, slope = np.c_[np.linspace(200, 900, 13), np.linspace(300, 500, 13)], np.array([-200.0, 700.0])
|
||||
turned = self.points[:, :2] @ np.array([[120.0, -90.0], [-90.0, -120.0]]) + [600.0, 400.0] # the plane's own picture, turned, scaled and v down
|
||||
thin = lambda A: (lambda s: s[-1] / s[0])(np.linalg.svd(A - A.mean(0), compute_uv=False)) # noqa: E731
|
||||
misfit = lambda P: core._square_on(plane[:, :2] - plane[:, :2].mean(0), P) # noqa: E731
|
||||
sites = (("pixels lie on one line", lambda t: (self.points, flat_px + t * np.outer(bump, slope)), lambda W, P: thin(P), {}),
|
||||
("world points lie on one line", lambda t: (line + t * np.outer(bump, across), np.array(list(self.pixels.values()))), lambda W, P: (lambda s: s[1] / s[0])(np.linalg.svd(W - W.mean(0), compute_uv=False)), {}),
|
||||
("does not decide the centre", lambda t: (plane + t * np.outer(bump, [0.0, 0.0, 1.0]), np.array(list(self.pixels.values()))), lambda W, P: thin(W), {"model": "free"}),
|
||||
("seen square-on", lambda t: (plane, turned + t * np.c_[bump, bump[::-1]]), lambda W, P: misfit(P), {"model": "upright"}))
|
||||
for said, make, reading, how in sites:
|
||||
unit = reading(*make(1e-6)) / 1e-6 # the reading is the offset's size times this, the offset being small
|
||||
for at, refused in ((3.16e-10, True), (3.16e-9, False)):
|
||||
W, P = make(at / unit)
|
||||
self.assertAlmostEqual(reading(W, P) / at, 1.0, delta=0.01, msg=said)
|
||||
try:
|
||||
core._decidable(NAMES, W, P, how.get("model", "auto"), False)
|
||||
self.assertFalse(refused, f"{said}: marks at {at:g} passed")
|
||||
except core.ReferenceFitError as refusal:
|
||||
self.assertTrue(refused, f"{said}: marks at {at:g} were refused: {refusal}")
|
||||
self.assertIn(said, str(refusal))
|
||||
|
||||
|
||||
def crease(n=2000):
|
||||
"""A crease of a part in its frame, x > 0: a bowed line 2 m long, as dense as a line drawn with a ruler."""
|
||||
|
|
|
|||
Loading…
Reference in a new issue