Parse crs:Crop* from the JPEG, draw the dashed overlay on the grid/loupe/filmstrip, embed the same block when the app crops, and strip it from baked deliveries so Lightroom does not apply it twice. Full framing usualScale follows Peter's Switzerland hand crops (~0.77).
732 lines
37 KiB
TypeScript
732 lines
37 KiB
TypeScript
/**
|
|
* Automatic sports crop: who the photo is about and the frame around them, the way a photojournalist crops a
|
|
* first pass. Pure geometry over detections (people, balls, and how sharp each person is), so it is fast,
|
|
* testable and easy to tune. Tuned against Peter's own Lightroom crops (handball, October 2026):
|
|
*
|
|
* - The subject is who is in focus with a visible face, not who is biggest: blurred / faceless players in
|
|
* the foreground are scenery (even when the AF point landed on them).
|
|
* - With a ball in play, the ball and the sharp players contesting it come along. Which ball that is
|
|
* depends on the sport: handball plays it in the hands, football plays it on the ground.
|
|
* - The crop is usually two thirds of the frame (the same shape), the subject in the middle across, the upper
|
|
* body a little above the middle and little or no empty pitch under the feet (spare height goes above, to the
|
|
* crowd and the stands). A foot that is whole in the photo stays in; heads and the ball are never cut.
|
|
* - A narrow body box stops at the torso, so the crop keeps a margin where the hands are. A foot that is whole
|
|
* stays whole when that person stays in the crop. A crop that slices a ball is not a crop.
|
|
* - An open frame with a team in it stays open: the row is the subject, and the crop does not drop people out of it.
|
|
* - Cutting another sharp person in half is avoided; cutting blurred ones doesn't matter.
|
|
* - A generic event, and any photo with no ball, is reportage: a whole hand and a whole foot stay in. When the
|
|
* foot already leaves the photo, the crop ends mid-shin or mid-thigh, never on the sock. A person the frame
|
|
* has already cut in half stays out. A stray hand or foot of someone else is cropped out. A head in a window
|
|
* or a torso does not beat a whole figure, and a crop never slices someone who is in it.
|
|
* - "tight" is the agencies' handball look, and only with a ball in play: the subject fills the height, cut
|
|
* mid-shin or mid-thigh when the foot is already out. "full" keeps whole bodies when they fit.
|
|
*
|
|
* Boxes are fractions of the upright photo (0..1, y down).
|
|
* When the camera wrote a focus point, the person under it is the subject; sharpness still frames everyone else.
|
|
*/
|
|
|
|
/** Where the camera focused, as a point on the upright photo. Same shape as `ingest/focus.ts`. */
|
|
export interface FocusHint {
|
|
x: number;
|
|
y: number;
|
|
box?: { x0: number; y0: number; x1: number; y1: number };
|
|
}
|
|
|
|
export interface Box {
|
|
x0: number;
|
|
y0: number;
|
|
x1: number;
|
|
y1: number;
|
|
}
|
|
|
|
export interface Detection extends Box {
|
|
score: number;
|
|
/** How sharp the person is, relative to the sharpest one in the photo (0..1). Absent: unknown (all equal). */
|
|
sharpness?: number;
|
|
/** The same measure, absolute (variance of the Laplacian at 1024 px): compares frames of a burst. */
|
|
focus?: number;
|
|
/**
|
|
* Head and shoulders boxed on their own (a face in a window, a torso) while the frame still has the rest of
|
|
* the person. Set for reportage once faces are known. Never the subject when a whole figure is in the photo.
|
|
*/
|
|
fragment?: boolean;
|
|
}
|
|
|
|
export interface Detections {
|
|
/** Upright photo size in pixels. */
|
|
width: number;
|
|
height: number;
|
|
people: Detection[];
|
|
balls: Detection[];
|
|
}
|
|
|
|
export interface Composition {
|
|
/** The proposed crop. */
|
|
rect: Box;
|
|
/** What the crop is built around. */
|
|
subject: Box;
|
|
reason: "ball" | "group" | "person";
|
|
/** People counted in the subject. */
|
|
people: number;
|
|
/** The ball in play, when the photo is about one. A crop that slices it is not sent. */
|
|
ball?: Box | null;
|
|
}
|
|
|
|
const MIN_PERSON = 0.4;
|
|
const MIN_BALL = 0.3;
|
|
/** Smaller people (in photo heights) are too far away to be what the photo is about. */
|
|
const MIN_HEIGHT = 0.08;
|
|
/** Tuning, fitted to Peter's crops (exported so the evaluation script can sweep it). */
|
|
export const TUNING = {
|
|
inFocus: 0.55,
|
|
// Fitted to Peter's Lightroom soft crops (Portugal x Suíça, Nov 2026): median width ~0.77, mode around 2/3.
|
|
usualScale: 0.77,
|
|
wScale: 1.0,
|
|
wFill: 1.0,
|
|
fillAt: 0.6,
|
|
wCentre: 1.2,
|
|
wHead: 0.8,
|
|
headMin: 0.04,
|
|
headMax: 0.16,
|
|
wChest: 1.4,
|
|
chestAt: 0.42,
|
|
wBelow: 2.5,
|
|
belowMax: 0.08,
|
|
wCut: 1.2,
|
|
wJoint: 0.8,
|
|
/** A hand or a foot of someone who is not the subject, left in the frame. */
|
|
wStray: 4,
|
|
};
|
|
|
|
/**
|
|
* Where the joints of a standing person roughly are, as fractions of their box from the top (neck, hips, knees,
|
|
* ankles). A crop edge across a body should fall between them, mid-limb, never on one (docs/photo-editing-rules.md).
|
|
*/
|
|
const JOINTS = [0.17, 0.53, 0.74, 0.95];
|
|
const JOINT_BAND = 0.035;
|
|
/** Below this, the foot is whole in the photo (the box does not run off the bottom edge). */
|
|
const FEET_IN_FRAME = 0.985;
|
|
/** A bottom edge past this fraction of the body is in the foot, not mid-shin. */
|
|
const FOOT_ZONE = 0.9;
|
|
/** Mid-shin and mid-thigh: between the joints, never on the ankle, the knee or the hip. */
|
|
const MID_SHIN = 0.86;
|
|
const MID_THIGH = 0.64;
|
|
/** Ground kept under a sole that stays in the crop, as a fraction of the body height. */
|
|
const SOLE_PAD = 0.03;
|
|
const SOLE_LIMIT = 0.995;
|
|
/** Deliberate plans of one moment: half body (between neck and hips) and three-quarter (mid-thigh). Never a joint, never the foot. */
|
|
export const PLANS = { half: 0.42, threeQuarter: MID_THIGH } as const;
|
|
/** A non-subject shorter than this, against the photo edge, is a stray hand or foot, not another person. */
|
|
const STRAY_HEIGHT = 0.35;
|
|
/**
|
|
* A person detector boxes the torso. On a narrow standing figure the hands sit outside that box, about this
|
|
* fraction of the body height to either side. The crop has to keep that margin.
|
|
*/
|
|
const HAND_PAD = 0.12;
|
|
/** How many similar people, across how much of the frame, make an open plan rather than one player's photo. */
|
|
const OPEN_PEOPLE = 4;
|
|
const OPEN_SPAN = 0.45;
|
|
|
|
/** Tight framing: the subject's tallest body about this many crop heights (a little cut at the bottom). */
|
|
export const TIGHT = { fillAt: 1.05, wFill: 2.2, chestAt: 0.34, headMax: 0.2 };
|
|
|
|
export interface ComposeOptions {
|
|
/** "full": whole bodies when they fit (default); "tight": the agencies' close framing. A complete foot stays in. */
|
|
framing?: "full" | "tight";
|
|
/**
|
|
* "reportage": a person, no match (a generic event, or a photo with no ball). Whole hands and feet stay.
|
|
* "sport": a ball in play; tight framing may cut a leg only when the foot already leaves the photo.
|
|
*/
|
|
context?: "sport" | "reportage";
|
|
/** Narrowest crop allowed, as a fraction of the photo's width (from the delivery's minimum resolution). */
|
|
minWidth?: number;
|
|
/** Where the camera focused. The person there is the subject; the rest of the crop still follows the model. */
|
|
focus?: FocusHint | null;
|
|
/** Faces already found on this photo, in the same fractions. Reportage uses them to tell a whole figure from a bust. */
|
|
faces?: readonly Box[];
|
|
/**
|
|
* The event's sport. Handball plays the ball in the hands or in the air, so a ball on the floor does not frame
|
|
* the photo. A sport that plays the ball on the ground (football) keeps the ball at the feet.
|
|
*/
|
|
sport?: string | null;
|
|
}
|
|
|
|
/** A generic event: no opponent and no fixture. The crop is a person, not a match. */
|
|
export function isReportage(event: { away?: string | null; fixtureId?: string | null } | null): boolean {
|
|
if (!event) return false;
|
|
if (event.fixtureId) return false;
|
|
return !(event.away ?? "").trim();
|
|
}
|
|
|
|
/** Handball keeps the ball in the hands. A ball below the knee is on the floor and is not the action. */
|
|
export function isHandball(sport: string | null | undefined): boolean {
|
|
const name = (sport ?? "").toLowerCase();
|
|
return name.includes("andebol") || name.includes("handball");
|
|
}
|
|
|
|
const h = (b: Box) => b.y1 - b.y0;
|
|
const w = (b: Box) => b.x1 - b.x0;
|
|
const cx = (b: Box) => (b.x0 + b.x1) / 2;
|
|
const cy = (b: Box) => (b.y0 + b.y1) / 2;
|
|
const union = (a: Box, b: Box): Box => ({ x0: Math.min(a.x0, b.x0), y0: Math.min(a.y0, b.y0), x1: Math.max(a.x1, b.x1), y1: Math.max(a.y1, b.y1) });
|
|
const area = (b: Box) => Math.max(0, w(b)) * Math.max(0, h(b));
|
|
function overlap(a: Box, b: Box): number {
|
|
return area({ x0: Math.max(a.x0, b.x0), y0: Math.max(a.y0, b.y0), x1: Math.min(a.x1, b.x1), y1: Math.min(a.y1, b.y1) });
|
|
}
|
|
/** Touches the photo's left or right edge: someone only partly in the photo. */
|
|
const atEdge = (b: Box) => b.x0 < 0.01 || b.x1 > 0.99;
|
|
const sharp = (p: Detection) => p.sharpness ?? 1;
|
|
/** A hand at the frame edge, not a person standing in the row. */
|
|
const sliver = (p: Detection) => h(p) < 0.12 || (atEdge(p) && w(p) < 0.07);
|
|
|
|
/**
|
|
* The hands of a narrow standing figure sit outside the torso box. A wide box already has the arms in it
|
|
* (someone leaning), so it is left alone.
|
|
*/
|
|
function withHands(p: Box): Box {
|
|
if (h(p) < 1.6 * Math.max(w(p), 1e-6)) return p;
|
|
const pad = HAND_PAD * h(p);
|
|
return { x0: Math.max(0, p.x0 - pad), y0: p.y0, x1: Math.min(1, p.x1 + pad), y1: p.y1 };
|
|
}
|
|
|
|
/** The subject box plus the hands of everyone it is built from. The crop has to contain this. */
|
|
function requiredBox(s: Box, people: Detection[]): Box {
|
|
let box = s;
|
|
for (const p of people) box = union(box, withHands(p));
|
|
return box;
|
|
}
|
|
|
|
/**
|
|
* The crop overlaps a ball without containing it. That is a cut ball: the frame is not a crop, and it is not sent.
|
|
* A ball fully inside, or fully outside, is not cut.
|
|
*/
|
|
export function clipsBall(r: Box, balls: readonly Box[]): boolean {
|
|
for (const b of balls) {
|
|
const iw = Math.min(r.x1, b.x1) - Math.max(r.x0, b.x0);
|
|
const ih = Math.min(r.y1, b.y1) - Math.max(r.y0, b.y0);
|
|
if (iw <= 1e-6 || ih <= 1e-6) continue;
|
|
if (iw * ih < area(b) - 1e-6) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** The camera frame already cuts this ball (the box runs off the photo). */
|
|
function ballCutByFrame(b: Box): boolean {
|
|
return b.x0 <= 0.012 || b.y0 <= 0.012 || b.x1 >= 0.988 || b.y1 >= 0.988;
|
|
}
|
|
|
|
/**
|
|
* Do not send this photo. The crop slices a ball, or the ball in play is already cut by the camera and the
|
|
* picture we would send still shows it.
|
|
*/
|
|
export function sendBlockedByBall(crop: Box | null, balls: readonly Detection[], inPlay: Box | null): boolean {
|
|
const real = balls.filter((b) => b.score >= MIN_BALL);
|
|
if (crop && clipsBall(crop, real)) return true;
|
|
if (!inPlay || !ballCutByFrame(inPlay)) return false;
|
|
if (!crop) return true;
|
|
return overlap(crop, inPlay) > 0;
|
|
}
|
|
|
|
/**
|
|
* The face that belongs to this person: its centre sits in the box, or just above it when the box starts at the chin.
|
|
* The largest such face wins (a small face in the background is not this person's head).
|
|
*/
|
|
function faceOf(p: Box, faces: readonly Box[]): Box | null {
|
|
let best: Box | null = null;
|
|
for (const f of faces) {
|
|
const fx = (f.x0 + f.x1) / 2;
|
|
const fy = (f.y0 + f.y1) / 2;
|
|
if (fx < p.x0 - 0.02 || fx > p.x1 + 0.02) continue;
|
|
if (fy < p.y0 - 0.55 * h(f) || fy > p.y0 + 0.75 * h(p)) continue;
|
|
if (!best || h(f) > h(best)) best = f;
|
|
}
|
|
return best;
|
|
}
|
|
|
|
/**
|
|
* Reportage only. A face that is a large share of a box, with frame left around it, is not a standing figure: it is
|
|
* a head in a window or a torso the detector stopped at the chest. A portrait the camera already filled (the body
|
|
* leaves the frame) stays a real subject. Hair is pulled into the box so the crop does not start at the eyebrows.
|
|
*/
|
|
function forReportage(d: Detections, faces: readonly Box[]): Detections {
|
|
if (!faces.length) return d;
|
|
return {
|
|
...d,
|
|
people: d.people.map((p) => {
|
|
const face = faceOf(p, faces);
|
|
if (!face) return p;
|
|
const fragment = h(face) >= 0.22 * h(p) && p.y1 <= 0.9 && p.y0 >= 0.05;
|
|
const top = Math.max(0, face.y0 - 0.45 * h(face));
|
|
const y0 = Math.min(p.y0, top);
|
|
if (!fragment && y0 === p.y0) return p;
|
|
return { ...p, y0, fragment };
|
|
}),
|
|
};
|
|
}
|
|
|
|
/** Who the photo is about. Null when there is nobody clear enough (empty pitch, distant crowd). */
|
|
export function findSubject(
|
|
d: Detections,
|
|
focus?: FocusHint | null,
|
|
opts?: { reportage?: boolean; sport?: string | null; faces?: readonly Box[] },
|
|
): { box: Box; reason: Composition["reason"]; people: Detection[]; ball?: Box } | null {
|
|
const people = d.people.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT);
|
|
if (!people.length) return null;
|
|
// An open plan: a team lined up, or a wide frame of many people. The row is the subject. A tight crop of one
|
|
// of them would delete the others, which is not the photograph.
|
|
const cast = openCast(people) ?? widePlan(people);
|
|
if (cast) {
|
|
const box = cast.reduce<Box>((u, p) => union(u, p), cast[0]!);
|
|
return { box, reason: "group", people: cast };
|
|
}
|
|
// The main subject: the person the camera focused on, when that point lands on someone who is sharp and
|
|
// whose face is visible. A soft / faceless body in the foreground (AF on the jump in front) is scenery —
|
|
// never the crop's subject when a sharp face sits behind. Otherwise: in focus, then size, then whole.
|
|
const faces = opts?.faces ?? [];
|
|
const faced = faces.length ? people.filter((p) => faceOf(p, faces)) : people;
|
|
const candidates = faced.length ? faced : people;
|
|
const weight = (p: Detection) => sharp(p) ** 2 * Math.min(1, h(p) / 0.3) * (atEdge(p) ? 0.4 : 1) * (0.5 + 0.5 * p.score);
|
|
const whole = opts?.reportage ? candidates.filter((p) => !p.fragment) : candidates;
|
|
const pool = whole.length ? whole : candidates;
|
|
const sharpest = Math.max(1e-6, ...people.map(sharp));
|
|
const aimed = focus ? personAtFocus(pool, focus) ?? personAtFocus(people, focus) : null;
|
|
const aimedOk =
|
|
!!aimed &&
|
|
sharp(aimed) >= TUNING.inFocus * sharpest &&
|
|
(!faces.length || faced.length === 0 || !!faceOf(aimed, faces));
|
|
const main = (aimedOk ? aimed : null) ?? pool.reduce((a, b) => (weight(b) > weight(a) ? b : a));
|
|
if (!aimedOk && weight(main) < 0.05) return null;
|
|
// Reportage keeps a conversation together: someone in the shade is still part of it. A match stays stricter.
|
|
// A body the frame has already cut in half is not part of that conversation, unless it is the subject.
|
|
const withMain = opts?.reportage ? 0.35 : TUNING.inFocus;
|
|
const reach = opts?.reportage ? 0.85 : 0.45;
|
|
const cutOff = (p: Detection) => atEdge(p) && p !== main;
|
|
const focused = people.filter((p) => sharp(p) >= withMain * sharp(main) && !cutOff(p));
|
|
|
|
// A ball in play near the subject. Handball plays it in the hands or in the air: a ball below the knee is on
|
|
// the floor, and it does not frame the photo even when it overlaps the legs and sits closer to the body's
|
|
// middle. A sport that plays the ball on the ground keeps the one on the person, then the nearest.
|
|
const handball = isHandball(opts?.sport);
|
|
const balls = d.balls.filter((b) => b.score >= MIN_BALL && w(b) < 0.6 * h(main) && w(b) > 0.02 * h(main));
|
|
const near = balls.filter((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + 0.5 * h(main) && cy(b) > main.y0 - 0.4 * h(main) && cy(b) < main.y1 + 0.1 * h(main));
|
|
const onTheFloor = (x: Box) => (cy(x) - main.y0) / Math.max(h(main), 1e-6) >= 0.74;
|
|
const playing = handball ? near.filter((b) => !onTheFloor(b)) : near;
|
|
const ball = playing.sort((a, b) => {
|
|
const held = (x: Box) => (overlap(x, main) > 0 ? 0 : 1);
|
|
const dist = (x: Box) => (cx(x) - cx(main)) ** 2 + (cy(x) - cy(main)) ** 2;
|
|
return held(a) - held(b) || dist(a) - dist(b);
|
|
})[0];
|
|
if (ball) {
|
|
// Everyone big and close to the ball is in the duel, in focus or not (the goalkeeper facing the shot).
|
|
// Not someone the frame has already cut in half: they are background, and the crop leaves them out.
|
|
const contest = people.filter((p) => p === main || (!cutOff(p) && h(p) >= 0.6 * h(main) && Math.abs(cx(p) - cx(ball)) <= 0.9 * h(main) && overlap(p, { x0: 0, y0: 0, x1: 1, y1: 1 }) > 0.7 * area(p)));
|
|
if (!contest.includes(main)) contest.push(main);
|
|
const box = contest.reduce<Box>((u, p) => union(u, p), { x0: ball.x0, y0: ball.y0, x1: ball.x1, y1: ball.y1 });
|
|
return { box, reason: "ball", people: contest, ball };
|
|
}
|
|
|
|
// No ball: the subject and the sharp people standing with them (a duel, a celebration, a line-up).
|
|
const group: Detection[] = [main];
|
|
let grown = true;
|
|
while (grown) {
|
|
grown = false;
|
|
for (const p of focused) {
|
|
if (group.includes(p) || h(p) < 0.6 * h(main)) continue;
|
|
// A match does not pull in someone far taller (a blurred figure in front of a distant subject). Reportage
|
|
// does: the taller person is closer, and cropping them through the chest is not a photograph.
|
|
if (!opts?.reportage && h(p) > 1.7 * h(main)) continue;
|
|
const gap = reach * (opts?.reportage ? Math.max(h(main), h(p)) : h(main));
|
|
const near = group.some((g) => overlap(g, p) > 0 || Math.max(g.x0, p.x0) - Math.min(g.x1, p.x1) < gap);
|
|
if (near) {
|
|
group.push(p);
|
|
grown = true;
|
|
}
|
|
}
|
|
}
|
|
const box = group.reduce<Box>((u, p) => union(u, p), { x0: main.x0, y0: main.y0, x1: main.x1, y1: main.y1 });
|
|
return { box, reason: group.length > 1 ? "group" : "person", people: group };
|
|
}
|
|
|
|
/** The person the focus point (or the camera's subject box) lands on. Null: the point is on nobody, so the model decides. */
|
|
function personAtFocus(people: Detection[], focus: FocusHint): Detection | null {
|
|
if (focus.box) {
|
|
let best: { p: Detection; o: number } | null = null;
|
|
for (const p of people) {
|
|
const o = overlap(p, focus.box) / Math.max(area(focus.box), 1e-9);
|
|
if (o > 0.15 && (!best || o > best.o)) best = { p, o };
|
|
}
|
|
if (best) return best.p;
|
|
}
|
|
const hits = people.filter((p) => focus.x >= p.x0 - 0.03 && focus.x <= p.x1 + 0.03 && focus.y >= p.y0 - 0.03 && focus.y <= p.y1 + 0.03);
|
|
if (!hits.length) return null;
|
|
return hits.reduce((a, b) => (h(b) > h(a) ? b : a));
|
|
}
|
|
|
|
/**
|
|
* The crop around the subject. `aspect` is width/height in pixels (null: the photo's own). Candidates of a few
|
|
* sizes and positions are scored; the best one wins. Null when there is no subject.
|
|
*/
|
|
export function compose(d: Detections, aspect: number | null = null, opts: ComposeOptions = {}): Composition | null {
|
|
const reportage = opts.context === "reportage";
|
|
const faces = opts.faces ?? [];
|
|
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
|
if (!found) return null;
|
|
const { box: s, reason, people: inSubject, ball } = found;
|
|
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width); // width/height in frame fractions
|
|
const tallest = Math.max(...inSubject.map(h));
|
|
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
|
|
const headroom = 0.04 * tallest;
|
|
const minWidth = opts.minWidth ?? 0;
|
|
const balls = d.balls.filter((b) => b.score >= MIN_BALL);
|
|
const feetIn = s.y1 < FEET_IN_FRAME;
|
|
// A little ground under a sole that is whole in the photo, so the crop line is not the shoe.
|
|
const sole = feetIn ? Math.min(SOLE_LIMIT, s.y1 + Math.min(SOLE_PAD * tallest, Math.max(0, SOLE_LIMIT - s.y1))) : s.y1;
|
|
const finish = (c: (Composition & { cost?: number }) | null): Composition | null => (c ? { ...c, ball: ball ?? null } : null);
|
|
// A lined-up team, or a wide frame of many people. Keep every one of them. A tight cut would delete the row.
|
|
// If nothing fits without cutting someone, leave the photograph as it was shot.
|
|
const open = !ball && inSubject.length >= OPEN_PEOPLE && w(s) >= OPEN_SPAN;
|
|
if (open) {
|
|
const bottom = Math.min(1, feetIn ? sole : s.y1);
|
|
return finish(
|
|
frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, false, false, true, balls) ??
|
|
frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, true, balls),
|
|
);
|
|
}
|
|
// A person, not a ball: reportage, or a match photo where nobody is playing the ball. The sports cut stays
|
|
// for a ball in play. A complete hand or foot is never cut just to fill the frame.
|
|
const personStory = opts.context === "reportage" || !ball;
|
|
if (opts.framing === "tight" && !personStory) {
|
|
// Feet that are whole in the photo stay in. Cutting the leg is not how a tight frame is made.
|
|
if (feetIn) {
|
|
// Headroom gives way before a complete foot does.
|
|
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, true, false, false, balls)
|
|
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls)
|
|
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls);
|
|
if (whole) return finish(whole);
|
|
}
|
|
// The foot already leaves the photo: end mid-shin or mid-thigh, not on the sock.
|
|
const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, true, false, ball, balls);
|
|
if (cut) return finish(cut);
|
|
return null;
|
|
}
|
|
// The foot already leaves the photo. Stopping on the sock is the same as cutting the ankle.
|
|
if (!feetIn) {
|
|
const cut = cutAboveTheAnkle(s, ratio, headroom, tallest, others, inSubject, reason, minWidth, false, reportage, ball, balls);
|
|
if (cut) return finish(cut);
|
|
}
|
|
// Whole bodies, feet included. A little headroom gives way before a complete foot does.
|
|
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls)
|
|
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls)
|
|
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls);
|
|
if (whole || feetIn) return finish(whole);
|
|
return finish(frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth, false, true, reportage, balls));
|
|
}
|
|
|
|
/**
|
|
* The foot is already out of the photo. The crop ends between the joints (mid-shin or mid-thigh), pinned there
|
|
* so it cannot slide down onto the sock. A ball in the hands stays below the cut. The hip, the knee and the
|
|
* ankle are never the line.
|
|
*/
|
|
function cutAboveTheAnkle(s: Box, ratio: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight: boolean, reportage: boolean, ball?: Box, balls: readonly Box[] = []): (Composition & { cost: number }) | null {
|
|
// The line is on the person. The subject box can start higher, at a ball held overhead, and that must not
|
|
// pull the cut up onto the hip.
|
|
const body = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
|
const keep = (y: number) => Math.min(body.y1, Math.max(y, ball ? ball.y1 + 0.01 : 0));
|
|
const lines = [MID_SHIN, MID_THIGH]
|
|
.map((at) => keep(body.y0 + at * h(body)))
|
|
.filter((y) => {
|
|
const at = (y - body.y0) / Math.max(h(body), 1e-6);
|
|
if (at > FOOT_ZONE) return false;
|
|
return !JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND);
|
|
});
|
|
const tries = lines
|
|
.map((bottom) => frame(s, ratio, bottom, headroom, tallest, others, inSubject, reason, minWidth, tight, true, reportage, balls))
|
|
.filter((c): c is Composition & { cost: number } => !!c);
|
|
return tries.reduce<(Composition & { cost: number }) | null>((a, b) => (!a || b.cost < a.cost ? b : a), null);
|
|
}
|
|
|
|
/**
|
|
* Recommended narrowest crop for a photo `width` px wide when deliveries need `minLongEdge` px.
|
|
* A large file used to be held at 35% of the frame, which on a modern body is about 4000 px and stops a
|
|
* tighter crop. 3000 px is enough: the export can go back up to 4000.
|
|
*/
|
|
export const CROP_FLOOR_PX = 3000;
|
|
export function minCropWidth(width: number, height: number, minLongEdge = 2400): number {
|
|
const long = Math.max(width, height);
|
|
const floor = Math.min(0.35, CROP_FLOOR_PX / long);
|
|
return Math.min(1, Math.max(floor, minLongEdge / long) * (width >= height ? 1 : height / width));
|
|
}
|
|
|
|
function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tallest: number, others: Detection[], inSubject: Detection[], reason: Composition["reason"], minWidth: number, tight = false, pinBottom = false, reportage = false, balls: readonly Box[] = []): (Composition & { cost: number }) | null {
|
|
const mainSharp = Math.max(...inSubject.map(sharp));
|
|
const keep = requiredBox(s, inSubject);
|
|
let best: { rect: Box; cost: number } | null = null;
|
|
for (let k = 0.35; k <= 1.0001; k += 0.025) {
|
|
// k: crop height as a fraction of the frame height; the width follows the aspect.
|
|
let ch = Math.min(1, k);
|
|
let cw = ch * ratio;
|
|
if (cw > 1) {
|
|
cw = 1;
|
|
ch = cw / ratio;
|
|
}
|
|
if (cw < w(keep) + 0.01 || ch < mustBottom - s.y0 + headroom || cw < minWidth - 1e-9) continue;
|
|
// Vertical positions: from the heads just under the top edge to the bottom of the subject just above the
|
|
// bottom edge (all the spare height above them: the crowd, the stands, never a strip of empty pitch below).
|
|
const top = s.y0 - headroom;
|
|
const spare = Math.max(0, ch - (mustBottom - top));
|
|
for (let i = 0; i <= 24; i++) {
|
|
const x0 = Math.min(Math.max(0, keep.x1 - cw + (i / 24) * (cw - w(keep))), 1 - cw);
|
|
// A plan pins the bottom on the waist or the thigh. Spare height goes above the head, never down into the legs.
|
|
const rows = pinBottom ? 1 : 21;
|
|
for (let j = 0; j < rows; j++) {
|
|
const y0 = pinBottom ? mustBottom - ch : Math.min(Math.max(0, top - (j / 20) * spare), 1 - ch);
|
|
if (y0 < -1e-9) continue;
|
|
const r = { x0, y0, x1: x0 + cw, y1: y0 + ch };
|
|
if (r.y1 > 1 + 1e-6) continue;
|
|
if (r.x0 > keep.x0 + 1e-6 || r.x1 < keep.x1 - 1e-6 || r.y0 > Math.max(0, s.y0 - headroom) + 1e-6 || r.y1 < mustBottom - 1e-6) continue;
|
|
if (pinBottom && r.y1 > mustBottom + 0.02) continue;
|
|
if (cutsFoot(r, inSubject)) continue;
|
|
if (cutsKeptFoot(r, others)) continue;
|
|
if (cutsKeptHands(r, others)) continue;
|
|
if (clipsBall(r, balls)) continue;
|
|
if (cutsHead(r, [...inSubject, ...others], tallest)) continue;
|
|
// Reportage: a person who is in the crop is in whole. A plan may end at the waist; it may not take the head
|
|
// off, and it may not cut someone down the side. The primary crop keeps their feet too.
|
|
if (reportage && slicesOther(r, others, mainSharp, tallest, pinBottom)) continue;
|
|
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight) + jointCost(r, inSubject, others, mainSharp);
|
|
if (!best || c < best.cost) best = { rect: r, cost: c };
|
|
}
|
|
}
|
|
}
|
|
if (!best) return null;
|
|
return { rect: best.rect, subject: s, reason, people: inSubject.length, cost: best.cost };
|
|
}
|
|
|
|
function cost(r: Box, s: Box, others: Detection[], ch: number, tallest: number, mainSharp: number, ratio: number, inSubject: Detection[], tight = false): number {
|
|
let c = 0;
|
|
// Sharp people cut in half by the crop's edge look wrong; blurred ones (foreground, background) don't matter.
|
|
for (const p of others) {
|
|
const f = overlap(r, p) / Math.max(area(p), 1e-9);
|
|
// Only a hand or a foot of someone who is not being photographed: leave it out. A whole other person stays
|
|
// on the rule below (in, or out, never sliced).
|
|
if (strayLimb(p, tallest)) {
|
|
if (f > 0.02) c += TUNING.wStray * f;
|
|
continue;
|
|
}
|
|
if (f <= 0.03 || f >= 0.95) continue;
|
|
const focus = Math.min(1, sharp(p) / Math.max(mainSharp, 1e-6));
|
|
if (focus < TUNING.inFocus) continue;
|
|
const size = Math.min(1, h(p) / tallest);
|
|
c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f));
|
|
}
|
|
if (tight) {
|
|
// The agencies' framing: the subject as tall as the crop (or a little taller, legs cut mid-limb).
|
|
c += TIGHT.wFill * Math.abs(tallest / ch - TIGHT.fillAt);
|
|
} else {
|
|
// Peter's usual crop is two thirds of the frame; bigger only when the subject needs it.
|
|
const k = Math.max(ch, w(r) / ratio);
|
|
c += TUNING.wScale * Math.abs(k - TUNING.usualScale);
|
|
// The subject fills a good part of the height (people tall in the frame).
|
|
c += TUNING.wFill * Math.max(0, TUNING.fillAt - tallest / ch);
|
|
}
|
|
// Centred across.
|
|
c += TUNING.wCentre * (Math.abs(cx(s) - cx(r)) / w(r));
|
|
// Heads a little below the top: not touching it, not floating in empty space.
|
|
const head = (s.y0 - r.y0) / ch;
|
|
c += TUNING.wHead * (Math.max(0, TUNING.headMin - head) + Math.max(0, head - (tight ? TIGHT.headMax : TUNING.headMax)));
|
|
// The upper body (chest, faces) near the middle, a little above it, as a photographer frames: not the knees in
|
|
// the middle with a strip of grass below.
|
|
const main = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
|
const chest = (main.y0 + 0.3 * h(main) - r.y0) / ch;
|
|
c += TUNING.wChest * Math.abs(chest - (tight ? TIGHT.chestAt : TUNING.chestAt));
|
|
// Empty space under the subject (pitch, floor) is the first thing an editor crops away.
|
|
const below = (r.y1 - Math.min(s.y1, r.y1)) / ch;
|
|
c += TUNING.wBelow * Math.max(0, below - TUNING.belowMax);
|
|
return c;
|
|
}
|
|
|
|
/**
|
|
* A bottom edge through the foot (below mid-shin, above the sole). The sole itself, or anything below it,
|
|
* keeps the whole foot. A body that already runs off the photo can still be cut mid-shin, never through the shoe.
|
|
*/
|
|
function cutsFoot(r: Box, people: Detection[]): boolean {
|
|
for (const p of people) {
|
|
if (r.x1 <= p.x0 || r.x0 >= p.x1) continue;
|
|
if (r.y1 >= p.y1 - 1e-6) continue;
|
|
if ((r.y1 - p.y0) / h(p) > FOOT_ZONE) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* A person the crop has already decided to keep, whose foot is whole in the photo. Including the leg and
|
|
* stopping on the shoe is the same as cutting the foot.
|
|
*/
|
|
function cutsKeptFoot(r: Box, people: Detection[]): boolean {
|
|
for (const p of people) {
|
|
if (p.y1 >= FEET_IN_FRAME) continue;
|
|
const widthIn = Math.max(0, Math.min(r.x1, p.x1) - Math.max(r.x0, p.x0)) / Math.max(w(p), 1e-9);
|
|
if (widthIn < 0.85) continue;
|
|
if (r.y1 >= p.y1 - 1e-6) continue;
|
|
if ((r.y1 - p.y0) / Math.max(h(p), 1e-6) > FOOT_ZONE) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** Same person, kept in the crop: the side edge may not pass through the hands that stick out of the torso. */
|
|
function cutsKeptHands(r: Box, people: Detection[]): boolean {
|
|
for (const p of people) {
|
|
const widthIn = Math.max(0, Math.min(r.x1, p.x1) - Math.max(r.x0, p.x0)) / Math.max(w(p), 1e-9);
|
|
if (widthIn < 0.85) continue;
|
|
const padded = withHands(p);
|
|
if (r.x0 > padded.x0 + 1e-6 || r.x1 < padded.x1 - 1e-6) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* A team standing in a row: similar height, feet on the same line, spread across the frame. One player
|
|
* filling the picture is not this. A half body at the edge is not a person in the row.
|
|
*/
|
|
function openCast(people: Detection[]): Detection[] | null {
|
|
const usable = people.filter((p) => !sliver(p));
|
|
if (usable.length < OPEN_PEOPLE) return null;
|
|
const heights = usable.map(h).sort((a, b) => a - b);
|
|
const median = heights[Math.floor(heights.length / 2)]!;
|
|
const tall = heights[heights.length - 1]!;
|
|
if (tall > 0.7 && tall > 1.45 * median) return null;
|
|
const row = usable.filter((p) => h(p) >= 0.62 * median && h(p) <= 1.45 * median);
|
|
if (row.length < OPEN_PEOPLE) return null;
|
|
const bases = [...row.map((p) => p.y1)].sort((a, b) => a - b);
|
|
const mid = bases[Math.floor(bases.length / 2)]!;
|
|
const level = row.filter((p) => Math.abs(p.y1 - mid) <= Math.max(0.1, 0.22 * median));
|
|
if (level.length < OPEN_PEOPLE) return null;
|
|
const span = Math.max(...level.map((p) => p.x1)) - Math.min(...level.map((p) => p.x0));
|
|
if (span < OPEN_SPAN) return null;
|
|
return level;
|
|
}
|
|
|
|
/** A wide photograph of many small figures. It stays wide: there is no single player to cut down to. */
|
|
function widePlan(people: Detection[]): Detection[] | null {
|
|
const usable = people.filter((p) => !sliver(p));
|
|
if (usable.length < 5) return null;
|
|
const tall = Math.max(...usable.map(h));
|
|
if (tall > 0.5) return null;
|
|
const span = Math.max(...usable.map((p) => p.x1)) - Math.min(...usable.map((p) => p.x0));
|
|
if (span < 0.55) return null;
|
|
return usable;
|
|
}
|
|
|
|
/**
|
|
* The crop starts below the head of a person who is otherwise in it. A large person counts even when they are
|
|
* a little less sharp (stood in the shade): their head is not a stray hand.
|
|
*/
|
|
function cutsHead(r: Box, people: Detection[], tallest: number): boolean {
|
|
for (const p of people) {
|
|
if (h(p) < 0.5 * tallest || strayLimb(p, tallest)) continue;
|
|
if (r.x1 <= p.x0 || r.x0 >= p.x1) continue;
|
|
if (overlap(r, p) / Math.max(area(p), 1e-9) < 0.35) continue;
|
|
if (r.y0 > p.y0 + 0.03 * h(p)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Someone the crop keeps a piece of, but not as a photograph would. In, or out: never a slice through the body,
|
|
* never the body without the head. A deliberate half or three-quarter (allowLegs) may end at the waist.
|
|
*/
|
|
function slicesOther(r: Box, others: Detection[], mainSharp: number, subjectTallest: number, allowLegs: boolean): boolean {
|
|
const tallest = Math.max(subjectTallest, 0, ...others.map(h));
|
|
for (const p of others) {
|
|
if (sharp(p) < 0.35 * mainSharp || strayLimb(p, tallest)) continue;
|
|
const widthIn = Math.max(0, Math.min(r.x1, p.x1) - Math.max(r.x0, p.x0)) / Math.max(w(p), 1e-9);
|
|
if (widthIn < 0.12) continue;
|
|
if (widthIn < 0.9) return true;
|
|
if (r.y0 > p.y0 + 0.05 * h(p)) return true;
|
|
if (!allowLegs && r.y1 < p.y1 - 0.04 * h(p)) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/** A short box against the photo edge: a hand or a foot of someone who is not the subject. */
|
|
function strayLimb(p: Detection, tallest: number): boolean {
|
|
if (h(p) >= STRAY_HEIGHT * tallest) return false;
|
|
return p.x0 < 0.02 || p.x1 > 0.98 || p.y0 < 0.02 || p.y1 > 0.98;
|
|
}
|
|
|
|
/**
|
|
* Where a sequence plan may end on this person, measured on their own box. A line taken from the top of the
|
|
* group lands on the neck of whoever stands lower. The hands stay: at the hip on a standing figure, and at the
|
|
* bottom of the box when the person is leaning (the box is wide because the arms are in it). Null: this plan
|
|
* would cut the neck or the hands, so the open crop stands and no second frame is made just to show a worse one.
|
|
*/
|
|
function planCut(p: Detection, at: number): number | null {
|
|
const line = p.y0 + at * h(p);
|
|
if (line < p.y0 + 0.28 * h(p)) return null;
|
|
if (line < p.y0 + 0.55 * h(p)) return null;
|
|
if (h(p) < 1.8 * Math.max(w(p), 1e-6) && line < p.y1 - 0.08 * h(p)) return null;
|
|
if (p.fragment && line < p.y1 - 0.04 * h(p)) return null;
|
|
return line;
|
|
}
|
|
|
|
/**
|
|
* A second or third plan of the same moment (half body, three-quarter). The bottom sits below the hands, the
|
|
* head stays, and the foot is not where the cut falls. Null when that plan would cut a neck or a hand, or cannot
|
|
* keep the delivery's resolution: the photo keeps the open crop.
|
|
*/
|
|
export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null {
|
|
const reportage = opts.context === "reportage";
|
|
const faces = opts.faces ?? [];
|
|
const found = findSubject(reportage ? forReportage(d, faces) : d, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
|
if (!found) return null;
|
|
const { box: s, reason, people: inSubject } = found;
|
|
// A lineup is one photograph. A half or a three-quarter of it would cut the row.
|
|
if (inSubject.length >= OPEN_PEOPLE && w(s) >= OPEN_SPAN) return null;
|
|
const tallest = Math.max(...inSubject.map(h));
|
|
const at = PLANS[which];
|
|
if (at > FOOT_ZONE || JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND)) return null;
|
|
const lines = inSubject.map((p) => planCut(p, at));
|
|
if (lines.some((line) => line === null)) return null;
|
|
const bottom = Math.max(...(lines as number[]));
|
|
const ratio = (aspect ?? d.width / d.height) * (d.height / d.width);
|
|
const others = d.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
|
|
const balls = d.balls.filter((b) => b.score >= MIN_BALL);
|
|
const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage, balls);
|
|
if (!made) return null;
|
|
if (made.rect.y1 > bottom + 0.025) return null;
|
|
return made.rect;
|
|
}
|
|
|
|
/** Crop edges that cross a body at a joint (ankle, knee, hip, neck): the "amputation" look. */
|
|
function jointCost(r: Box, subject: Detection[], others: Detection[], mainSharp: number): number {
|
|
let c = 0;
|
|
const bodies = [...subject, ...others.filter((p) => sharp(p) >= TUNING.inFocus * mainSharp)];
|
|
for (const p of bodies) {
|
|
// Only edges that actually cut through this person, horizontally inside their box.
|
|
if (r.x1 <= p.x0 || r.x0 >= p.x1) continue;
|
|
for (const edge of [r.y0, r.y1]) {
|
|
if (edge <= p.y0 || edge >= p.y1) continue;
|
|
const at = (edge - p.y0) / h(p);
|
|
if (JOINTS.some((j) => Math.abs(at - j) < JOINT_BAND)) c += TUNING.wJoint * Math.min(1, h(p) / 0.4);
|
|
}
|
|
}
|
|
return c;
|
|
}
|
|
|
|
/** People inside the subject box (a duel, a celebration: more than one). */
|
|
export function peopleIn(d: Detections, subject: Box): number {
|
|
return d.people.filter((p) => p.x0 >= subject.x0 - 1e-9 && p.x1 <= subject.x1 + 1e-9 && p.y0 >= subject.y0 - 1e-9 && p.y1 <= subject.y1 + 1e-9).length;
|
|
}
|
|
|
|
/**
|
|
* How good a frame is, to pick the best of a burst (docs/photo-editing-rules.md §3): the subject in focus (no motion
|
|
* blur), big enough, with the ball when there is one. Only meaningful between frames of the same burst.
|
|
*/
|
|
export function frameScore(d: Detections, c: Composition | null): number {
|
|
if (!c) return 0;
|
|
const subject = d.people.filter((p) => p.x0 >= c.subject.x0 - 1e-9 && p.x1 <= c.subject.x1 + 1e-9 && p.y0 >= c.subject.y0 - 1e-9 && p.y1 <= c.subject.y1 + 1e-9);
|
|
const focus = Math.max(0, ...subject.map((p) => p.focus ?? 0));
|
|
const tallest = Math.max(0, ...subject.map(h));
|
|
return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1);
|
|
}
|