diff --git a/apps/api/src/autopilot/service.ts b/apps/api/src/autopilot/service.ts index b83ce7e..a4c9026 100644 --- a/apps/api/src/autopilot/service.ts +++ b/apps/api/src/autopilot/service.ts @@ -144,9 +144,12 @@ export class AutopilotService { const focus = focusFromExifJson(photo.exif) ?? (existsSync(focusFile) ? await readFocusPoint(focusFile) : null); const minWidth = minCropWidth(W, H, settings.minLongEdge); const context = reportage ? "reportage" : "sport"; - const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context }) : null; + // Faces tell a whole figure from a bust (a head in a car window, a torso). They may not be ready yet; + // the crop still refuses to slice a person who is only a little less sharp. + const faces = reportage ? (await db.face.findMany({ where: { photoId }, select: { x0: true, y0: true, x1: true, y1: true } })).map((f) => ({ x0: f.x0, y0: f.y0, x1: f.x1, y1: f.y1 })) : []; + const composition = detections ? compose(detections, aspect, { minWidth, focus, framing: settings.framing, context, faces }) : null; const wideComposition = detections && !reportage && settings.framing === "tight" ? compose(detections, aspect, { minWidth, focus, framing: "full", context: "sport" }) : null; - const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context }) } : null; + const plans = reportage && detections ? { half: planCrop(detections, "half", aspect, { minWidth, focus, context, faces }), threeQuarter: planCrop(detections, "threeQuarter", aspect, { minWidth, focus, context, faces }) } : null; let crop: Box | null = null; if (settings.crop && composition) { // Photographers who always tighten the autopilot's crop get it tighter (never cutting into the subject). diff --git a/apps/api/src/composition/compose.ts b/apps/api/src/composition/compose.ts index 7609460..11a93d4 100644 --- a/apps/api/src/composition/compose.ts +++ b/apps/api/src/composition/compose.ts @@ -11,6 +11,7 @@ * - 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. A leg is * cut only when the foot already leaves the photo. 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. * @@ -33,6 +34,11 @@ export interface Detection extends Box { 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 { @@ -114,6 +120,8 @@ export interface ComposeOptions { 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[]; } /** A generic event: no opponent and no fixture. The crop is a person, not a match. */ @@ -136,20 +144,62 @@ function overlap(a: Box, b: Box): number { const atEdge = (b: Box) => b.x0 < 0.01 || b.x1 > 0.99; const sharp = (p: Detection) => p.sharpness ?? 1; +/** + * 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 }): { 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; // The main subject: the person the camera focused on, when that point lands on someone. Otherwise in focus - // first, then a reasonable size, then whole in the photo. + // first, then a reasonable size, then whole in the photo. In reportage a whole figure beats a sharper bust. 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 aimed = focus ? personAtFocus(people, focus) : null; - const main = aimed ?? people.reduce((a, b) => (weight(b) > weight(a) ? b : a)); + const whole = opts?.reportage ? people.filter((p) => !p.fragment) : people; + const pool = whole.length ? whole : people; + const aimed = focus ? personAtFocus(pool, focus) : null; + const main = aimed ?? pool.reduce((a, b) => (weight(b) > weight(a) ? b : a)); if (!aimed && weight(main) < 0.05) return null; // Reportage keeps a conversation together: someone in the shade is still part of it. A match stays stricter. + // Someone who merely touches the edge but is a whole figure is still in the conversation. A short box on the + // edge is a stray hand or foot. const withMain = opts?.reportage ? 0.35 : TUNING.inFocus; const reach = opts?.reportage ? 0.85 : 0.45; - const focused = people.filter((p) => sharp(p) >= withMain * sharp(main) && !atEdge(p)); + const leaves = (p: Detection) => atEdge(p) && (!opts?.reportage || h(p) < 0.5); + const focused = people.filter((p) => sharp(p) >= withMain * sharp(main) && !leaves(p)); // A ball in play near the subject: in the hands, at the feet, or in the air just above. const balls = d.balls.filter((b) => b.score >= MIN_BALL && w(b) < 0.6 * h(main) && w(b) > 0.02 * h(main)); @@ -168,8 +218,12 @@ export function findSubject(d: Detections, focus?: FocusHint | null, opts?: { re while (grown) { grown = false; for (const p of focused) { - if (group.includes(p) || h(p) < 0.6 * h(main) || h(p) > 1.7 * h(main)) continue; - const near = group.some((g) => overlap(g, p) > 0 || Math.max(g.x0, p.x0) - Math.min(g.x1, p.x1) < reach * h(main)); + 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; @@ -200,7 +254,8 @@ function personAtFocus(people: Detection[], focus: FocusHint): Detection | null * 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 found = findSubject(d, opts.focus, { reportage: opts.context === "reportage" }); + const reportage = opts.context === "reportage"; + const found = findSubject(reportage ? forReportage(d, opts.faces ?? []) : d, opts.focus, { reportage }); 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 @@ -235,9 +290,9 @@ export function compose(d: Detections, aspect: number | null = null, opts: Compo } // Whole bodies, feet included. A little headroom gives way before a complete foot does. Mid-thigh only when // the foot already leaves the photo, or the whole body cannot fit at all. - const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth) - ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth) - ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth); + const whole = frame(s, ratio, sole, headroom, tallest, others, inSubject, reason, minWidth, false, false, reportage) + ?? frame(s, ratio, sole, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage) + ?? frame(s, ratio, s.y1, 0, tallest, others, inSubject, reason, minWidth, false, false, reportage); if (whole || feetIn) return whole; return frame(s, ratio, s.y0 + MID_THIGH * tallest, headroom, tallest, others, inSubject, reason, minWidth); } @@ -254,7 +309,7 @@ export function minCropWidth(width: number, height: number, minLongEdge = 2400): 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): (Composition & { cost: number }) | null { +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): (Composition & { cost: number }) | null { const mainSharp = Math.max(...inSubject.map(sharp)); let best: { rect: Box; cost: number } | null = null; for (let k = 0.35; k <= 1.0001; k += 0.025) { @@ -283,6 +338,9 @@ function frame(s: Box, ratio: number, mustBottom: number, headroom: number, tall if (pinBottom && r.y1 > mustBottom + 0.02) continue; if (cutsFoot(r, inSubject)) 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 }; } @@ -362,6 +420,23 @@ function cutsHead(r: Box, people: Detection[], tallest: number): boolean { 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; @@ -374,7 +449,8 @@ function strayLimb(p: Detection, tallest: number): boolean { * keep the delivery's resolution. */ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: number | null = null, opts: ComposeOptions = {}): Box | null { - const found = findSubject(d, opts.focus, { reportage: opts.context === "reportage" }); + const reportage = opts.context === "reportage"; + const found = findSubject(reportage ? forReportage(d, opts.faces ?? []) : d, opts.focus, { reportage }); if (!found) return null; const { box: s, reason, people: inSubject } = found; const tallest = Math.max(...inSubject.map(h)); @@ -383,7 +459,7 @@ export function planCrop(d: Detections, which: keyof typeof PLANS, aspect: numbe const bottom = s.y0 + at * tallest; 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 made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true); + const made = frame(s, ratio, bottom, 0.04 * tallest, tallest, others, inSubject, reason, opts.minWidth ?? 0, true, true, reportage); if (!made) return null; if (made.rect.y1 > bottom + 0.025) return null; return made.rect; diff --git a/apps/api/src/composition/routes.ts b/apps/api/src/composition/routes.ts index ee1e6bb..c16fb6e 100644 --- a/apps/api/src/composition/routes.ts +++ b/apps/api/src/composition/routes.ts @@ -8,7 +8,7 @@ import { notFound } from "../lib/errors.js"; import type { LocalStorage } from "../storage/storage.js"; import { readFocusPoint } from "../ingest/exif.js"; import { focusFromExifJson } from "../ingest/focus.js"; -import { compose } from "./compose.js"; +import { compose, isReportage } from "./compose.js"; import { lazyDetector } from "./detect.js"; const Params = z.object({ photoId: z.uuid() }); @@ -26,7 +26,19 @@ export async function registerCompositionRoutes(app: FastifyInstance, deps: { db app.post("/v1/photos/:photoId/auto-crop", { preHandler: authenticate }, async (req, reply) => { const { photoId } = Params.parse(req.params); const { aspect } = Body.parse(req.body ?? {}); - const photo = await db.photo.findUnique({ where: { id: photoId }, select: { organizationId: true, sha256: true, status: true, exif: true, storageKey: true, originalStored: true } }); + const photo = await db.photo.findUnique({ + where: { id: photoId }, + select: { + organizationId: true, + sha256: true, + status: true, + exif: true, + storageKey: true, + originalStored: true, + faces: { select: { x0: true, y0: true, x1: true, y1: true } }, + event: { select: { away: true, fixtureId: true } }, + }, + }); if (!photo || photo.status !== "READY") throw notFound("photo_not_found"); await requireMembership(db, req, photo.organizationId, "PHOTOGRAPHER"); const pending = load(); @@ -35,6 +47,7 @@ export async function registerCompositionRoutes(app: FastifyInstance, deps: { db const detections = await (await pending).detect(preview); const original = photo.originalStored ? storage.resolve(photo.storageKey) : preview; const focus = focusFromExifJson(photo.exif) ?? (existsSync(original) ? await readFocusPoint(original) : null); - return { crop: compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus }) }; + const context = isReportage(photo.event) ? "reportage" : "sport"; + return { crop: compose(detections, aspect ? aspect[0] / aspect[1] : null, { focus, context, faces: photo.faces }) }; }); } diff --git a/apps/api/test/compose.test.ts b/apps/api/test/compose.test.ts index 8a20fd6..8c5066c 100644 --- a/apps/api/test/compose.test.ts +++ b/apps/api/test/compose.test.ts @@ -188,6 +188,59 @@ describe("reportage", () => { expect(c.rect.y1).toBeGreaterThan(subject.y1); }); + it("crops the whole person at the car, not the sharper face in the window", () => { + // PSR15838. The standing woman touches the frame edge and is a little less sharp. The face in the window is + // only a bust, and it used to become the crop: a band through the door. + const standing = { ...person(0.002, 0.175, 0.215, 0.995, 0.94), sharpness: 0.37 }; + const window = { ...person(0.42, 0.315, 0.605, 0.568, 0.76), sharpness: 1 }; + const faces = [ + { x0: 0.148, y0: 0.214, x1: 0.187, y1: 0.318 }, + { x0: 0.43, y0: 0.317, x1: 0.483, y1: 0.422 }, + ]; + const c = compose({ width: 6000, height: 4000, people: [standing, window], balls: [] }, null, { context: "reportage", faces, minWidth: 0.5 })!; + expect(c.rect.y0).toBeLessThanOrEqual(standing.y0 + 1e-6); + expect(c.rect.y1).toBeGreaterThan(standing.y1 - 1e-6); + expect(c.rect.x0).toBeLessThanOrEqual(standing.x0 + 1e-6); + const widthIn = Math.max(0, Math.min(c.rect.x1, window.x1) - Math.max(c.rect.x0, window.x0)) / (window.x1 - window.x0); + expect(widthIn < 0.12 || widthIn > 0.9).toBe(true); + if (widthIn > 0.9) { + expect(c.rect.y0).toBeLessThanOrEqual(window.y0); + expect(c.rect.y1).toBeGreaterThan(window.y1); + } + }); + + it("keeps the closer woman whole when the woman behind her is sharper", () => { + // PSR39046, the glass entrance. The foreground figure is taller; the crop used to be a band on the woman behind. + const front = { ...person(0.45, 0.23, 0.636, 0.933, 0.9), sharpness: 0.6 }; + const behind = { ...person(0.382, 0.304, 0.473, 0.667, 0.9), sharpness: 1 }; + const c = compose({ width: 6000, height: 4000, people: [front, behind], balls: [] }, null, { + context: "reportage", + minWidth: 0.5, + faces: [ + { x0: 0.5, y0: 0.25, x1: 0.56, y1: 0.34 }, + { x0: 0.4, y0: 0.31, x1: 0.45, y1: 0.4 }, + ], + })!; + expect(c.rect.y0).toBeLessThanOrEqual(front.y0 + 1e-6); + expect(c.rect.y1).toBeGreaterThan(front.y1 - 1e-6); + expect(c.rect.x0).toBeLessThanOrEqual(front.x0 + 1e-6); + expect(c.rect.x1).toBeGreaterThanOrEqual(front.x1 - 1e-6); + expect(c.rect.y1 - c.rect.y0).toBeGreaterThan(0.7); + }); + + it("still frames three whole figures standing in the middle of a wide shot", () => { + // PSR16148. The boxes already are the bodies. The crop stays around them, it does not become the whole frame. + const a = { ...person(0.368, 0.296, 0.463, 0.614), sharpness: 0.84 }; + const b = { ...person(0.477, 0.308, 0.547, 0.627), sharpness: 1 }; + const c0 = { ...person(0.535, 0.293, 0.615, 0.62), sharpness: 0.85 }; + const c = compose({ width: 6000, height: 4000, people: [a, b, c0], balls: [] }, null, { context: "reportage", minWidth: 0.5 })!; + expect(c.reason).toBe("group"); + expect(c.rect.y0).toBeLessThanOrEqual(0.296); + expect(c.rect.y1).toBeGreaterThanOrEqual(0.627); + expect(c.rect.y1 - c.rect.y0).toBeLessThan(0.75); + expect(c.rect.x1 - c.rect.x0).toBeLessThan(0.92); + }); + it("makes a half-body plan above the hips and a three-quarter above the knee, head included", () => { const p = person(0.4, 0.1, 0.55, 0.9); const d = { ...frame, people: [p], balls: [] }; diff --git a/docs/photo-editing-rules.md b/docs/photo-editing-rules.md index 284e62f..277f15a 100644 --- a/docs/photo-editing-rules.md +++ b/docs/photo-editing-rules.md @@ -44,7 +44,12 @@ Following the AP and NPPA codes: cut only when the foot already leaves the photo, or the whole body cannot fit: mid-thigh, or (with a ball in play) mid-shin, never at a joint, and never below the ball. - **Edges:** no slivers of other in-focus people at the crop edge: either in, or out. Blurred foreground and - background people don't count. + background people don't count. In reportage this is absolute for anyone still reasonably sharp: the crop + keeps their head, and the primary crop keeps their feet when those feet are in the photo. A half or a + three-quarter may end at the waist, and it still starts above the head. A band through the chest is never a crop. +- **A bust is not the subject.** A head in a window, or a torso the detector stopped at the chest, does not + beat a whole figure standing in the same photo. The taller person, closer to the camera, stays in the frame + even when someone behind them is a little sharper. - **Stray limbs:** a hand or a foot of someone who is not the subject, and nothing more of them, is cropped out so the frame stays clean. A whole other person is not that: they stay in or go out, they are not sliced. - **Headroom:** heads a little below the top edge, not touching it, not floating in empty space.