From 9ed025d1c65a7c46c21808d8c493d4a7d610aaea Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Fri, 31 Jul 2026 13:28:45 +0200 Subject: [PATCH] feat(reframe): layout for a screen with the camera composited into a corner One source: the whole screen (a game, a desktop) with the person composited into a corner. It is how OBS records and how any stream VOD looks, and it is the case screencast_layout got wrong: there the speaker band is a large crop taken AROUND the face, which on a full-screen source means more screen. On the measured Excel clip the output showed the same spreadsheet twice, whole and enlarged. What is needed is the inset's own rectangle, and finding it has three traps, each of which cost an iteration: - The inset does not touch two edges. YOLO returns an upper-body box that stops at the chest, so a webcam pinned to the right side measured 18% clear of the bottom and the "corner" filter threw it away. The test that works is subject SMALL and OFF-CENTRE. - A presenter standing in front of a screen passes any geometric filter. What separates them is that a composited inset DOES NOT MOVE: 3-11px between samples versus 316px for a person. With a plain min-max range the filter was too brittle (one lost sample killed three good detections), so it clusters around the median and requires a majority. - The height cannot be scaled from the detection: for a webcam of about 325x180 YOLO returned 246x86, and growing that shape still cut the head off. It is derived from the width assuming 16:9 and pinned to the edge the inset touches. The filtergraph keeps the screen at full width (the HUD and the edges are the content) and the camera band takes its height from the inset's real aspect: forcing a fixed ratio stretched faces 12% horizontally. Verified on 10 clips: finds the 4 with a composited camera and rejects the 6 without one (presenter in front of a screen, talking heads, presenter composited full-screen). The miss is a 720p clip whose webcam is too small for either detector. --- camera_inset.py | 284 +++++++++++++++++++++++++++++++++++++ tests/test_camera_inset.py | 120 ++++++++++++++++ 2 files changed, 404 insertions(+) create mode 100644 camera_inset.py create mode 100644 tests/test_camera_inset.py diff --git a/camera_inset.py b/camera_inset.py new file mode 100644 index 0000000..873e0b7 --- /dev/null +++ b/camera_inset.py @@ -0,0 +1,284 @@ +"""Find the webcam inset in a screen recording, and frame the two apart. + +The case: one source, the whole screen (a game, a desktop, an editor) with the +person composited into a corner. It is how OBS records and how every stream VOD +looks, and it is the case screencast_layout gets wrong. There the speaker band +is a large crop taken AROUND the face, which on a full-screen source means the +band is mostly more screen: measured on an Excel walkthrough, the output showed +the same spreadsheet twice, once whole and once enlarged. + +What this needs instead is the inset's own rectangle, so the two bands can hold +genuinely different things — screen above, person below. + +Finding it exactly is harder than it looks. The inset is not always a rectangle +(circles and clipped polygons are common), it has no reliable border, and on +gameplay the background moves as much as the person does, which rules out +temporal-variance tricks. What IS reliable is that the inset is anchored to a +corner and that a person detector fires inside it. So: locate the person, decide +which corner they are nearest, and grow a box from that corner until it covers +them with margin. +""" +import os + +CORNER_MARGIN = 0.20 # a subject this far from an edge (as a fraction of the + # frame) still counts as anchored to it + +# An inset subject is SMALL and OFF-CENTRE; a presenter filling the shot is +# neither. Requiring the detection to actually touch two edges was tried first +# and rejected: YOLO returns an upper-body box that stops at the chest, so a +# webcam pinned to the right edge measured 18% clear of the bottom and got +# thrown out. Measured on four real clips, these two properties separate the +# cases where "touching a corner" did not. +MAX_SUBJECT_HEIGHT = 0.35 # fraction of frame height +MIN_OFFSET = 0.18 # centre-to-centre distance, fraction of frame + +# How much bigger than the detected head/upper body the inset is assumed to be. +# A webcam frames head and shoulders, and detectors return the head or the upper +# body, so the box has to grow to reach the inset's real edges. +INSET_PADDING = float(os.environ.get("INSET_PADDING", "1.45")) + +# Guard rails as a fraction of frame height. Below the floor there is nothing +# worth showing; above the ceiling it stopped being an inset and the layout +# should not be used at all. +MIN_INSET_HEIGHT = 0.10 +MAX_INSET_HEIGHT = 0.38 + +# An inset is pinned to the same pixels for the whole recording; a presenter +# walks about. Spread of the detected centres, as a fraction of frame width, +# above which this is a person in a room rather than a composited camera. +# Measured on the two false positives this rule was written for: a real inset +# moved 3-11px across samples, a presenter 316px. +MAX_CENTRE_SPREAD = 0.05 + + +def nearest_corner(box, frame_w, frame_h): + """Which corner the subject sits in: (horizontal, vertical) as strings. + + Returns e.g. ("left", "bottom"). A subject in the middle of the frame is + reported by its nearest edges anyway; callers use `is_cornered` to reject. + """ + cx = box[0] + box[2] / 2.0 + cy = box[1] + box[3] / 2.0 + return ("left" if cx < frame_w / 2 else "right", + "top" if cy < frame_h / 2 else "bottom") + + +def is_cornered(box, frame_w, frame_h, margin=CORNER_MARGIN): + """True when the subject looks like a webcam inset rather than the shot. + + Small and off-centre, not "touches two edges": see MAX_SUBJECT_HEIGHT. + + This is a sanity filter, not the decision. Whether the video is a screen + recording with a camera in it at all is answered upstream by layout_picker; + a game character standing in a corner would pass this test, and is kept out + by the fact that nobody asked for this layout on that video. + """ + x, y, w, h = box + if h > frame_h * MAX_SUBJECT_HEIGHT: + return False + + cx = (x + w / 2.0) / frame_w + cy = (y + h / 2.0) / frame_h + off_centre = abs(cx - 0.5) >= MIN_OFFSET or abs(cy - 0.5) >= MIN_OFFSET + + near_edge = (x <= frame_w * margin or (x + w) >= frame_w * (1 - margin) + or y <= frame_h * margin or (y + h) >= frame_h * (1 - margin)) + return off_centre and near_edge + + +INSET_ASPECT = 16 / 9.0 + + +def inset_box(box, frame_w, frame_h, padding=None): + """Estimated inset rectangle (x, y, w, h) around a detected subject. + + Grown from the corner the subject is anchored to, so the box hugs the same + edges the inset does instead of floating around the face. + + The height comes from assuming a 16:9 inset rather than from scaling the + detection, because the detection is often a torso: YOLO returned a 246x86 + box for a webcam whose real rectangle was about 325x180, and padding that + shape upwards still cut the head off. Deriving the height from the width + and pinning the result to the corner reaches the top of the inset instead. + """ + padding = INSET_PADDING if padding is None else padding + x, y, w, h = box + horizontal, vertical = nearest_corner(box, frame_w, frame_h) + + new_w = min(frame_w, w * padding) + new_h = min(frame_h, max(h * padding, new_w / INSET_ASPECT)) + + # Anchor: keep the edge the subject is already near, grow the other way. + if horizontal == "left": + new_x = max(0, min(x - (new_w - w) / 2.0, frame_w - new_w)) + if x <= frame_w * CORNER_MARGIN: + new_x = 0 + else: + new_x = max(0, min(x + w + (new_w - w) / 2.0 - new_w, frame_w - new_w)) + if (x + w) >= frame_w * (1 - CORNER_MARGIN): + new_x = frame_w - new_w + + # Vertical growth is biased upwards: detectors return the head or the chest, + # and a portrait needs headroom, not more torso. Splitting the growth evenly + # cropped the top of the head off on real clips. + grow = new_h - h + if vertical == "top": + new_y = max(0, min(y - grow * 0.6, frame_h - new_h)) + if y <= frame_h * CORNER_MARGIN: + new_y = 0 + else: + # Pin to the bottom edge: the inset is there, and the detection sits + # somewhere inside it rather than at its top. + new_y = frame_h - new_h + if (y + h) < frame_h * (1 - CORNER_MARGIN): + new_y = max(0, min(y - grow * 0.6, frame_h - new_h)) + + return (int(round(new_x)), int(round(new_y)), + int(round(new_w)), int(round(new_h))) + + +def usable(box, frame_h, min_ratio=MIN_INSET_HEIGHT, max_ratio=MAX_INSET_HEIGHT): + """Whether an inset of this size is worth building a layout around.""" + return min_ratio * frame_h <= box[3] <= max_ratio * frame_h + + +def detect(video_path, samples=10): + """Median inset rectangle across sampled frames, or None. + + None means "no usable inset here", which callers must treat as "use another + layout" rather than as an error. + """ + import cv2 + import numpy as np + import main as m + import screencast_layout + + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return None + total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + frame_w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + frame_h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + if total <= 0 or not frame_w: + cap.release() + return None + + boxes = [] + try: + for i in range(samples): + cap.set(cv2.CAP_PROP_POS_FRAMES, int(i * total / samples)) + ok, frame = cap.read() + if not ok: + continue + # Faces first, body as fallback: a webcam inset is small, and on a + # 1080p source the face inside it is often too few pixels for + # BlazeFace even at full resolution, while YOLO still finds the + # person. + faces = screencast_layout.detect_faces_full_res(frame) + if faces: + box = max(faces, key=lambda c: c['score'])['box'] + else: + box = m.detect_person_yolo(frame) + if not box: + continue + if not is_cornered(box, frame_w, frame_h): + continue + boxes.append(inset_box(box, frame_w, frame_h)) + finally: + cap.release() + + if len(boxes) < max(3, samples // 3): + return None + + arr = np.array(boxes, dtype=float) + + # Stability gate. Without it, a presenter standing in front of a screen and + # an ordinary talking head both come back as "insets" and the layout puts a + # zoom of someone's face under a copy of the same shot. + # + # Measured against the plain min-to-max range first, which was far too + # brittle: one sample landing on a face elsewhere in the frame killed three + # genuine insets. So cluster around the median instead and require most + # detections to agree, which tolerates the odd stray without tolerating a + # subject that actually moves. + centres_x = arr[:, 0] + arr[:, 2] / 2.0 + centres_y = arr[:, 1] + arr[:, 3] / 2.0 + mid_x, mid_y = np.median(centres_x), np.median(centres_y) + tolerance = frame_w * MAX_CENTRE_SPREAD + close = ((np.abs(centres_x - mid_x) <= tolerance) + & (np.abs(centres_y - mid_y) <= tolerance)) + if close.sum() < max(3, 0.6 * len(boxes)): + return None + + arr = arr[close] + median = tuple(int(v) for v in np.median(arr, axis=0)) + if not usable(median, frame_h): + return None + return median + + +MAX_CAMERA_RATIO = 0.40 + + +def inset_filtergraph(orig_w, orig_h, out_w, out_h, box, camera_ratio=None): + """Screen on top at full width, the webcam inset below. + + The screen keeps its whole width, which is the point: a game HUD or a + desktop puts what matters at the edges. The inset is scaled up so the person + reads at a size the source never gave them. + + The camera band takes its height from the INSET'S OWN aspect ratio rather + than a fixed share of the frame. A fixed share was tried first and stretched + every face sideways: a 16:9 inset forced into a 2:1 band is a 12% horizontal + stretch, and it is immediately visible on a face. + """ + box_w = max(2, box[2]) + box_h = max(2, box[3]) + + if camera_ratio is not None: + cam_h = int(out_h * camera_ratio) + else: + cam_h = int(round(out_w * box_h / float(box_w))) + cam_h = min(cam_h, int(out_h * MAX_CAMERA_RATIO)) + cam_h -= cam_h % 2 + + screen_h = int(round(out_w * orig_h / float(orig_w))) + screen_h -= screen_h % 2 + screen_h = max(2, min(screen_h, out_h - cam_h - 2)) + + # Widen (or heighten) the crop to the band's aspect so the scale below is + # uniform. Clamped to the frame, so an inset hard against an edge simply + # keeps whatever it can reach. + target_aspect = out_w / float(cam_h) + x, y, w, h = box + if w / float(h) < target_aspect: + want_w = min(orig_w, int(round(h * target_aspect))) + x = int(round(x + w / 2.0 - want_w / 2.0)) + w = want_w + else: + want_h = min(orig_h, int(round(w / target_aspect))) + y = int(round(y + h / 2.0 - want_h / 2.0)) + h = want_h + x = max(0, min(x, orig_w - w)) + y = max(0, min(y, orig_h - h)) + + w -= w % 2 + h -= h % 2 + x -= x % 2 + y -= y % 2 + + filler_h = out_h - screen_h - cam_h + + return ( + f"[0:v]split=3[bga][sa][ca];" + # Blurred backdrop so the leftover strip is not a black bar. Scaled by + # HEIGHT: scaling a 16:9 source to 1080 wide gives 608 tall, and there + # is no 1920-tall crop to take out of that. + f"[bga]scale=-2:{out_h},crop=w=min(iw\\,{out_w}):h={out_h}," + f"scale={out_w}:{out_h},gblur=sigma=14[bg];" + f"[sa]scale={out_w}:{screen_h}[screen];" + f"[ca]crop=w={w}:h={h}:x={x}:y={y},scale={out_w}:{cam_h}[cam];" + f"[bg][screen]overlay=x=0:y={filler_h // 2}[withscreen];" + f"[withscreen][cam]overlay=x=0:y={filler_h // 2 + screen_h}," + f"setsar=1[v]" + ) diff --git a/tests/test_camera_inset.py b/tests/test_camera_inset.py new file mode 100644 index 0000000..7b22318 --- /dev/null +++ b/tests/test_camera_inset.py @@ -0,0 +1,120 @@ +from camera_inset import ( + INSET_ASPECT, + inset_box, + inset_filtergraph, + is_cornered, + nearest_corner, + usable, +) + +HD = (1920, 1080) + + +class TestNearestCorner: + def test_reads_the_quadrant(self): + assert nearest_corner([10, 10, 100, 100], *HD) == ("left", "top") + assert nearest_corner([1800, 980, 100, 100], *HD) == ("right", "bottom") + assert nearest_corner([1800, 10, 100, 100], *HD) == ("right", "top") + assert nearest_corner([10, 980, 100, 100], *HD) == ("left", "bottom") + + +class TestIsCornered: + def test_small_subject_against_an_edge_qualifies(self): + # A webcam pinned to the bottom-right: the exact case YOLO reports as a + # short, wide upper-body box. + assert is_cornered([1500, 900, 350, 120], *HD) + + def test_a_presenter_filling_the_shot_is_rejected(self): + assert not is_cornered([600, 100, 700, 900], *HD) + + def test_a_small_but_centred_subject_is_rejected(self): + assert not is_cornered([900, 500, 150, 100], *HD) + + def test_box_not_touching_the_bottom_still_counts(self): + # Measured failure: an inset pinned to the right edge sat 18% clear of + # the bottom because the detector stopped at the chest. Requiring two + # edges threw it away. + assert is_cornered([991 * 1.5, 502 * 1.5, 246 * 1.5, 86 * 1.5], *HD) + + def test_a_tall_subject_is_never_an_inset(self): + assert not is_cornered([1700, 100, 200, 800], *HD) + + +class TestInsetBox: + def test_box_stays_inside_the_frame(self): + for box in ([0, 980, 200, 100], [1800, 0, 120, 120], + [1850, 1000, 70, 80]): + x, y, w, h = inset_box(box, *HD) + assert 0 <= x and x + w <= 1920 + assert 0 <= y and y + h <= 1080 + + def test_bottom_anchored_inset_reaches_the_bottom_edge(self): + # The head sits above the detection, so the box must extend upward + # while staying pinned to the edge the inset actually touches. + x, y, w, h = inset_box([1500, 950, 300, 100], *HD) + assert y + h == 1080 + assert y < 950 + + def test_height_follows_the_16_9_assumption(self): + # A wide, flat torso detection must still yield a webcam-shaped box. + _x, _y, w, h = inset_box([1000, 800, 300, 80], *HD) + assert h >= w / INSET_ASPECT - 1 + + def test_box_grows_around_the_subject(self): + x, y, w, h = inset_box([1600, 900, 200, 120], *HD) + assert w >= 200 and h >= 120 + + +class TestUsable: + def test_rejects_a_speck(self): + assert not usable((0, 0, 40, 20), 1080) + + def test_rejects_something_that_fills_the_frame(self): + assert not usable((0, 0, 1920, 900), 1080) + + def test_accepts_a_normal_webcam(self): + assert usable((1500, 850, 350, 200), 1080) + + +class TestInsetFiltergraph: + def test_graph_places_screen_and_camera(self): + graph = inset_filtergraph(1920, 1080, 1080, 1920, (1500, 880, 350, 200)) + assert "split=3" in graph + assert "[screen]" in graph and "[cam]" in graph + assert graph.endswith("[v]") + + def test_screen_band_is_never_cropped(self): + # The whole point: a game HUD or a desktop keeps its edges. + graph = inset_filtergraph(1920, 1080, 1080, 1920, (1500, 880, 350, 200)) + screen = graph.split("[sa]")[-1].split("[screen]")[0] + assert "crop" not in screen + assert "scale=1080:608" in screen + + def test_camera_band_keeps_the_inset_aspect(self): + # A 16:9 inset must not be stretched into a wider band; that shows up + # instantly on a face. + graph = inset_filtergraph(1920, 1080, 1080, 1920, (1500, 880, 356, 200)) + cam = graph.split("[ca]")[-1].split("[cam]")[0] + crop_w = int(cam.split("w=")[1].split(":")[0]) + crop_h = int(cam.split("h=")[1].split(":")[0]) + band_h = int(cam.split("scale=1080:")[1].split("[")[0]) + assert abs((crop_w / crop_h) - (1080 / band_h)) < 0.05 + + def test_camera_band_is_capped(self): + # A near-square inset would otherwise claim most of the frame. + graph = inset_filtergraph(1920, 1080, 1080, 1920, (1500, 700, 300, 290)) + band_h = int(graph.split("[cam]")[0].split("scale=1080:")[-1]) + assert band_h <= 1920 * 0.40 + 2 + + def test_crop_coordinates_stay_inside_the_source(self): + graph = inset_filtergraph(1920, 1080, 1080, 1920, (1850, 1000, 70, 80)) + cam = graph.split("[ca]")[-1].split("[cam]")[0] + x = int(cam.split("x=")[1].split(":")[0]) + w = int(cam.split("w=")[1].split(":")[0]) + assert x >= 0 and x + w <= 1920 + + def test_every_dimension_is_even(self): + graph = inset_filtergraph(1920, 1080, 1080, 1920, (1501, 881, 351, 201)) + cam = graph.split("[ca]")[-1].split("[cam]")[0] + for key in ("w=", "h=", "x=", "y="): + assert int(cam.split(key)[1].split(":")[0].split(",")[0]) % 2 == 0