brokkr_reference: a reference view's camera solved from marked points (cut reference-camera) #35

Merged
eureka merged 7 commits from nibu/reference-camera into main 2026-12-02 19:07:57 +00:00
7 changed files with 1335 additions and 0 deletions

View file

@ -0,0 +1,90 @@
"""Fit a scene to a reference image: the camera a reference view was drawn through, solved from marked points.
A host add-on for Brokkr beside brokkr_mesh_polish (it imports that package's operator base, and nothing from
Brokkr): brokkr_actions.json beside this file lists the operators agents may run (docs/reference.md). The
arithmetic is core.py (numpy, tested without Blender); this file is the bpy around it. Every operator writes a
JSON report to WindowManager.brokkr_mesh_polish_result, as the polish operators do.
The camera record core.solve returns is the truth; a Blender camera stood at it is derived by core.blender, and
core.camera_of reads one back. The images, traces and masks a view is marked on stay with whoever marked them:
this package takes points and gives cameras.
"""
bl_info = {"name": "Brokkr Reference", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
"category": "Camera", "description": "Solve a reference view's camera from marked points; agent-callable through Brokkr."}
import bpy
from mathutils import Matrix
try:
from brokkr_mesh_polish import RESULT, PolishOperator, Refused
MISSING = None
except ImportError as error: # register() says so; the class below only needs something to subclass
RESULT, PolishOperator, Refused, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, error
from . import core
def stand(scene, name, cam, width):
"""Create or update the camera object `name` at a camera record, the frame being the record's box at `width`
pixels across, and set the scene's render size to that frame: a pixel of the render is then the image's pixel
less the box's corner, times width over the box's width (core.in_frame). Returns core.blender's params."""
params = core.blender(cam, width)
obj = bpy.data.objects.get(name)
if obj is None:
obj = bpy.data.objects.new(name, bpy.data.cameras.new(name))
scene.collection.objects.link(obj)
data = obj.data
data.type, data.sensor_fit, data.sensor_width = "PERSP", params["sensor_fit"], params["sensor_width"]
data.lens, data.shift_x, data.shift_y = params["lens"], params["shift_x"], params["shift_y"]
data.clip_end = max(data.clip_end, 4 * cam["distance"])
obj.matrix_world = Matrix(params["matrix_world"])
scene.render.resolution_x, scene.render.resolution_y = params["resolution"]
return params
class BROKKR_REFERENCE_OT_solve_camera(PolishOperator):
"""Solve the camera a reference view was drawn through from points known in the world and marked on the
image, and optionally stand a scene camera there"""
bl_idname = "brokkr_reference.solve_camera"
bl_label = "Solve Reference Camera"
world: bpy.props.StringProperty(name="World", maxlen=4000, description="name=x,y,z; name=x,y,z ... points in the world, metres")
pixels: bpy.props.StringProperty(name="Pixels", maxlen=4000, description="name=u,v; name=u,v ... where the image draws each, v down; six or more names shared with World")
box: bpy.props.StringProperty(name="Box", maxlen=120, description="u0,v0,u1,v1: the view's box on the image, in the pixels the points were marked in")
model: bpy.props.EnumProperty(name="Model", default="auto", description="What the camera may do beyond standing, turning and zooming",
items=[("auto", "Auto", "Upright, rolled or free, whichever predicts left-out points best"),
("upright", "Upright", "Level, its centre at the middle of the box"), ("rolled", "Rolled", "May roll about its line of sight"),
("free", "Free", "May roll, and its centre is solved (a view cropped off-axis)"),
("square", "Square", "Looks straight along a world axis: an elevation drawn from far off")])
lens: bpy.props.FloatProperty(name="Lens", default=0.0, min=0.0, max=4000.0, description="mm on a 36 mm sensor across the box; 0 solves it. Hold it for a view that must agree with another")
turned: bpy.props.StringProperty(name="Turned", maxlen=2000, description="Names, spaces between, of points that turn as one about the vertical through Pivot; the angle is solved")
pivot: bpy.props.StringProperty(name="Pivot", maxlen=80, description="x,y of that vertical; empty is 0,0")
camera_name: bpy.props.StringProperty(name="Camera", maxlen=63, description="A camera object to create or update at the solved camera, with the scene's render size; empty only computes")
width: bpy.props.IntProperty(name="Width", default=1000, min=16, max=16384, description="Pixels across the frame the box becomes")
def work(self, context):
if self.camera_name and getattr(bpy.data.objects.get(self.camera_name), "type", "CAMERA") != "CAMERA":
raise Refused(f"{self.camera_name!r} is an object that is not a camera.")
try:
cam = core.solve(core.points(self.world, 3, "world"), core.points(self.pixels, 2, "pixels"), core.numbers(self.box, 4, "box"), model=self.model,
lens=self.lens or None, turned=tuple(self.turned.split()), pivot=core.numbers(self.pivot, 2, "pivot") if self.pivot.strip() else (0.0, 0.0))
except core.ReferenceFitError as refusal:
raise Refused(str(refusal)) from None
report = {**cam, "residuals": {k: [round(v, 2) for v in r] for k, r in cam["residuals"].items()}, "camera": None} # hundredths of a pixel: 280 points still fit a receipt
if self.camera_name:
report.update(camera=self.camera_name, blender=stand(context.scene, self.camera_name, cam, self.width))
return report
classes = (BROKKR_REFERENCE_OT_solve_camera,)
def register():
if MISSING is not None or not hasattr(bpy.types.WindowManager, RESULT):
raise RuntimeError(f"brokkr_reference needs brokkr_mesh_polish enabled first ({MISSING or 'its result property is not registered'}).")
for cls in classes:
bpy.utils.register_class(cls)
def unregister():
for cls in reversed(classes):
bpy.utils.unregister_class(cls)

View file

@ -0,0 +1,85 @@
{
"schema": "brokkr.blender.host_actions.v0",
"actions": [
{
"name": "brokkr_reference.solve_camera",
"doc": "Solve the camera a reference view was drawn through from six or more points known in the world and marked on the image; with camera_name, stand a camera there and set the render size to the view's box. The result is the camera record (docs/reference.md).",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "world",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 4000,
"doc": "name=x,y,z; name=x,y,z ... points in the world: x right, y forward, z up, metres"
},
{
"name": "pixels",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 4000,
"doc": "name=u,v; name=u,v ... where the image draws each, v down; six or more names shared with world"
},
{
"name": "box",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 120,
"doc": "u0,v0,u1,v1: the view's box on the image, in the pixels the points were marked in"
},
{
"name": "model",
"type": "string",
"enum": [
"auto",
"upright",
"rolled",
"free",
"square"
],
"default": "auto",
"doc": "auto takes upright, rolled or free by leave-one-out error; square looks straight along a world axis (an elevation)"
},
{
"name": "lens",
"type": "number",
"minimum": 0,
"maximum": 4000,
"default": 0,
"doc": "mm on a 36 mm sensor across the box; 0 solves it, 4 to 4000 holds it (a view that must agree with another)"
},
{
"name": "turned",
"type": "string",
"maxLength": 2000,
"doc": "names, spaces between, of points that turn as one about the vertical through pivot; the angle is solved as twist"
},
{
"name": "pivot",
"type": "string",
"maxLength": 80,
"doc": "x,y of that vertical; absent is 0,0"
},
{
"name": "camera_name",
"type": "string",
"maxLength": 63,
"doc": "a camera object to create or update at the solved camera; absent only computes"
},
{
"name": "width",
"type": "integer",
"minimum": 16,
"maximum": 16384,
"default": 1000,
"doc": "pixels across the frame the box becomes when camera_name is given"
}
]
}
]
}

View file

@ -0,0 +1,362 @@
"""The camera of a reference view, solved from marked points. numpy and the standard library; no Blender.
A reference image (a concept sheet, a render, a photograph) draws a view through some camera nobody wrote down.
Given points whose place in the world is known (a build's joints, sockets or vertices) and the pixel where the
image draws each, solve() finds the pinhole camera that draws them there: where it stands, how it is turned and
its focal length, all at once (PnP with the focal length unknown), by Levenberg-Marquardt from a grid of starts
round the points. docs/reference.md says what the answer is worth; in short, six or more points not all in one
plane decide the camera, and a long or square-on view decides everything but how far off it stands: distance and
focal length trade against each other (a dolly zoom), and "lens_band" says how far.
world x right, y forward, z up, metres
pixels the image's, in whatever unit the points were marked in; v down
camera looks down its own -z, y up (Blender's); "R" turns world to camera; "f" is in pixels; "c" is the
principal point, at the middle of the view's box unless the model solves it (MODELS)
misses are weighed by a pseudo-Huber loss (SOFT pixels): a build poses some points elsewhere than the image
draws them, and those should not turn the camera
lens millimetres on a SENSOR mm sensor across the box's width, held inside LENS_MM
solve(world, pixels, box, model="auto") the camera record, a dict that goes to JSON
project(cam, points) pixels of world points
ray(cam, pixel) (origin, unit direction) of a pixel's line of sight, in the world
lift(cam, pixel, plane_point, plane_normal) where that line of sight meets a plane: a traced 2D point made 3D
blender(cam, width) what a Blender camera takes to be this one, the frame being the box
camera_of(params, box) the record of a Blender camera: blender() read back
in_frame(cam, pixels, width) image pixels as pixels of the frame blender() renders
points(text, size), numbers(text, count) the action's string fields
"""
from __future__ import annotations
import math
import numpy as np
SOFT = 10.0 # pixels: about the error of a point marked by hand; a point the build poses elsewhere misses by several times that
SENSOR = 36.0 # mm, fitted to the box's width
LENS_MM = (4.0, 4000.0) # the focal length never leaves this: past 4000 mm a view is orthographic to any marking, and an unbounded solve runs off (docs/reference.md)
BAND = 1.1 # lens_band: the lenses whose refitted rms is within this multiple of the best
STEP = 0.1 # the band is walked in steps of this in log f
MODELS = {"upright": (), "rolled": ("roll",), "free": ("roll", "centre"), "square": ("square",)} # what a model solves beyond place, yaw, pitch and focal length; "square" holds the yaw at a quarter turn instead
QUARTER = math.pi / 2
class ReferenceFitError(ValueError):
"""solve() or a field parser cannot take what it was given; the message names which."""
def _rotation(yaw, pitch, roll):
"""World to camera for a camera whose line of sight is turned `yaw` about the world's z from looking along +y,
pitched up by `pitch`, and rolled about its line of sight."""
cy, sy, cp, sp, cr, sr = math.cos(yaw), math.sin(yaw), math.cos(pitch), math.sin(pitch), math.cos(roll), math.sin(roll)
look = np.array([-sy * cp, cy * cp, sp])
right = np.array([cy, sy, 0.0])
up = np.array([sy * sp, -cy * sp, cp]) # right x look
r, u = cr * right + sr * up, -sr * right + cr * up
return np.stack([r, u, -look])
def project(cam, points):
"""Pixels (n, 2) of world points (n, 3). A point behind the camera comes back far off the frame."""
q = (np.asarray(points, float) - np.asarray(cam["C"], float)) @ np.asarray(cam["R"], float).T
z = np.where(q[:, 2] < -1e-6, -q[:, 2], 1e-6)
return np.stack([cam["c"][0] + cam["f"] * q[:, 0] / z, cam["c"][1] - cam["f"] * q[:, 1] / z], 1)
def ray(cam, pixel):
d = np.array([(pixel[0] - cam["c"][0]) / cam["f"], -(pixel[1] - cam["c"][1]) / cam["f"], -1.0]) @ np.asarray(cam["R"], float)
return np.asarray(cam["C"], float), d / np.linalg.norm(d)
def lift(cam, pixel, plane_point, plane_normal):
o, d = ray(cam, pixel)
n = np.asarray(plane_normal, float)
return o + d * (((np.asarray(plane_point, float) - o) @ n) / (d @ n))
def lm(residual, p, low=None, high=None, rounds=80):
"""Levenberg-Marquardt on a residual function, its Jacobian by differences. `low` and `high` (per parameter,
infinite where free) are bounds: a step is clipped to them, a difference that would cross one is taken the
other way, and a parameter held against one is left out of the step. Returns (p, residual)."""
p = np.array(p, float)
low = np.full(len(p), -np.inf) if low is None else np.asarray(low, float)
high = np.full(len(p), np.inf) if high is None else np.asarray(high, float)
p = np.clip(p, low, high)
r = residual(p)
lam = 1e-3
for _ in range(rounds):
J = np.empty((len(r), len(p)))
for k in range(len(p)):
h = 1e-6 * max(1.0, abs(p[k]))
if p[k] + h > high[k]:
h = -h
q = p.copy()
q[k] += h
J[:, k] = (residual(q) - r) / h
J[:, ((p <= low) & (J.T @ r > 0)) | ((p >= high) & (J.T @ r < 0))] = 0.0 # a parameter at its bound and pulled past it sits this round out, so the others take their own step
A, g = J.T @ J, J.T @ r
for _ in range(12):
try:
step = np.linalg.solve(A + lam * np.diag(np.diag(A) + 1e-12), -g)
except np.linalg.LinAlgError:
lam *= 10
continue
q = np.clip(p + step, low, high)
r2 = residual(q)
if r2 @ r2 < r @ r:
gain = (r @ r - r2 @ r2) / max(r @ r, 1e-30)
p, r, lam = q, r2, lam / 3
break
lam *= 4
else:
break
if gain < 1e-12:
break
return p, r
def _turned(W, turned, angle, pivot):
"""W with its `turned` rows turned by `angle` about the vertical through `pivot`."""
X = W.copy()
if turned.any():
c, s = math.cos(angle), math.sin(angle)
d = W[turned, :2] - np.asarray(pivot, float)
X[turned, 0], X[turned, 1] = pivot[0] + c * d[:, 0] - s * d[:, 1], pivot[1] + s * d[:, 0] + c * d[:, 1]
return X
def _fit(W, P, c0, model, logf, f_fixed=None, near=None, turned=None, pivot=(0.0, 0.0), frame=None):
"""The best camera of a model over a grid of starts, or from the one start `near` (the parameter vector of a
solve of nearly the same points): (rms pixels, parameter vector, camera, the points as solved, the turn).
`logf` is (low, high), the bounds of log f. `turned` marks the points that turn together about the vertical
through `pivot` (x, y) by one more unknown angle. The vector is place (3), yaw, pitch, then roll, log f, centre
(2) and the turn, each only when solved. Place is the camera's offset from the points' middle divided by f over
the marks' extent in pixels, so that log f alone is a dolly zoom: the camera backs off as the lens grows and
the picture keeps its size. A long view decides its lens loosely, and with place in metres the solve crawled
along that trade and stopped short of where the error was least. `frame` is the (middle, extent) a `near`
vector was solved in, when its points were not quite these."""
extra = MODELS[model]
turned = np.zeros(len(W), bool) if turned is None else np.asarray(turned, bool)
twist = bool(turned.any())
size = np.ptp(W, axis=0).max()
centre, px = (W.mean(0), np.ptp(P, axis=0).max()) if frame is None else frame
at = 5 + ("roll" in extra) # where log f sits when it is solved
def split(p):
p = list(p)
off, yaw, pitch = np.array(p[:3]), p[3], p[4]
del p[:5]
if "square" in extra:
yaw = QUARTER * round(yaw / QUARTER) # held: a difference of 1e-6 never crosses to the next quarter, so the yaw's column is zero and it stays at its start
roll = p.pop(0) if "roll" in extra else 0.0
f = f_fixed if f_fixed is not None else math.exp(min(max(p.pop(0), logf[0]), logf[1]))
c = [p.pop(0), p.pop(0)] if "centre" in extra else c0
return {"C": centre + off * (f / px), "R": _rotation(yaw, pitch, roll), "f": f, "c": np.array(c, float)}, (p.pop(0) if twist else 0.0)
def residual(p):
cam, angle = split(p)
r = project(cam, _turned(W, turned, angle, pivot)) - P
n = np.maximum(np.hypot(r[:, 0], r[:, 1]), 1e-9) # pseudo-Huber: a miss far past SOFT pixels pulls as its distance, not its square
return (r * (np.sqrt(2 * SOFT * SOFT * (np.sqrt(1 + (n / SOFT) ** 2) - 1)) / n)[:, None]).ravel()
starts = []
if near is not None:
starts.append(near)
else:
for az in (range(0, 360, 90) if "square" in extra else range(-180, 180, 45)):
for dist in (1.5, 6.0):
a = math.radians(az)
d = dist * size
starts.append([-size * math.sin(a), size * math.cos(a), 0.0, a + math.pi, 0.0] + [0.0] * ("roll" in extra)
+ ([] if f_fixed is not None else [math.log(px * d / size)]) + (list(c0) if "centre" in extra else []) + [0.0] * twist)
low, high = np.full(len(starts[0]), -np.inf), np.full(len(starts[0]), np.inf)
if f_fixed is None:
low[at], high[at] = logf
best = None
for start in starts:
p, r = lm(residual, start, low, high)
if best is None or r @ r < best[0] - 1e-9:
best = (float(r @ r), p)
cam, angle = split(best[1])
X = _turned(W, turned, angle, pivot)
miss = project(cam, X) - P
return math.sqrt((miss * miss).sum() / len(W)), best[1], cam, X, angle
def _left_out(W, P, c0, model, logf, f_fixed, near, turned, pivot):
"""Leave-one-out: each point predicted by the camera solved without it; the rms of those misses, pixels."""
miss, frame = [], (W.mean(0), np.ptp(P, axis=0).max())
for k in range(len(W)):
keep = np.arange(len(W)) != k
start = near if turned[keep].any() or not turned.any() else near[:-1]
_, _, cam, _, angle = _fit(W[keep], P[keep], c0, model, logf, f_fixed=f_fixed, near=start, turned=turned[keep], pivot=pivot, frame=frame)
one = _turned(W[k:k + 1], turned[k:k + 1], angle, pivot)
miss.append(np.linalg.norm(project(cam, one)[0] - P[k]))
return float(np.sqrt(np.mean(np.square(miss))))
def _decidable(names, W, P, plane_will_do):
"""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."""
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]:
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]:
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")
def solve(world, pixels, box, model="auto", lens=None, turned=(), pivot=(0.0, 0.0)):
"""world {name: [x, y, z]}, pixels {name: [u, v]}: the camera that draws the names both hold. `box` is the
view's box on the image [u0, v0, u1, v1]. `model` is one of MODELS: "upright" holds the camera level and its
centre at the middle of the box, "rolled" lets it roll, "free" solves the centre too (a view cropped off-axis);
"auto" takes whichever of those predicts left-out points best, since a freer model always fits the marked ones
closer. "square" is for a view drawn square-on from far off (a rear or side elevation): there the points lie
nearly in one plane across the line of sight, a turn of the camera and a narrower figure draw the same picture,
and the solve would spend the turn on the build's error in width; so the camera looks straight along a world
axis, whichever quarter turn fits best. `lens` (mm) holds the focal length instead of solving it: for a view
that must agree with another. `turned` names points that turn as one about the vertical through `pivot` (a
torso on its waist ring): the angle is solved with the camera, and "twist" is how far they turn from where
they were given.
Returns the camera record: {"C", "R", "f", "c", "box", "lens" (mm), "lens_band" [low, high] (the lenses that
refit within BAND of the best rms, walked out from the best in steps of STEP in log f, about 10%, to the first
that misses: an equal-error band, not a confidence interval, and no finer than its step, so [x, x] says the
band is narrower than one step each way, not that the lens is exact),
"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.
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."""
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]
if len(box) != 4 or not all(math.isfinite(v) for v in box) or box[2] - box[0] <= 0 or box[3] - box[1] <= 0:
raise ReferenceFitError(f"box {box} has no {'width' if len(box) != 4 or not box[2] - box[0] > 0 else 'height'}: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0")
width = box[2] - box[0]
if lens is not None and not LENS_MM[0] <= lens <= LENS_MM[1]:
raise ReferenceFitError(f"lens {lens} mm is outside {LENS_MM[0]:g} to {LENS_MM[1]:g} mm")
names = [k for k in pixels if k in world]
if len(names) < 6:
raise ReferenceFitError(f"{len(names)} points are named in both world and pixels; six are needed")
for k in names:
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"))
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,)):
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])
rms, p, cam, X, angle, left = tried[kind]
mm = lambda f: min(max(f * SENSOR / width, LENS_MM[0]), LENS_MM[1]) # noqa: E731 an end of the range reads as exactly that end
span, best = [cam["f"]], math.log(cam["f"])
for way in ((-1, 1) if fixed is None else ()): # walk the lens out each way from the best, each solve started at the last, to the first that misses or to the bound
q, step = np.delete(p, 5 + ("roll" in MODELS[kind])), 1
while True:
at = best + STEP * way * step
f = math.exp(min(max(at, logf[0]), logf[1]))
r_f, q = _fit(W, P, c0, kind, logf, f_fixed=f, near=q, turned=T, pivot=pivot)[:2]
if r_f > BAND * rms + 1e-9:
break
span.append(f)
if not logf[0] < at < logf[1]:
break
step += 1
off = cam["C"] - X.mean(0)
res = project(cam, X) - P
if not (math.isfinite(rms) and math.isfinite(left) and np.isfinite(cam["C"]).all() and np.isfinite(res).all()):
raise ReferenceFitError("the solve did not come to finite numbers: the marks do not decide a camera")
worst = int(np.argmax(np.linalg.norm(res, axis=1)))
edge = None if fixed is not None else "short" if best <= logf[0] + 1e-9 else "long" if best >= logf[1] - 1e-9 else None
return {"C": [float(v) for v in cam["C"]], "R": [[float(v) for v in row] for row in cam["R"]], "f": float(cam["f"]), "c": [float(v) for v in cam["c"]],
"box": box, "lens": float(mm(cam["f"])), "lens_band": [float(mm(min(span))), float(mm(max(span)))], "lens_at_bound": edge,
"rms": float(rms), "median": float(np.median(np.linalg.norm(res, axis=1))), "worst": [names[worst], float(np.linalg.norm(res[worst]))],
"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)),
"residuals": {k: [float(v) for v in r] for k, r in zip(names, res)}}
def blender(cam, width):
"""What a Blender camera takes to be this one, the frame being the view's box at `width` pixels across:
{"matrix_world" (rows), "lens" (mm), "shift_x", "shift_y", "sensor_width", "sensor_fit", "resolution" [w, h]}.
The sensor is SENSOR mm, fitted HORIZONTAL, so both shifts are in widths of the frame."""
R, C = np.asarray(cam["R"], float), np.asarray(cam["C"], float)
M = np.eye(4)
M[:3, :3], M[:3, 3] = R.T, C
u0, v0, u1, v1 = cam["box"]
w, h = u1 - u0, v1 - v0
return {"matrix_world": [[float(v) for v in row] for row in M], "lens": float(cam["f"] * SENSOR / w), "shift_x": float(((u0 + u1) / 2 - cam["c"][0]) / w),
"shift_y": float((cam["c"][1] - (v0 + v1) / 2) / w), "sensor_width": SENSOR, "sensor_fit": "HORIZONTAL", "resolution": [int(width), int(round(width * h / w))]}
def camera_of(params, box=None, width=None):
"""The camera record of a Blender camera, blender() read back: {"C", "R", "f", "c", "box", "lens"}. `params` is
what blender() returns (a scene camera's matrix_world rows, lens, shifts, sensor_width and the render's
resolution; the sensor fit must be HORIZONTAL, which is what AUTO means on a frame wider than tall). `box` is
the frame in the image's pixels; without one it is the frame itself from (0, 0), `width` pixels across (the
render's own width when that is not given either)."""
if params.get("sensor_fit", "HORIZONTAL") != "HORIZONTAL":
raise ReferenceFitError(f"sensor fit {params['sensor_fit']!r}: camera_of reads a HORIZONTAL fit only")
M = np.asarray(params["matrix_world"], float)
if box is None:
rx, ry = params["resolution"]
width = rx if width is None else width
box = [0.0, 0.0, float(width), float(width) * ry / rx]
u0, v0, u1, v1 = (float(v) for v in box)
w = u1 - u0
return {"C": [float(v) for v in M[:3, 3]], "R": [[float(v) for v in row] for row in M[:3, :3].T], "f": float(params["lens"] * w / params.get("sensor_width", SENSOR)),
"c": [float((u0 + u1) / 2 - params["shift_x"] * w), float((v0 + v1) / 2 + params["shift_y"] * w)], "box": [u0, v0, u1, v1], "lens": float(params["lens"] * SENSOR / params.get("sensor_width", SENSOR))}
def in_frame(cam, pixels, width):
"""Image pixels as pixels of the frame blender() renders at `width`. The frame's height is a whole number of
pixels, so it stands up to half a pixel taller or shorter than the box about the same middle."""
u0, v0, u1, v1 = cam["box"]
k = width / (u1 - u0)
return (np.asarray(pixels, float) - np.array([u0, v0], float)) * k + np.array([0.0, (round(k * (v1 - v0)) - k * (v1 - v0)) / 2])
def numbers(text, count, what):
"""'1, 2.5, 3' as `count` finite floats; ReferenceFitError names `what`."""
try:
values = [float(v) for v in text.split(",")]
except ValueError:
values = []
if len(values) != count or not all(math.isfinite(v) for v in values):
raise ReferenceFitError(f"{what} {text.strip()!r} is not {count} finite numbers with commas between")
return values
def points(text, size, what):
"""'a=1,2,3; b=4,5,6' as {name: [numbers]}, each of `size` numbers; ReferenceFitError names `what` and the entry.
A name given twice is refused: which of the two was meant is not this parser's to choose."""
out = {}
for entry in (piece.strip() for piece in text.split(";")):
if not entry:
continue
name, _, values = entry.partition("=")
name = name.strip()
if not name:
raise ReferenceFitError(f"{what} entry {entry!r} has no name")
if name in out:
raise ReferenceFitError(f"{what} names {name!r} twice")
out[name] = numbers(values, size, f"{what} point {name!r}:")
return out

View file

@ -0,0 +1,130 @@
# Reference views: the camera a picture was drawn through
`surfaces/blender/brokkr_reference` is a Blender add-on that fits a scene to a reference image. A concept sheet,
a render or a photograph draws its subject through a camera nobody wrote down; given points whose place in the
world is known and the pixel where the image draws each, `solve_camera` finds that camera, so that a render through
it lays over the image pixel for pixel and a line traced on the image can be lifted into the scene.
It is a host add-on in Brokkr's sense (`install.md`, "Host add-on actions"), a sibling of `brokkr_mesh_polish`: it
imports that package's operator base and `Refused`, and nothing from `brokkr_bridge`. Enable `brokkr_mesh_polish`
first; `brokkr_reference` refuses to register without it. `brokkr_actions.json` beside its `__init__.py` lists the
one operator agents may run; the arithmetic is `core.py` (numpy only, tested without Blender), which a script may
import directly. The action writes its JSON report to `brokkr_mesh_polish_result`, returned in the receipt's
`hostResult`.
The package takes points and gives cameras. The images, the marks on them, traces and masks belong to whoever
made them; nothing here opens an image.
## Conventions
- World: x right, y forward, z up, metres.
- Pixels: the image's, in whatever unit the points were marked in, u right and v down. `box` is the view's
rectangle on the image, `u0,v0,u1,v1`; for an image that is one view it is `0,0,width,height`.
- Camera record: `C` is where the camera stands, `R` turns world to camera (rows), the camera looks down its own
-z with y up (Blender's), `f` is the focal length in pixels, `c` the principal point in pixels. `lens` is `f`
in millimetres on a 36 mm sensor across the box's width.
- Misses are weighed by a pseudo-Huber loss of 10 px: a build poses some points elsewhere than the image draws
them, and one such point pulls the camera as its distance, not its square.
The record is the truth. A Blender camera stood at it (`core.blender`) is derived, and `core.camera_of` reads one
back into a record.
## The action
`brokkr_reference.solve_camera`. Host action fields are scalar, so points go in as text:
| field | |
| --- | --- |
| `world` | `name=x,y,z; name=x,y,z ...` |
| `pixels` | `name=u,v; name=u,v ...`; six or more names shared with `world`, the rest ignored |
| `box` | `u0,v0,u1,v1` |
| `model` | `auto` (default), `upright`, `rolled`, `free`, `square` |
| `lens` | mm; 0 (default) solves it, 4 to 4000 holds it |
| `turned` | names, spaces between, of points that turn as one about the vertical through `pivot` |
| `pivot` | `x,y`; absent is `0,0` |
| `camera_name` | a camera object to create or update at the solved camera; absent only computes |
| `width` | pixels across the frame the box becomes (default 1000) |
The models differ in what the camera may do beyond standing somewhere, turning and zooming. `upright` holds it
level with its centre at the middle of the box. `rolled` lets it roll about its line of sight. `free` also solves
the centre: a view cropped off-axis. `auto` solves all three and takes the one that predicts left-out points best
(each point predicted by the camera solved without it), since a freer model always fits the marked points closer.
`square` is for an elevation drawn square-on from far off: the points lie nearly in one plane across the line of
sight, where a small turn of the camera and a narrower subject draw the same picture, so the camera is held looking
straight along a world axis, whichever of the four fits best.
`turned` is for one articulated group (a torso on its waist ring): its turn about the vertical through `pivot` is
solved with the camera and reported as `twist`, in degrees from where the points were given.
With `camera_name` the action creates that camera, or updates it if it exists (an object of that name that is not
a camera is refused): its matrix, lens, shifts, a 36 mm sensor fitted horizontally, `clip_end` raised to four
times the camera's distance if it was nearer, and the scene's render resolution set to `width` by the box's
proportion. It does not make it the scene's active camera and does not touch `resolution_percentage`. A pixel of a
render through it at 100% is then the image's pixel less the box's corner, times `width` over the box's width
(`core.in_frame`; the frame's height is a whole number of pixels, so it can stand half a pixel off the box's).
The report is the camera record: `C`, `R`, `f`, `c`, `box`, `lens`, `lens_band`, `lens_at_bound`, `rms`, `median`
and `worst` (`[name, pixels]`), `left_out` (the leave-one-out rms), `model`, `tried` (each model's `rms`,
`left_out` and `lens`), `azimuth`, `elevation` and `distance` (where the camera stands round the points' middle),
`roll`, `twist`, and `residuals` (`{name: [du, dv]}`, to a hundredth of a pixel in a receipt); plus `camera` (the
object's name or null) and, when a camera was stood, `blender` (what `core.blender` gave it).
Refusals name their cause: fewer than six shared names, a point that is not finite numbers, a name given twice, a
box of no width or height, a lens outside 4 to 4000 mm. Marks that cannot decide a camera are refused before any
solve: fewer than six different world points or six different pixels among the shared names (the message names two
that share one), pixels all on one line, world points all on one line, and world points all in one plane unless
`lens` is held and the model is `upright`, `rolled` or `square`. These are exact cases; points nearly in a line or
a plane are solved, and the band says what they leave open. A report never holds a number that is not finite.
## How far to trust the lens
Six or more points that are not all in one plane decide a camera. What they decide well is the picture: where each
point is drawn. What a long or square-on view decides badly is how far off the camera stands, because distance
and focal length trade against each other (a dolly zoom) and the picture barely changes. So:
- The focal length is held inside 4 to 4000 mm. Without a bound the solve ran the focal length to overflow on long
views; past 4000 mm a view is orthographic to any marking. `lens_at_bound` is `"long"` or `"short"` when the
answer sits at an end: read that as "at least this long", not as a lens.
- `lens_band` is `[low, high]`: the lenses that, held and refitted, come within 1.1 times the best rms, walked out
from the best in steps of a tenth in log f until one misses or the bound is reached. It is an **equal-error
band, not a confidence interval**: it says which lenses the marks cannot tell apart, not where the true lens
lies, and on a probe one such band excluded the true lens. A band that ends at 4000 was stopped by the bound.
The walk's step is the band's resolution: each end is the last step that still fitted, so the true end lies up
to one step (about 10%) further out, and a band of `[x, x]` means the first step each way already missed, that
is, a band narrower than one 10% step each way, not a lens known exactly.
- There is no prior. Where the data cannot decide, the answer is a wide band rather than a plausible-looking 50 mm.
- Hold `lens` only when views must agree: two views of one subject solved alone may each sit anywhere in their
bands, and a fit rendered from elsewhere than the reference view depends on the lens the band does not fix.
What this buys and costs, measured on a generated hull rendered at known cameras with 10 to 16 marked points
(Blender 5.3 on Starfire): a 50 mm oblique view with 1 px of marking noise came back at 49.9 mm; a 135 mm view on a
build 2% of its length out came back anywhere from 94 mm to the bound, with the camera's place off by eleven hull
lengths, and a crease lifted through that camera onto the hull's mirror plane was still within 1.4% of the hull's
length of the truth, moving at most 0.6% between the band's ends. A wide band is a warning about the camera's
place, not about a lift made in the view's own frame.
`rms` is the plain root mean square of the misses, in pixels at the marking unit, though the solve minimises the
pseudo-Huber loss; `median` beside it shows when a few points carry the error. A solve with `auto` on 13 points
takes several seconds (three models, each from 16 starts, plus a left-out solve per point per model).
## What it cannot do
It solves one pinhole camera for one view: no lens distortion, no two views solved together, one turned group and
no other pose. It does not find the points; marking them is the caller's. Points on posed joints fit worse than
points on rigid features of one body, because the build's pose is not the drawing's. It does not say whether the
subject is the right size: a build twice too large is the same picture from twice as far.
## From a script
```python
from brokkr_reference import core
cam = core.solve(world, pixels, box, model="auto") # dicts by name; the record
u_v = core.project(cam, points) # where it draws world points
origin, direction = core.ray(cam, (u, v)) # a pixel's line of sight
point = core.lift(cam, (u, v), plane_point, plane_normal) # a traced pixel on a plane
params = core.blender(cam, 1000) # matrix_world, lens, shifts, resolution
cam2 = core.camera_of(params, box) # and back
```
The tests are `tests/test_reference.py` (no Blender) and `tests/live/reference.py` (a known scene rendered,
solved through the action and rendered again; `reference.result.json` is its last run).

View file

@ -0,0 +1,183 @@
"""Live proof, in a background Blender, that the brokkr_reference row is admitted by Brokkr as a host action and
that solve_camera, through run_intent, finds the camera a known scene was rendered through: three boxes rendered
at a 50 mm camera cropped off-axis, their corners marked where Blender's own projection draws them (to a tenth of
a pixel), the camera solved and stood as a second camera object, and the scene rendered again through it. The two
silhouettes must agree. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/reference.py -- <out>
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
without them). <out> is an absolute path: it writes <out>.result.json, <out>.truth.png and <out>.solved.png, and
exits 1 when a check failed. The checks run inside one try: an uncaught error is a failed check that names the
check before it, and the result file is written whatever happened.
"""
import json
import os
import sys
import tempfile
import time
import traceback
import types
from pathlib import Path
import bmesh
import bpy
import numpy as np
from bpy_extras.object_utils import world_to_camera_view
from mathutils import Euler, Matrix, Vector
SURFACE = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(SURFACE / "tools"))
import private_dirs # noqa: E402
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
if _refused:
raise SystemExit(_refused)
OUT = sys.argv[sys.argv.index("--") + 1]
if not os.path.isabs(OUT):
raise SystemExit(f"<out> must be an absolute path, not {OUT!r}: a relative one lands in Blender's start directory")
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules["brokkr_bridge"] = package
from brokkr_bridge import blender_target as bt # noqa: E402
import addon_utils # noqa: E402
sys.path.append(str(SURFACE))
bpy.ops.wm.read_factory_settings(use_empty=True)
for module in ("brokkr_mesh_polish", "brokkr_reference"):
addon_utils.enable(module, default_set=True)
from brokkr_reference import core # noqa: E402
target = bt.BrokkrBlenderTarget(bpy)
target.configure_action_dirs("", tempfile.mkdtemp(prefix="brokkr-reference-live-"))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1],
"hostRows": [row["name"] for row in target.host_actions()[0]]}
COUNT = [0]
T0 = time.time()
WIDTH, HEIGHT = 800, 600
def check(name, ok, detail=None):
R["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
def send(action, **fields):
COUNT[0] += 1
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
result = json.loads(receipt["hostResult"]) if receipt.get("hostResult") else None
print("SEND", f"{time.time() - T0:.1f}s", action, receipt["status"], str(receipt["message"])[:300], flush=True)
return receipt, result
def silhouette(camera, path):
"""Render through `camera` with a transparent film and return where the scene covers the frame."""
scene = bpy.context.scene
scene.camera = camera
scene.render.filepath = path
bpy.ops.render.render(write_still=True)
image = bpy.data.images.load(path)
alpha = np.array(image.pixels[:], dtype=np.float32).reshape(image.size[1], image.size[0], 4)[:, :, 3]
bpy.data.images.remove(image)
return alpha > 0.5
def drawn(camera, point):
"""The frame pixel (u, v down) Blender's own projection gives a world point."""
x, y, _ = world_to_camera_view(bpy.context.scene, camera, Vector(point))
return x * WIDTH, (1.0 - y) * HEIGHT
def params_of(camera):
data, render = camera.data, bpy.context.scene.render
return {"matrix_world": [list(row) for row in camera.matrix_world], "lens": data.lens, "shift_x": data.shift_x, "shift_y": data.shift_y,
"sensor_width": data.sensor_width, "sensor_fit": data.sensor_fit, "resolution": [render.resolution_x, render.resolution_y]}
try:
check("host file admitted", not R["hostErrors"] and "brokkr_reference.solve_camera" in R["hostRows"], R["hostRows"])
scene = bpy.context.scene
scene.render.engine = "BLENDER_WORKBENCH"
scene.render.film_transparent = True
scene.render.image_settings.file_format = "PNG"
scene.render.image_settings.color_mode = "RGBA"
scene.render.resolution_x, scene.render.resolution_y, scene.render.resolution_percentage = WIDTH, HEIGHT, 100
# --- the known scene: a hull, a tower off its middle and a wing, none mirrored, so no camera but one draws it --------
bm = bmesh.new()
for size, place in (((1.6, 4.0, 0.8), (0.0, 0.0, 0.4)), ((0.6, 0.8, 1.2), (0.3, -1.0, 1.4)), ((1.8, 1.0, 0.2), (1.7, 0.6, 0.5))):
bmesh.ops.create_cube(bm, size=1.0, matrix=Matrix.Translation(place) @ Matrix.Diagonal((*size, 1.0)))
mesh = bpy.data.meshes.new("Known")
bm.to_mesh(mesh)
bm.free()
scene.collection.objects.link(bpy.data.objects.new("Known", mesh))
truth = bpy.data.objects.new("Truth", bpy.data.cameras.new("Truth"))
scene.collection.objects.link(truth)
truth.data.lens, truth.data.sensor_width, truth.data.sensor_fit, truth.data.shift_x, truth.data.shift_y = 50.0, 36.0, "HORIZONTAL", 0.08, -0.05
truth.matrix_world = Matrix.Translation((-6.5, -8.0, 4.6)) @ Euler((1.2, 0.03, -0.72), "XYZ").to_matrix().to_4x4()
bpy.context.view_layer.update()
first = silhouette(truth, OUT + ".truth.png")
check("fixture: the scene covers part of the frame and touches no edge", 0.05 < first.mean() < 0.6 and not (first[0].any() or first[-1].any() or first[:, 0].any() or first[:, -1].any()), float(first.mean()))
corners = {f"v{v.index}": tuple(v.co) for v in mesh.vertices}
marks = {k: drawn(truth, p) for k, p in corners.items()}
world = "; ".join(f"{k}={p[0]:.4f},{p[1]:.4f},{p[2]:.4f}" for k, p in corners.items())
pixels = "; ".join(f"{k}={u:.1f},{v:.1f}" for k, (u, v) in marks.items())
box = f"0,0,{WIDTH},{HEIGHT}"
# --- camera_of reads the scene's own camera: the record draws what Blender draws ------------------------------------
record = core.camera_of(params_of(truth))
off = float(np.abs(core.project(record, list(corners.values())) - np.array(list(marks.values()))).max())
check("camera_of(the truth camera) draws each corner where Blender does, within 0.01 px", off < 0.01, off)
# --- compute only ----------------------------------------------------------------------------------------------------
before = sorted(o.name for o in bpy.data.objects)
receipt, only = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box)
check("compute only: accepted, the record in the receipt, no object made", receipt["status"] == "accepted" and only and only["camera"] is None
and sorted(o.name for o in bpy.data.objects) == before and len(only["residuals"]) == 24, [receipt["message"], only and only["model"]])
check("auto takes the free model on a view cropped off-axis", only and only["model"] == "free", only and only["tried"])
# --- stood as a camera, and the scene rendered again through it ---------------------------------------------------
scene.render.resolution_x, scene.render.resolution_y = 320, 200 # the action sets the frame, not the caller
receipt, solved = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, model="free", camera_name="Solved", width=WIDTH)
stood = bpy.data.objects.get("Solved")
check("solve_camera with camera_name: accepted, a camera object, the render size set to the box", receipt["status"] == "accepted" and stood is not None
and stood.type == "CAMERA" and (scene.render.resolution_x, scene.render.resolution_y) == (WIDTH, HEIGHT), receipt["message"])
R["record"] = {k: solved[k] for k in ("lens", "lens_band", "lens_at_bound", "rms", "median", "left_out", "model", "c", "azimuth", "elevation", "distance", "roll")}
place = float((stood.matrix_world.translation - truth.matrix_world.translation).length)
check("the record: lens within 1 mm of 50, place within 0.1 m, rms under 0.2 px, lens not at a bound",
abs(solved["lens"] - 50.0) < 1.0 and place < 0.1 and solved["rms"] < 0.2 and solved["lens_at_bound"] is None, [solved["lens"], place, solved["rms"]])
check("the centre is solved: the truth's shifts within 0.005 of a frame width", abs(stood.data.shift_x - 0.08) < 0.005 and abs(stood.data.shift_y + 0.05) < 0.005,
[stood.data.shift_x, stood.data.shift_y])
worst = max(float(np.hypot(*np.subtract(drawn(stood, p), marks[k]))) for k, p in corners.items())
check("Blender's projection through the stood camera draws each corner within 0.5 px of its mark", worst < 0.5, worst)
second = silhouette(stood, OUT + ".solved.png")
miss = 1.0 - float((first & second).sum() / (first | second).sum())
R["iouMiss"] = miss
# 1 - IoU of the two silhouettes. Shipped 0.000168; with shift_y's sign flipped in core.blender (M5) 0.6489: the bound is their geometric mean.
check("the re-render's silhouette matches the first: 1 - IoU under 0.0105", miss < 0.0105, miss)
# --- again under the same name updates the one camera; a held lens is held ------------------------------------------
receipt, held = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, model="free", lens=85, camera_name="Solved", width=400)
check("a second run updates the same camera: one object, the lens held at 85, the frame 400 by 300", receipt["status"] == "accepted"
and [o.name for o in bpy.data.objects if o.type == "CAMERA"] == ["Solved", "Truth"] and abs(stood.data.lens - 85.0) < 1e-4
and held["lens_band"] == [85.0, 85.0] and (scene.render.resolution_x, scene.render.resolution_y) == (400, 300), [receipt["message"], held and held["lens"]])
# --- refusals are failed receipts that name the cause ----------------------------------------------------------------
five = "; ".join(pixels.split("; ")[:5])
receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=five, box=box)
check("five points: failed, naming the count", receipt["status"] == "failed" and "5 points" in receipt["message"], receipt["message"])
receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box=box, camera_name="Known")
check("camera_name of a mesh object: failed, nothing changed", receipt["status"] == "failed" and "not a camera" in receipt["message"]
and bpy.data.objects["Known"].type == "MESH", receipt["message"])
receipt, _ = send("brokkr_reference.solve_camera", world=world, pixels=pixels, box="0,0,0,600")
check("a box of no width: failed, naming it", receipt["status"] == "failed" and "no width" in receipt["message"], receipt["message"])
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, printed and written, not a missing result file
check(f"no uncaught error after: {R['checks'][-1]['name'] if R['checks'] else 'the start'}", False, traceback.format_exc().splitlines()[-6:])
R["ok"] = all(c["ok"] for c in R["checks"])
for c in R["checks"]:
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,146 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "host file admitted",
"ok": true,
"detail": [
"brokkr_mesh_polish.audit",
"brokkr_mesh_polish.repair",
"brokkr_mesh_polish.orient",
"brokkr_mesh_polish.delight",
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera"
]
},
{
"name": "fixture: the scene covers part of the frame and touches no edge",
"ok": true,
"detail": 0.1361375
},
{
"name": "camera_of(the truth camera) draws each corner where Blender does, within 0.01 px",
"ok": true,
"detail": 6.941722509168358e-05
},
{
"name": "compute only: accepted, the record in the receipt, no object made",
"ok": true,
"detail": [
"Operator brokkr_reference.solve_camera finished.",
"free"
]
},
{
"name": "auto takes the free model on a view cropped off-axis",
"ok": true,
"detail": {
"upright": {
"rms": 1.380259942769221,
"left_out": 1.5572430492976839,
"lens": 48.08928208959338
},
"rolled": {
"rms": 0.6797349192884168,
"left_out": 0.8350092431422779,
"lens": 48.499059377417225
},
"free": {
"rms": 0.03555833513434369,
"left_out": 0.04252972975472319,
"lens": 50.02266319807241
}
}
},
{
"name": "solve_camera with camera_name: accepted, a camera object, the render size set to the box",
"ok": true,
"detail": "Operator brokkr_reference.solve_camera finished."
},
{
"name": "the record: lens within 1 mm of 50, place within 0.1 m, rms under 0.2 px, lens not at a bound",
"ok": true,
"detail": [
50.02266319807241,
0.004567543465755453,
0.03555833513434369
]
},
{
"name": "the centre is solved: the truth's shifts within 0.005 of a frame width",
"ok": true,
"detail": [
0.079900361597538,
-0.051553647965192795
]
},
{
"name": "Blender's projection through the stood camera draws each corner within 0.5 px of its mark",
"ok": true,
"detail": 0.03400179965902824
},
{
"name": "the re-render's silhouette matches the first: 1 - IoU under 0.0105",
"ok": true,
"detail": 0.00016831152933971527
},
{
"name": "a second run updates the same camera: one object, the lens held at 85, the frame 400 by 300",
"ok": true,
"detail": [
"Operator brokkr_reference.solve_camera finished.",
85.0
]
},
{
"name": "five points: failed, naming the count",
"ok": true,
"detail": "Error: 5 points are named in both world and pixels; six are needed"
},
{
"name": "camera_name of a mesh object: failed, nothing changed",
"ok": true,
"detail": "Error: 'Known' is an object that is not a camera."
},
{
"name": "a box of no width: failed, naming it",
"ok": true,
"detail": "Error: box [0.0, 0.0, 0.0, 600.0] has no width: it is u0, v0, u1, v1 with u1 past u0 and v1 past v0"
}
],
"hostErrors": [],
"hostRows": [
"brokkr_mesh_polish.audit",
"brokkr_mesh_polish.repair",
"brokkr_mesh_polish.orient",
"brokkr_mesh_polish.delight",
"brokkr_mesh_polish.scrub_markings",
"brokkr_mesh_polish.cut_parts",
"brokkr_mesh_polish.pick",
"brokkr_reference.solve_camera"
],
"record": {
"lens": 50.02266319807241,
"lens_band": [
50.02266319807241,
50.02266319807241
],
"lens_at_bound": null,
"rms": 0.03555833513434369,
"median": 0.036713200453055594,
"left_out": 0.04252972975472319,
"model": "free",
"c": [
336.07971210679585,
258.7570824524072
],
"azimuth": 137.66552423487752,
"elevation": 19.81349852084873,
"distance": 11.315569478894277,
"roll": -1.8445361216036547
},
"iouMiss": 0.00016831152933971527,
"ok": true
}

View file

@ -0,0 +1,339 @@
"""Reference camera tests. No Blender: brokkr_reference/core.py on seeded points drawn through known cameras, and
the host action file against Brokkr's own checker.
Run: python3 -m unittest discover -s surfaces/blender/tests -v (needs numpy; skipped without it)
The operator and a camera stood in a scene are exercised in a real Blender by tests/live/reference.py.
Bounds follow lodur:ruling:deterministic-bound-margin: a reading here is the same on every run, so a bound a mutant
claims sits at the geometric mean of the shipped reading and that mutant's, and says both. The other numbers are
tolerances round a known truth that no mutant claims. The mutants, each run once on a scratch copy:
M1 plain squares for the pseudo-Huber loss test_one_point_60_px_off_does_not_turn_the_camera
M2 auto chooses by in-sample rms test_auto_takes_the_model_that_predicts_left_out_points
M3 the lens walk restarts from the grid test_the_band_is_walked_from_the_last_solve
M4 no bound on the focal length SolveTests.setUpClass (OverflowError), before test_long_lenses_stay_finite_and_inside_the_range
M5 shift_y's sign flipped in blender() test_blender_params_draw_the_same_pixels
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
"""
from __future__ import annotations
import importlib.util
import json
import math
import re
import sys
import types
import unittest
from pathlib import Path
SURFACE = Path(__file__).resolve().parents[1]
package = types.ModuleType("brokkr_bridge")
package.__path__ = [str(SURFACE / "brokkr_bridge")]
sys.modules.setdefault("brokkr_bridge", package)
from brokkr_bridge import action_table as at # noqa: E402
try:
import numpy as np
except ImportError: # pragma: no cover
np = None
if np is not None:
spec = importlib.util.spec_from_file_location("brokkr_reference_core", SURFACE / "brokkr_reference" / "core.py")
core = importlib.util.module_from_spec(spec)
spec.loader.exec_module(core)
BOX = [100.0, 50.0, 1100.0, 800.0]
NAMES = [f"p{i}" for i in range(13)]
def cloud():
"""Thirteen points in a box 3 m wide, 5 m long and 2 m tall."""
return np.random.default_rng(3).uniform([-1.5, -2.5, 0.0], [1.5, 2.5, 2.0], (13, 3))
def camera(points, azimuth, elevation, lens, centre=None):
"""A camera `lens` mm long looking at the points' middle from far enough off that they fill most of the box."""
f = lens * (BOX[2] - BOX[0]) / 36.0
a, e = math.radians(azimuth), math.radians(elevation)
off = 1.3 * np.ptp(points, axis=0).max() * f / (BOX[2] - BOX[0])
C = points.mean(0) + off * np.array([-math.sin(a) * math.cos(e), math.cos(a) * math.cos(e), math.sin(e)])
return {"C": C, "R": core._rotation(a + math.pi, -e, 0.0), "f": f, "c": centre or [(BOX[0] + BOX[2]) / 2, (BOX[1] + BOX[3]) / 2], "box": BOX}
def marks(cam, points, noise=1.0, build=0.0, drawn=None):
"""(world, pixels): the points as a build has them (`build` metres of error) and as the image draws them."""
r = np.random.default_rng(5)
P = core.project(cam, points if drawn is None else drawn) + r.normal(0, noise, (len(points), 2))
W = points + r.normal(0, build, points.shape) if build else points
return dict(zip(NAMES, W.tolist())), dict(zip(NAMES, P.tolist()))
def place_error(solved, cam):
return float(np.linalg.norm(np.array(solved["C"]) - cam["C"]))
@unittest.skipIf(np is None, "numpy")
class SolveTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.points = cloud()
cls.oblique = camera(cls.points, 35, 20, 50)
cls.world, cls.pixels = marks(cls.oblique, cls.points)
cls.auto = core.solve(cls.world, cls.pixels, BOX)
def test_an_oblique_50_mm_view_is_recovered(self):
"""recovers-oblique: 1 px of marking noise on 13 points. Read 50.22 mm, 0.031 m, 34.99 and 20.08 degrees, rms 1.17."""
s = self.auto
self.assertAlmostEqual(s["lens"], 50.0, delta=1.0)
self.assertLess(place_error(s, self.oblique), 0.1)
self.assertAlmostEqual(s["azimuth"], 35.0, delta=0.3)
self.assertAlmostEqual(s["elevation"], 20.0, delta=0.3)
self.assertTrue(0.8 < s["rms"] < 1.6, s["rms"])
self.assertEqual(s["lens_at_bound"], None)
self.assertEqual(sorted(s["residuals"]), sorted(NAMES))
self.assertEqual(json.loads(json.dumps(s)), s)
def test_one_point_60_px_off_does_not_turn_the_camera(self):
"""M1. Azimuth off by 0.262 degrees shipped, 1.186 with plain squares: bound 0.557. Place off by 0.0411 m
shipped, 0.1401: bound 0.0759. Median miss 1.43 px shipped, 2.82: bound 2.01."""
pixels = dict(self.pixels, p4=[self.pixels["p4"][0] + 60, self.pixels["p4"][1]])
s = core.solve(self.world, pixels, BOX, model="upright")
self.assertLess(abs(s["azimuth"] - 35.0), 0.557)
self.assertLess(place_error(s, self.oblique), 0.0759)
self.assertLess(s["median"], 2.01)
self.assertEqual(s["worst"][0], "p4")
def test_auto_takes_the_model_that_predicts_left_out_points(self):
"""M2: on a centred view the free model fits the marks closest (rms 1.10 against upright's 1.17) and predicts
a left-out one worst (1.95 against 1.49); on a view cropped off-centre it is the only one that predicts."""
self.assertEqual(self.auto["model"], "upright")
tried = self.auto["tried"]
self.assertLess(tried["free"]["rms"], tried["upright"]["rms"])
self.assertLess(tried["upright"]["left_out"], tried["free"]["left_out"])
cropped = camera(self.points, 35, 20, 50, centre=[640.0, 400.0])
s = core.solve(*marks(cropped, self.points), BOX)
self.assertEqual(s["model"], "free")
self.assertAlmostEqual(s["c"][0], 640.0, delta=5.0)
def test_the_band_is_an_equal_error_band(self):
"""band-is-equal-error: a build 4 cm off. Every lens in the band refits within BAND of the best rms, and one
step past each end does not."""
world, pixels = marks(self.oblique, self.points, build=0.04)
s = core.solve(world, pixels, BOX, model="upright")
low, high = s["lens_band"]
self.assertLess(low, s["lens"] * 0.95)
self.assertGreater(high, s["lens"] * 1.05)
for lens in (low, math.sqrt(low * s["lens"]), math.sqrt(high * s["lens"]), high):
self.assertLessEqual(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"] + 1e-6, lens)
for lens in (low * math.exp(-core.STEP), high * math.exp(core.STEP)):
self.assertGreater(core.solve(world, pixels, BOX, model="upright", lens=lens)["rms"], core.BAND * s["rms"], lens)
held = core.solve(world, pixels, BOX, model="upright", lens=low)
self.assertEqual((held["lens"], held["lens_band"], held["lens_at_bound"]), (low, [low, low], None))
def test_the_band_is_walked_from_the_last_solve(self):
"""M3: each step of the walk is one solve started at the one before; restarting from the grid costs 16 per
step. lm calls: 34 shipped (16 starts, 13 left-out solves, 3 lenses inside the band and one past each end),
109 restarted, separation 3.2: bound 61."""
world, pixels = marks(self.oblique, self.points, build=0.04)
calls, lm = [0], core.lm
def counted(*args, **kwargs):
calls[0] += 1
return lm(*args, **kwargs)
core.lm = counted
try:
s = core.solve(world, pixels, BOX, model="upright")
finally:
core.lm = lm
self.assertGreater(s["lens_band"][1] / s["lens_band"][0], math.exp(2.5 * core.STEP)) # a band of steps to walk
self.assertLess(calls[0], 61)
def test_a_wide_band_is_walked_to_its_end(self):
"""M13: a 135 mm view of a build 8 cm off cannot tell 72 mm from the bound, 32 steps above its best lens
(159.3 mm). The band's long end is 4000 mm shipped and 1177 (the best times e^2) when the walk stops after
20 steps, separation 3.4: bound 2170."""
s = core.solve(*marks(camera(self.points, 35, 20, 135), self.points, build=0.08), BOX, model="upright")
self.assertGreater(s["lens_band"][1], 2170)
self.assertEqual((s["lens_band"][1], s["lens_at_bound"]), (core.LENS_MM[1], None)) # the band reaches the bound; the best lens does not
def test_long_lenses_stay_finite_and_inside_the_range(self):
"""long-lens-bounded, M4: with no bound the 400 mm view on a build 4 cm off runs log f to OverflowError and
the orthographic one reads 20208 mm; so does one start of the oblique solve in setUpClass, which is where
the mutant run died (every test of this class with it)."""
for lens in (135, 400):
cam = camera(self.points, 35, 20, lens)
for build in (0.0, 0.04):
s = core.solve(*marks(cam, self.points, build=build), BOX, model="upright")
low, high = s["lens_band"]
self.assertTrue(core.LENS_MM[0] <= low <= s["lens"] <= high <= core.LENS_MM[1], (lens, build, s["lens"], s["lens_band"]))
self.assertTrue(low <= lens <= high or build == 0.0, (lens, build, s["lens_band"]))
self.assertTrue(all(math.isfinite(v) for v in s["C"]))
self.assertEqual(s["lens_at_bound"], "long" if s["lens"] == core.LENS_MM[1] else None)
far = camera(self.points, 35, 20, 1e5) # orthographic to any marking
s = core.solve(*marks(far, self.points, noise=0.0), BOX, model="upright")
self.assertEqual((s["lens"], s["lens_at_bound"], s["lens_band"][1]), (core.LENS_MM[1], "long", core.LENS_MM[1]))
self.assertLess(s["rms"], 1.0)
self.assertAlmostEqual(s["azimuth"], 35.0, delta=0.3)
def test_a_turned_torso_is_recovered_as_twist(self):
"""torso-turn, M6: five points drawn turned 12 degrees about a pivot. Twist off by 0.05 degrees shipped and
by 12 untwisted: bound 0.77. rms 1.16 px shipped, 23.5: bound 5.2."""
turned, pivot = NAMES[:5], (0.2, -0.3)
drawn = core._turned(self.points, np.array([n in turned for n in NAMES]), math.radians(12), pivot)
world, pixels = marks(self.oblique, self.points, drawn=drawn)
s = core.solve(world, pixels, BOX, model="upright", turned=turned, pivot=pivot)
self.assertLess(abs(s["twist"] - 12.0), 0.77)
self.assertLess(s["rms"], 5.2)
def test_square_solves_elevations_along_both_axes(self):
"""square-quarter-turns, M7: a rear elevation (the camera behind, looking along +y) and a side elevation
(looking along x) at 300 mm. The side view's rms is 1.19 px shipped and 193.9 with the yaw held to y only:
bound 15.2."""
for azimuth in (180, 90):
cam = camera(self.points, azimuth, 0, 300)
s = core.solve(*marks(cam, self.points), BOX, model="square")
self.assertLess(s["rms"], 15.2, azimuth)
self.assertAlmostEqual(abs(s["azimuth"]), azimuth, delta=0.05)
look = -np.array(s["R"][2])
self.assertLess(min(abs(look[0]), abs(look[1])), 1e-9) # straight along a world axis
def test_refusals_name_their_cause(self):
"""refusals"""
few = {k: self.pixels[k] for k in NAMES[:5]}
cases = (((self.world, few, BOX), {}, "5 points"), ((dict(self.world, p3=[0.0, float("nan"), 1.0]), self.pixels, BOX), {}, "'p3'"),
((self.world, self.pixels, [100, 50, 100, 800]), {}, "no width"), ((self.world, self.pixels, [100, 50, 1100, 50]), {}, "no height"),
((self.world, self.pixels, BOX), {"model": "x"}, "unknown model 'x'"), ((self.world, self.pixels, BOX), {"lens": 5000.0}, "5000"))
for args, kwargs, said in cases:
with self.assertRaises(core.ReferenceFitError) as caught:
core.solve(*args, **kwargs)
self.assertIn(said, str(caught.exception))
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."""
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()))
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"))
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)
self.assertLess(held["rms"], 1e-3)
self.assertAlmostEqual(held["azimuth"], 35.0, delta=0.01)
self.assertNotIn("NaN", json.dumps(held))
@unittest.skipIf(np is None, "numpy")
class CameraTests(unittest.TestCase):
CAM = {"C": [3.0, -7.0, 2.5], "f": 1400.0, "c": [640.0, 395.0], "box": BOX}
def setUp(self):
self.cam = dict(self.CAM, R=core._rotation(0.4, -0.2, 0.05).tolist())
self.points = cloud()
def blender_pixels(self, params, points):
"""Where Blender's camera draws world points, from its own definitions: the sensor spans the frame's width,
shifts are in frame widths, and the frame's middle is the optical axis moved by the shift."""
M = np.array(params["matrix_world"])
q = (points - M[:3, 3]) @ M[:3, :3]
w, h = params["resolution"]
x = q[:, 0] / -q[:, 2] * params["lens"] / params["sensor_width"] - params["shift_x"]
y = q[:, 1] / -q[:, 2] * params["lens"] / params["sensor_width"] - params["shift_y"]
return np.stack([(x + 0.5) * w, h / 2 - y * w], 1)
def test_blender_params_draw_the_same_pixels(self):
"""blender-round-trip, M5: the centre is 30 px below the box's middle, so a flipped shift_y moves every
point 72 px at this width."""
for width in (1200, 777):
params = core.blender(self.cam, width)
self.assertEqual(params["resolution"], [width, round(width * 0.75)])
ours = core.in_frame(self.cam, core.project(self.cam, self.points), width)
self.assertLess(np.abs(self.blender_pixels(params, self.points) - ours).max(), 1e-6)
def test_camera_of_reads_blender_back(self):
back = core.camera_of(core.blender(self.cam, 1200), BOX)
for key in ("C", "R", "f", "c", "box"):
self.assertLess(np.abs(np.array(back[key]) - np.array(self.cam[key])).max(), 1e-9, key)
framed = core.camera_of(core.blender(self.cam, 1200)) # no box: the frame itself, in its own pixels
self.assertEqual(framed["box"], [0.0, 0.0, 1200.0, 900.0])
self.assertLess(np.abs(core.project(framed, self.points) - core.in_frame(self.cam, core.project(self.cam, self.points), 1200)).max(), 1e-6)
with self.assertRaises(core.ReferenceFitError):
core.camera_of(dict(core.blender(self.cam, 1200), sensor_fit="VERTICAL"))
def test_a_lifted_pixel_lies_on_its_plane_and_draws_back(self):
point = core.lift(self.cam, [500.0, 300.0], [0.0, 0.0, 1.0], [0.0, 0.0, 1.0])
self.assertAlmostEqual(point[2], 1.0, places=9)
self.assertLess(np.abs(core.project(self.cam, point[None])[0] - [500.0, 300.0]).max(), 1e-6)
def test_field_parsers(self):
self.assertEqual(core.points("a=1,2,3; b = 4, 5.5 ,6;", 3, "world"), {"a": [1.0, 2.0, 3.0], "b": [4.0, 5.5, 6.0]})
self.assertEqual(core.numbers("100, 50,1100,800", 4, "box"), BOX)
for text, size, said in (("a=1,2", 3, "'a'"), ("a=1,2,3; a=4,5,6", 3, "twice"), ("=1,2", 2, "no name"), ("a=1,nan", 2, "'a'"), ("a=1,x", 2, "'a'")):
with self.assertRaises(core.ReferenceFitError) as caught:
core.points(text, size, "world")
self.assertIn(said, str(caught.exception))
class HostFileTests(unittest.TestCase):
def setUp(self):
self.document = json.loads((SURFACE / "brokkr_reference" / "brokkr_actions.json").read_text(encoding="utf-8"))
self.host = [{**row, "host": "brokkr_reference"} for row in self.document["actions"]]
self.envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_reference.solve_camera"}
def test_brokkr_admits_the_file(self):
"""rows-check: Brokkr's own host-file checker."""
at.check_host(self.document, at.table()["charsets"])
def test_the_row_names_the_operator_and_properties_the_add_on_defines(self):
source = (SURFACE / "brokkr_reference" / "__init__.py").read_text(encoding="utf-8")
(row,) = self.document["actions"]
self.assertIn(f'bl_idname = "{row["name"]}"', source)
self.assertEqual(row.get("result"), "brokkr_mesh_polish_result")
body = source.split(f'bl_idname = "{row["name"]}"')[1].split("def work")[0]
for field in row["fields"]:
self.assertIn(f" {field['name']}: bpy.props.", body, field["name"])
self.assertEqual(body.count(": bpy.props."), len(row["fields"]))
def test_a_valid_intent_is_admitted_and_a_bound_miss_is_refused(self):
fields = {"world": "a=0,0,0", "pixels": "a=1,2", "box": "0,0,10,10"}
admitted = at.validate({**self.envelope, **fields}, self.host)
self.assertEqual((admitted["model"], admitted["lens"], admitted["width"]), ("auto", 0, 1000))
for bad in ({"lens": 4001}, {"model": "fisheye"}, {"width": 8}, {"world": ""}):
with self.assertRaises(at.IntentInvalid):
at.validate({**self.envelope, **fields, **bad}, self.host)
class OwnershipTests(unittest.TestCase):
"""The negative patterns of the cut: the arithmetic needs no Blender, the images and sheets stay with whoever
marked them, and no other package reaches into this one."""
def test_core_does_not_import_blender(self):
self.assertIsNone(re.search(r"import bpy|mathutils", (SURFACE / "brokkr_reference" / "core.py").read_text(encoding="utf-8")))
def test_the_package_reads_no_image_or_sheet(self):
for path in (SURFACE / "brokkr_reference").glob("*"):
if path.is_file():
self.assertIsNone(re.search(r"concepts\.json|PIL|Image\.open", path.read_text(encoding="utf-8")), path.name)
def test_no_other_package_names_this_one(self):
for package in ("brokkr_kitbash", "brokkr_rig", "brokkr_bridge", "brokkr_mesh_polish"):
for path in (SURFACE / package).rglob("*.py"):
self.assertNotIn("brokkr_reference", path.read_text(encoding="utf-8"), str(path))
if __name__ == "__main__":
unittest.main()