A single figure with empty floor — someone walking, a suitcase beside them — is the subject. The crop keeps the body and what they carry. A conversation, a distant figure, and a frame that is already full stay as shot.
1086 lines
53 KiB
TypeScript
1086 lines
53 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 is reportage. One clear person is the subject, even with empty floor around them
|
||
* (someone walking, a suitcase beside them): the crop keeps the whole body and what they carry, and
|
||
* cuts that empty floor. It is not a sports fill. A conversation stays as framed. A distant figure
|
||
* (under about a fifth of the frame) is the place. A figure that already fills the frame stays.
|
||
* A frame the camera already closed is only finished (mid-limb). A person already cut off at the edge
|
||
* is left out.
|
||
* - "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[];
|
||
/** Suitcase, handbag or backpack next to a person. Part of the subject, not scenery. */
|
||
carried?: 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,
|
||
/** Horizontal lead room: how hard to pull the subject off-centre toward their back. */
|
||
wLead: 1.4,
|
||
/** Where the subject sits in the crop when facing right (more space on the right). */
|
||
leadRight: 0.38,
|
||
/** Where the subject sits in the crop when facing left. */
|
||
leadLeft: 0.62,
|
||
/** Bright / ad clutter on a crop edge relative to the interior. */
|
||
wEdgeClutter: 2.2,
|
||
/**
|
||
* How hard to push away from the delivery floor (`minLongEdge` / `CROP_FLOOR_PX`). A crop that only works
|
||
* near that floor is a bad read of the photo — prefer a wider frame or leave it as shot.
|
||
*/
|
||
wFloor: 3.5,
|
||
/** Prefer another burst frame when the planned crop is this tight (span of the longer crop side). */
|
||
scoreComfortFrom: 0.5,
|
||
scoreComfortSpan: 0.35,
|
||
};
|
||
|
||
/**
|
||
* 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;
|
||
/**
|
||
* A person under half the picture is a long shot: the place is what was photographed.
|
||
* The same line picture editors draw between a long shot and a full-length.
|
||
*/
|
||
const LONG_SHOT = 0.5;
|
||
/**
|
||
* A prime at least this long cannot zoom. On one full-length the crop may come in to PRIME_STEP,
|
||
* the zoom the lens could not make. Shorter primes and zooms stay with the frame as shot.
|
||
*/
|
||
const LONG_PRIME_MM = 100;
|
||
/** One step in from the photograph. Not the sports fill: the same picture, a little closer. */
|
||
const PRIME_STEP = 0.85;
|
||
/**
|
||
* Among reportage crops of the same size, a slight pull toward the subject.
|
||
* Smaller than one step of the size search (0.025), so it never closes a frame to centre it.
|
||
*/
|
||
const FRAME_TIE = 0.02;
|
||
|
||
/** 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;
|
||
/**
|
||
* The lens that made the frame. A long prime may step closer on a single full-length.
|
||
* A zoom, or an unknown lens, does not: the photographer could have zoomed, so the space is the picture.
|
||
*/
|
||
lens?: LensHint | null;
|
||
/**
|
||
* How much brighter/more saturated a crop's edge bands are than its interior (0 = clean).
|
||
* Used to prefer a cleaner frame without changing the photograph's aspect.
|
||
*/
|
||
edgeClutter?: (rect: Box) => number;
|
||
}
|
||
|
||
/** What the file says about the lens. `range` equal at both ends is a prime. */
|
||
export interface LensHint {
|
||
focalLength?: number | null;
|
||
range?: readonly [number, number] | null;
|
||
name?: string | null;
|
||
}
|
||
|
||
/** Focal length, lens name and the EXIF lens range stored on a photo. */
|
||
export function lensHintFromExif(exif: unknown, focalLength: number | null, name: string | null): LensHint {
|
||
let range: [number, number] | null = null;
|
||
if (exif && typeof exif === "object" && "lensRange" in exif) {
|
||
const raw = (exif as { lensRange?: unknown }).lensRange;
|
||
if (Array.isArray(raw) && raw.length >= 2) {
|
||
const min = raw[0];
|
||
const max = raw[1];
|
||
if (typeof min === "number" && typeof max === "number" && Number.isFinite(min) && Number.isFinite(max)) {
|
||
range = [min, max];
|
||
}
|
||
}
|
||
}
|
||
return { focalLength, range, name };
|
||
}
|
||
|
||
/**
|
||
* A prime of 100mm or more. The photographer could not zoom in. A 70-200 at 135mm is not this:
|
||
* that lens still had room. Unknown lens: not this either.
|
||
*/
|
||
export function isLongPrime(lens: LensHint | null | undefined): boolean {
|
||
if (!lens) return false;
|
||
const focal = lens.focalLength;
|
||
if (focal == null || !Number.isFinite(focal) || focal < LONG_PRIME_MM) return false;
|
||
const range = lens.range;
|
||
if (range && range[0] > 0 && range[1] > 0) {
|
||
return Math.abs(range[0] - range[1]) < 1;
|
||
}
|
||
const name = lens.name ?? "";
|
||
if (/\d+\s*-\s*\d+/.test(name)) return false;
|
||
if (/\d+\s*mm/i.test(name)) return true;
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* A zoom parked at (or very near) its wide end: the photographer chose the wide plan on purpose
|
||
* (e.g. 15–35 at 15). Aggressive sports reframe is wrong — typically only straighten.
|
||
*/
|
||
export function isWideZoomOpen(lens: LensHint | null | undefined): boolean {
|
||
if (!lens) return false;
|
||
const focal = lens.focalLength;
|
||
if (focal == null || !Number.isFinite(focal)) return false;
|
||
const range = lens.range;
|
||
if (range && range[0] > 0 && range[1] > range[0] + 1) {
|
||
const span = range[1] - range[0];
|
||
const nearWide = focal <= range[0] + Math.max(2, 0.08 * span);
|
||
return nearWide;
|
||
}
|
||
const name = lens.name ?? "";
|
||
const m = name.match(/(\d+(?:\.\d+)?)\s*-\s*(\d+(?:\.\d+)?)/);
|
||
if (!m) return false;
|
||
const lo = Number(m[1]);
|
||
const hi = Number(m[2]);
|
||
if (!(hi > lo + 1)) return false;
|
||
return focal <= lo + Math.max(2, 0.08 * (hi - lo));
|
||
}
|
||
|
||
/**
|
||
* Horizontal facing for lead room: -1 left, +1 right, 0 unknown.
|
||
* Face offset on the body wins; otherwise the ball side relative to the subject.
|
||
*/
|
||
export function facingSide(subject: Box, faces: readonly Box[], ball: Box | null | undefined): -1 | 0 | 1 {
|
||
const head = { x0: subject.x0, y0: subject.y0, x1: subject.x1, y1: subject.y0 + 0.5 * (subject.y1 - subject.y0) };
|
||
let best: Box | null = null;
|
||
let bestO = 0;
|
||
for (const f of faces) {
|
||
const o = overlap(f, head) / Math.max(area(f), 1e-9);
|
||
if (o > 0.2 && o > bestO) {
|
||
best = f;
|
||
bestO = o;
|
||
}
|
||
}
|
||
if (best) {
|
||
const bias = cx(best) - cx(subject);
|
||
if (bias > 0.03) return 1;
|
||
if (bias < -0.03) return -1;
|
||
}
|
||
if (ball) {
|
||
const bias = cx(ball) - cx(subject);
|
||
if (bias > 0.04) return 1;
|
||
if (bias < -0.04) return -1;
|
||
}
|
||
return 0;
|
||
}
|
||
|
||
/** 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);
|
||
|
||
/** What the photograph already is. The photographer framed it; the size of the person is the plan. */
|
||
export type ShotIntent = "scene" | "figure" | "group" | "closed";
|
||
|
||
/**
|
||
* The plan a picture editor would name from the frame alone.
|
||
* A long shot is the place. A full-length or a group is finished when the bodies are whole.
|
||
* Closed means the camera already cut the body: the feet leave the picture and the person is large.
|
||
*/
|
||
export function shotIntent(subject: readonly Detection[]): ShotIntent | null {
|
||
const usable = subject.filter((p) => p.score >= MIN_PERSON && h(p) >= MIN_HEIGHT && !p.fragment && !sliver(p));
|
||
if (usable.length === 0) return null;
|
||
const tallestPerson = usable.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||
if (h(tallestPerson) < LONG_SHOT) return "scene";
|
||
const feetCut = usable.some((p) => p.y1 >= FEET_IN_FRAME);
|
||
if (feetCut) return "closed";
|
||
if (usable.length >= 2) return "group";
|
||
return "figure";
|
||
}
|
||
|
||
/** Someone the camera already left out: cut by the frame edge, and not a stray hand or foot. */
|
||
function edgeAccident(p: Detection, tallest: number): boolean {
|
||
if (!atEdge(p)) return false;
|
||
if (sliver(p)) return false;
|
||
if (strayLimb(p, tallest)) return false;
|
||
return true;
|
||
}
|
||
|
||
/**
|
||
* A person shorter than this is scenery in a place, not who the photo is about.
|
||
* Taller than this, alone in the frame, they are the subject — a suitcase and empty floor do not hide them.
|
||
*/
|
||
const CLEAR_PERSON = 0.22;
|
||
|
||
/**
|
||
* Reportage leaves the photograph when it is not one clear person with room around them.
|
||
* A conversation stays. A distant figure stays. A body that already fills the height stays.
|
||
* Someone the frame already cut off at the edge is not a reason to leave the rest.
|
||
*/
|
||
function leaveAsShot(inSubject: Detection[], others: Detection[]): boolean {
|
||
const intent = shotIntent(inSubject);
|
||
if (!intent || intent === "closed") return false;
|
||
const tallestPerson = inSubject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||
const tallest = h(tallestPerson);
|
||
if (others.some((p) => edgeAccident(p, tallest))) return false;
|
||
if (intent === "group") return true;
|
||
// Several people under half the frame: the place, or a wide shot. One person that size is the subject.
|
||
if (intent === "scene" && inSubject.length > 1) return true;
|
||
if (tallest < CLEAR_PERSON) return true;
|
||
if (tallestPerson.y0 <= 0.06 && tallestPerson.y1 >= 0.94) return true;
|
||
return false;
|
||
}
|
||
|
||
/** A bag or suitcase touching the person is part of the subject. One across the frame is not. */
|
||
function withCarried(box: Box, people: Detection[], carried: readonly Detection[] | undefined): Box {
|
||
if (!carried?.length) return box;
|
||
let out = box;
|
||
for (const item of carried) {
|
||
if (item.score < 0.35) continue;
|
||
let close = false;
|
||
for (const p of people) {
|
||
const gapX = Math.max(0, Math.max(p.x0, item.x0) - Math.min(p.x1, item.x1));
|
||
const gapY = Math.max(0, Math.max(p.y0, item.y0) - Math.min(p.y1, item.y1));
|
||
if (overlap(p, item) > 0 || (gapX < 0.12 && gapY < 0.15)) close = true;
|
||
}
|
||
if (close) out = union(out, item);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
/**
|
||
* 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));
|
||
// An outstretched arm holds the ball well outside the torso box. Half a body is not enough.
|
||
const arm = handball ? 0.9 * h(main) : 0.5 * h(main);
|
||
const near = balls.filter((b) => Math.abs(cx(b) - cx(main)) <= w(main) / 2 + arm && 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) {
|
||
// Sharp people big and close to the ball are in the duel. Soft / OOF bodies near the ball are scenery —
|
||
// they must not expand the subject box (docs/photo-editing-rules.md).
|
||
const contest = people.filter(
|
||
(p) =>
|
||
p === main ||
|
||
(!cutOff(p) &&
|
||
sharp(p) >= withMain * sharp(main) &&
|
||
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 detected = reportage ? forReportage(d, faces) : d;
|
||
const found = findSubject(detected, opts.focus, { reportage, sport: opts.sport ?? null, faces });
|
||
if (!found) return null;
|
||
const { reason, people: inSubject, ball } = found;
|
||
const s = withCarried(found.box, inSubject, d.carried);
|
||
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 = detected.people.filter((p) => p.score >= MIN_PERSON && !inSubject.includes(p));
|
||
// A conversation, a distant figure, or a body that already fills the frame stays as shot.
|
||
// One clear person does not: empty floor and a suitcase are not "no subject".
|
||
const primeFigure = reportage && isLongPrime(opts.lens) && shotIntent(inSubject) === "figure";
|
||
if (reportage && leaveAsShot(inSubject, others)) return null;
|
||
// Zoom at the wide end: the photographer opened on purpose — do not reframe (level only later).
|
||
if (isWideZoomOpen(opts.lens)) return null;
|
||
const headroom = 0.04 * tallest;
|
||
const lead = reportage ? 0 : facingSide(s, faces, ball ?? null);
|
||
const edgeClutter = opts.edgeClutter;
|
||
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;
|
||
// Near the delivery floor the subject was read too small / too far — do not force a super-crop.
|
||
const finish = (c: (Composition & { cost?: number }) | null): Composition | null => {
|
||
if (!c) return null;
|
||
if (minWidth > 0 && w(c.rect) <= minWidth * 1.08) return null;
|
||
return { ...c, ball: ball ?? 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, false, 0, edgeClutter) ??
|
||
frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, true, balls, false, 0, edgeClutter),
|
||
);
|
||
}
|
||
// 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. If the players do not fit in a tighter frame, the
|
||
// photograph stays: cutting the legs is not the way out.
|
||
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter)
|
||
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter)
|
||
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, true, false, false, balls, false, lead, edgeClutter);
|
||
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, lead, edgeClutter);
|
||
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, lead, edgeClutter);
|
||
if (cut) return finish(cut);
|
||
}
|
||
// Whole bodies, feet included. A little headroom gives way before a complete foot does.
|
||
// One person: score a real crop (empty floor goes). Do not prefer the untouched frame.
|
||
const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false)
|
||
?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false)
|
||
?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage, balls, primeFigure, lead, edgeClutter, false);
|
||
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, false, lead, edgeClutter));
|
||
}
|
||
|
||
/**
|
||
* 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[] = [], lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number): (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, false, lead, edgeClutter))
|
||
.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[] = [], closer = false, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number, holdFrame?: boolean): (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;
|
||
// Soft scraps and stray limbs: out of the crop in sport and reportage when possible.
|
||
if (overlapsStray(r, others, tallest)) continue;
|
||
if (overlapsSoftScrap(r, others, mainSharp, tallest)) continue;
|
||
if (reportage && overlapsEdgeCut(r, others, tallest)) continue;
|
||
// A player the photographer left in the picture stays in it. Cutting them out, or through the body,
|
||
// is not a crop. Soft scenery may still go.
|
||
if (dropsPlayer(r, others, mainSharp, tallest)) continue;
|
||
const stayWide = holdFrame ?? reportage;
|
||
const c = cost(r, s, others, ch, tallest, mainSharp, ratio, inSubject, tight, stayWide, closer, lead, edgeClutter, minWidth) + 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, trustFrame = false, closer = false, lead: -1 | 0 | 1 = 0, edgeClutter?: (rect: Box) => number, minWidth = 0): number {
|
||
let c = 0;
|
||
// Sharp people cut in half by the crop's edge look wrong. Soft scraps still cost when they sit in the frame.
|
||
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) || softScrap(p, mainSharp, 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) {
|
||
// Soft body left partly in: dirty frame — prefer the crop that puts them out.
|
||
c += TUNING.wStray * 0.6 * Math.min(f, 1 - f);
|
||
continue;
|
||
}
|
||
const size = Math.min(1, h(p) / tallest);
|
||
c += TUNING.wCut * focus * size * (0.3 + Math.min(f, 1 - f));
|
||
}
|
||
if (trustFrame) {
|
||
// The photograph as shot. A long prime may take one step in, still centred on the same picture.
|
||
const scale = Math.max(ch, w(r) / ratio);
|
||
let target = 1;
|
||
if (closer) target = PRIME_STEP;
|
||
c += Math.abs(scale - target);
|
||
let anchor = cx(s);
|
||
if (closer) anchor = 0.5;
|
||
const offCentre = Math.abs(anchor - cx(r)) / Math.max(w(r), 1e-6);
|
||
c += FRAME_TIE * offCentre;
|
||
return c;
|
||
}
|
||
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);
|
||
}
|
||
// Lead room when facing is known; otherwise centre.
|
||
let anchor = 0.5;
|
||
if (lead > 0) anchor = TUNING.leadRight;
|
||
else if (lead < 0) anchor = TUNING.leadLeft;
|
||
const subjectAt = (cx(s) - r.x0) / Math.max(w(r), 1e-6);
|
||
if (lead) c += TUNING.wLead * Math.abs(subjectAt - anchor);
|
||
else c += TUNING.wCentre * Math.abs(subjectAt - 0.5);
|
||
if (edgeClutter) c += TUNING.wEdgeClutter * edgeClutter(r);
|
||
// A crop that sits on the delivery floor is a bad evaluation — pay to stay wider.
|
||
if (minWidth > 0) {
|
||
const headroom = (w(r) - minWidth) / Math.max(minWidth, 1e-6);
|
||
if (headroom < 0.25) c += TUNING.wFloor * (0.25 - headroom);
|
||
}
|
||
// 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.
|
||
*/
|
||
/**
|
||
* A player who is clearly in the photograph: large in the frame, or nearly as tall as the subject.
|
||
* Not a distant figure, not a hand at the edge.
|
||
*/
|
||
function prominentPlayer(p: Detection, tallest: number): boolean {
|
||
if (sliver(p) || strayLimb(p, tallest)) return false;
|
||
if (h(p) >= 0.42) return true;
|
||
if (h(p) >= 0.28 && h(p) >= 0.72 * tallest) return true;
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* The crop throws a player out or cuts through them. A prominent player has to stay whole.
|
||
* A smaller one may be left out, but not sliced.
|
||
*/
|
||
function dropsPlayer(r: Box, others: Detection[], mainSharp: number, tallest: number): boolean {
|
||
for (const p of others) {
|
||
if (sliver(p) || strayLimb(p, tallest)) continue;
|
||
if (sharp(p) < 0.45 * mainSharp) continue;
|
||
if (edgeAccident(p, tallest)) continue;
|
||
const share = overlap(r, p) / Math.max(area(p), 1e-9);
|
||
const widthIn = Math.max(0, Math.min(r.x1, p.x1) - Math.max(r.x0, p.x0)) / Math.max(w(p), 1e-9);
|
||
if (prominentPlayer(p, tallest)) {
|
||
if (share < 0.9) return true;
|
||
if (r.y0 > p.y0 + 0.04 * h(p)) return true;
|
||
if (p.y1 < FEET_IN_FRAME && r.y1 < p.y1 - 0.05 * h(p)) return true;
|
||
continue;
|
||
}
|
||
if (share > 0.08 && share < 0.9) return true;
|
||
if (widthIn > 0.15 && widthIn < 0.88) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
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;
|
||
}
|
||
|
||
/** Soft / tiny non-subject: scenery that should leave the crop when possible. */
|
||
function softScrap(p: Detection, mainSharp: number, tallest: number): boolean {
|
||
if (strayLimb(p, tallest) || sliver(p)) return true;
|
||
if (h(p) < 0.28 * tallest) return true;
|
||
if (sharp(p) < TUNING.inFocus * Math.max(mainSharp, 1e-6)) return true;
|
||
return false;
|
||
}
|
||
|
||
function overlapsStray(r: Box, others: Detection[], tallest: number): boolean {
|
||
for (const p of others) {
|
||
if (!strayLimb(p, tallest) && !sliver(p)) continue;
|
||
const share = overlap(r, p) / Math.max(area(p), 1e-9);
|
||
if (share > 0.02) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/** Soft or tiny body left only partly in the crop — prefer the tighter clean frame. */
|
||
function overlapsSoftScrap(r: Box, others: Detection[], mainSharp: number, tallest: number): boolean {
|
||
for (const p of others) {
|
||
if (!softScrap(p, mainSharp, tallest)) continue;
|
||
if (strayLimb(p, tallest) || sliver(p)) continue;
|
||
const share = overlap(r, p) / Math.max(area(p), 1e-9);
|
||
if (share > 0.04 && share < 0.85) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function overlapsEdgeCut(r: Box, others: Detection[], tallest: number): boolean {
|
||
for (const p of others) {
|
||
if (!edgeAccident(p, tallest)) continue;
|
||
const share = overlap(r, p) / Math.max(area(p), 1e-9);
|
||
if (share > 0.05) return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
/**
|
||
* 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 detected = reportage ? forReportage(d, faces) : d;
|
||
const found = findSubject(detected, 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 = detected.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, false, 0, opts.edgeClutter);
|
||
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));
|
||
let peak = 1;
|
||
if (c.reason === "ball" && c.ball && subject.length) {
|
||
// Closer ball-to-body = peak contact; approach / follow-through lose.
|
||
const body = subject.reduce((a, b) => (h(b) > h(a) ? b : a));
|
||
const dist = Math.hypot(cx(c.ball) - cx(body), cy(c.ball) - cy(body)) / Math.max(h(body), 1e-6);
|
||
const touch = overlap(c.ball, body) > 0;
|
||
peak = touch ? 1.35 : Math.max(0.75, 1.25 - dist);
|
||
}
|
||
// A frame that only works with a heavy reframe loses to one the photographer already framed.
|
||
const cropSpan = Math.max(w(c.rect), h(c.rect));
|
||
const comfort = Math.min(1, Math.max(0, (cropSpan - TUNING.scoreComfortFrom) / TUNING.scoreComfortSpan));
|
||
const cropWeight = 0.7 + 0.3 * comfort;
|
||
return Math.log10(1 + focus) * (0.6 + Math.min(1, tallest / 0.5)) * (c.reason === "ball" ? 1.15 : 1) * peak * cropWeight;
|
||
}
|