From 255996da63f3d64b24561598a5c6f0e417c5001e Mon Sep 17 00:00:00 2001
From: WuYongJie <549727955@qq.com>
Date: Wed, 25 Nov 2026 18:48:43 +0800
Subject: [PATCH] =?UTF-8?q?=E8=AF=A6=E6=83=85=E6=9B=BF=E6=8D=A2=E4=BF=9D?=
=?UTF-8?q?=E7=95=99=E5=8E=9F=E5=9B=BE=E6=A0=87=E9=A2=98=E5=92=8C=E8=A7=92?=
=?UTF-8?q?=E6=A0=87?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
lib/ai/replacement-layout-lock.ts | 144 +++++++++++++++++++
tests/routes/replacement-layout-lock.test.ts | 46 ++++++
2 files changed, 190 insertions(+)
diff --git a/lib/ai/replacement-layout-lock.ts b/lib/ai/replacement-layout-lock.ts
index d5898e4f1..e904c1026 100644
--- a/lib/ai/replacement-layout-lock.ts
+++ b/lib/ai/replacement-layout-lock.ts
@@ -230,12 +230,29 @@ function buildTextLockMask(params: {
width: number;
height: number;
feather: number;
+ copyPanelHeight?: number;
+ cornerCaptions?: { source: NormalizedReplacementBox; bounds: PixelBox }[];
}) {
const mask = Buffer.alloc(params.width * params.height);
const padding = Math.max(4, Math.round(Math.min(params.width, params.height) * 0.006));
for (const normalizedBox of params.boxes) {
const box = normalizedToPixelBox(normalizedBox, params.width, params.height);
+ if (params.copyPanelHeight && box.top < params.copyPanelHeight) continue;
+ const cornerCaption = params.cornerCaptions?.find(({ source }) => source === normalizedBox);
+ if (cornerCaption) {
+ // A corner caption may have shifted down or clipped at the edge of the generated photo.
+ const { bounds } = cornerCaption;
+ const feather = Math.max(params.feather, Math.round((bounds.bottom - bounds.top) * 0.4));
+ const padding = Math.max(2, Math.round((bounds.bottom - bounds.top) * 0.15));
+ paintFeatheredRectangle(mask, params.width, params.height, {
+ left: bounds.left - padding - feather,
+ top: bounds.top - padding - feather,
+ right: bounds.right + padding + feather,
+ bottom: bounds.bottom + padding + feather,
+ }, feather);
+ continue;
+ }
paintFeatheredRectangle(
mask,
params.width,
@@ -255,9 +272,122 @@ function buildTextLockMask(params: {
);
}
+ // The photo boundary is a hard edge in the reference layout.
+ if (params.copyPanelHeight) mask.fill(255, 0, params.copyPanelHeight * params.width);
return mask;
}
+async function findLightCopyPanelHeight(params: {
+ reference: Buffer;
+ width: number;
+ height: number;
+ textBoxes: NormalizedReplacementBox[];
+ subjectBox?: NormalizedReplacementBox | null;
+}) {
+ const { width, height } = params;
+ const sharp = (await import("sharp")).default;
+ const sampleWidth = Math.min(width, 120);
+ const { data, info } = await sharp(params.reference)
+ .resize(sampleWidth, height, { fit: "fill" })
+ .removeAlpha()
+ .toColourspace("srgb")
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ const margin = Math.floor(sampleWidth * 0.04);
+ const lightShare = new Float32Array(height);
+ for (let y = 0; y < height; y += 1) {
+ let lightPixels = 0;
+ for (let x = margin; x < sampleWidth - margin; x += 1) {
+ const offset = (y * sampleWidth + x) * info.channels;
+ const r = data[offset]!;
+ const g = data[offset + 1]!;
+ const b = data[offset + 2]!;
+ const minimum = Math.min(r, g, b);
+ if (minimum >= 238 && Math.max(r, g, b) - minimum <= 14) {
+ lightPixels += 1;
+ }
+ }
+ lightShare[y] = lightPixels / (sampleWidth - 2 * margin);
+ }
+
+ const averageLightShare = (first: number, last: number) => {
+ let sum = 0;
+ for (let row = first; row < last; row += 1) sum += lightShare[row]!;
+ return sum / (last - first);
+ };
+ const separatorHeight = Math.max(3, Math.round(height * 0.007));
+ const photoProbeHeight = Math.max(8, Math.round(height * 0.022));
+ const firstBoundary = Math.max(separatorHeight, Math.round(height * 0.09));
+ const lastBoundary = Math.min(height - 2 * photoProbeHeight, Math.round(height * 0.47));
+ for (let boundary = firstBoundary; boundary < lastBoundary; boundary += 1) {
+ if (lightShare[boundary]! > 0.65) continue;
+ if (averageLightShare(boundary - separatorHeight, boundary) < 0.92) continue;
+ if (averageLightShare(boundary, boundary + photoProbeHeight) > 0.64) continue;
+ if (averageLightShare(boundary + photoProbeHeight, boundary + 2 * photoProbeHeight) > 0.75) continue;
+ const normalizedBoundary = (boundary / height) * 1000;
+ if (!params.textBoxes.some((box) => box[3] <= normalizedBoundary)) continue;
+ if (params.subjectBox && params.subjectBox[1] + 25 < normalizedBoundary) continue;
+ if (averageLightShare(0, boundary) >= 0.8) return boundary;
+ }
+ return 0;
+}
+
+async function findCornerCaptionBounds(params: {
+ generated: Buffer;
+ reference: Buffer;
+ width: number;
+ height: number;
+ source: NormalizedReplacementBox;
+}) {
+ const { generated, reference, width, height, source } = params;
+ if (source[1] < 820 || source[2] - source[0] >= 500 ||
+ (source[0] > 120 && source[2] < 880)) return null;
+ const box = normalizedToPixelBox(source, width, height);
+ const boxWidth = box.right - box.left;
+ const boxHeight = box.bottom - box.top;
+ const left = source[0] <= 120 ? 0 : Math.floor(Math.max(0, box.left - boxWidth * 0.35));
+ const right = source[2] >= 880 ? width : Math.ceil(Math.min(width, box.right + boxWidth * 0.35));
+ const top = Math.floor(Math.max(0, box.top - boxHeight * 0.35));
+ const bottom = Math.ceil(Math.min(height, box.bottom + boxHeight));
+ const sharp = (await import("sharp")).default;
+ const readAccentBounds = async (image: Buffer) => {
+ const { data, info } = await sharp(image)
+ .extract({ left, top, width: right - left, height: bottom - top })
+ .removeAlpha().toColourspace("srgb").raw().toBuffer({ resolveWithObject: true });
+ const bounds = { left: right, right: left, top: bottom, bottom: top };
+ for (let y = 0; y < info.height; y += 1) {
+ let first = info.width;
+ let last = -1;
+ let accentPixels = 0;
+ for (let x = 0; x < info.width; x += 1) {
+ const offset = (y * info.width + x) * info.channels;
+ const rgb = [data[offset]!, data[offset + 1]!, data[offset + 2]!];
+ const maximum = Math.max(...rgb);
+ if (maximum < 220 || maximum - Math.min(...rgb) < 105) continue;
+ first = Math.min(first, x);
+ last = x;
+ accentPixels += 1;
+ }
+ if (accentPixels < Math.max(3, boxWidth * 0.12)) continue;
+ bounds.left = Math.min(bounds.left, left + first);
+ bounds.right = Math.max(bounds.right, left + last + 1);
+ bounds.top = Math.min(bounds.top, top + y);
+ bounds.bottom = top + y + 1;
+ }
+ return bounds.right - bounds.left >= boxWidth * 0.5 &&
+ bounds.bottom - bounds.top >= 3 &&
+ bounds.bottom - bounds.top <= boxHeight * 1.3 ? bounds : null;
+ };
+ const [original, rendered] = await Promise.all([readAccentBounds(reference), readAccentBounds(generated)]);
+ if (!original || !rendered) return null;
+ return { source, bounds: {
+ left: Math.min(original.left, rendered.left),
+ right: Math.max(original.right, rendered.right),
+ top: Math.min(original.top, rendered.top),
+ bottom: Math.max(original.bottom, rendered.bottom),
+ } };
+}
+
async function addAlphaMask(params: {
buffer: Buffer;
mask: Buffer;
@@ -352,11 +482,25 @@ export async function compositeReplacementWithReferenceLocks(params: {
return generatedBuffer;
}
+ const copyPanelHeight = await findLightCopyPanelHeight({
+ reference: referenceBuffer,
+ width,
+ height,
+ textBoxes: textBoundingBoxes,
+ subjectBox: params.subjectBoundingBox,
+ });
+ const cornerCaptions = copyPanelHeight
+ ? (await Promise.all(textBoundingBoxes.map((source) => findCornerCaptionBounds({
+ generated: generatedBuffer, reference: referenceBuffer, width, height, source,
+ })))).filter((caption) => caption !== null)
+ : [];
const textMask = buildTextLockMask({
boxes: textBoundingBoxes,
width,
height,
feather,
+ copyPanelHeight,
+ cornerCaptions,
});
const referenceTextLayer = await addAlphaMask({
buffer: referenceBuffer,
diff --git a/tests/routes/replacement-layout-lock.test.ts b/tests/routes/replacement-layout-lock.test.ts
index d318594e8..f4f04f1ee 100644
--- a/tests/routes/replacement-layout-lock.test.ts
+++ b/tests/routes/replacement-layout-lock.test.ts
@@ -152,3 +152,49 @@ test("restores original text pixels while retaining a regenerated scene", async
expect(pixel(5, 5)).toEqual([0, 0, 255]);
expect(pixel(50, 50)).toEqual([255, 0, 0]);
});
+
+test("keeps the full title panel and corner caption over the regenerated photo", async () => {
+ const width = 120;
+ const height = 160;
+ const panelHeight = 54;
+ const reference = await sharp(Buffer.from(`
+ `)).png().toBuffer();
+ const generated = await sharp(Buffer.from(`
+ `)).png().toBuffer();
+
+ const result = await compositeReplacementWithReferenceLocks({
+ generatedBuffer: generated,
+ referenceBuffer: reference,
+ width,
+ height,
+ preserveReferenceOutsideSubject: false,
+ subjectBoundingBox: [160, 400, 850, 920],
+ textBoundingBoxes: [[75, 106, 510, 158], [75, 193, 660, 370], [50, 884, 259, 935]],
+ });
+ const pixels = (image: Buffer, top: number, sectionHeight: number, left = 0, sectionWidth = width) =>
+ sharp(image)
+ .extract({ left, top, width: sectionWidth, height: sectionHeight })
+ .removeAlpha()
+ .raw()
+ .toBuffer();
+
+ expect((await pixels(result, 0, panelHeight)).equals(await pixels(reference, 0, panelHeight)))
+ .toBe(true);
+ expect((await pixels(result, panelHeight, 60)).equals(await pixels(generated, panelHeight, 60)))
+ .toBe(true);
+ expect((await pixels(result, 145, 12, 0, 30)).equals(await pixels(reference, 145, 12, 0, 30)))
+ .toBe(true);
+ expect((await pixels(result, 145, 12, 55, 45)).equals(await pixels(generated, 145, 12, 55, 45)))
+ .toBe(true);
+});