Spaces:
Running
Keep the original photo's background instead of downscaling and interpolating it
Browse filesThe pipeline resizes the target to the working resolution (1024 on CPU) so the
models stay affordable, then upscales the whole frame 4x for the download. For a
1086x1448 location photo that means everything — including the background and
body, which the swap never touches — is halved in detail and then interpolated
back up.
The result is now composited back onto the untouched full-resolution target,
pasting only the region the pipeline actually changed. The mask comes from a
diff against the working-resolution target rather than a parsed head shape, so
changes outside the head are carried over too: match_skin_to_source also
recolours neck, arms and hands, and a head-only mask would silently drop that.
Measured end-to-end on the Library target, in regions the swap never touches:
background sharpness goes from ~34% of the original to 100% (bottom edge 97.6%),
and the delivered image is now 1086x1448 native rather than 768x1024, so the 4x
download is 4344x5792 instead of 3072x4096. No seam at the composite boundary.
14 tests pass.
Files changed (2)
- utils/image_io.py+47
- web_app.py+14-1
56 unmodified lines57585960616256 unmodified linesreturn cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)def image_to_bytes(image: np.ndarray, fmt: str = "PNG") -> bytes:"""Convert BGR numpy array to encoded bytes."""rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)56 unmodified lines5758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810956 unmodified linesreturn cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)def composite_onto_original(result: np.ndarray, work_target: np.ndarray,orig_target: np.ndarray, threshold: int = 6,feather: float = 0.004) -> np.ndarray:"""Put everything the pipeline CHANGED back onto the full-resolution target.The swap runs at a reduced working resolution so the models stay affordable,and the 4x download then interpolates that whole frame back up. For a1086x1448 photo processed at 768x1024 that discards half the real detail —including the background and body, which the swap never touches. Here wediff the result against the working-resolution target to find what actuallychanged (the head, plus any skin the tone match reached), and paste onlythat onto the untouched original. Everything else stays pixel-exact.A diff-driven mask is used rather than a parsed head mask so that changesoutside the head — match_skin_to_source also recolours neck, arms and hands— are carried over too instead of being silently dropped."""if orig_target is None or result is None:return resultoh, ow = orig_target.shape[:2]rh, rw = result.shape[:2]if (oh, ow) == (rh, rw):return result # nothing was downscaledif work_target is None or work_target.shape[:2] != result.shape[:2]:return cv2.resize(result, (ow, oh), interpolation=cv2.INTER_LANCZOS4)diff = cv2.absdiff(result, work_target).max(axis=2)# Blur before thresholding so JPEG-level speckle doesn't fragment the mask.diff = cv2.GaussianBlur(diff, (0, 0), max(1.0, min(rh, rw) * 0.002))mask = (diff > threshold).astype(np.float32)if mask.max() <= 0:return orig_target.copy() # pipeline was a no-op# Close holes, then grow slightly so the seam sits outside the changed area.k = max(3, int(min(rh, rw) * 0.01) | 1)mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((k, k), np.uint8))mask = cv2.dilate(mask, np.ones((k, k), np.uint8))up_result = cv2.resize(result, (ow, oh), interpolation=cv2.INTER_LANCZOS4)up_mask = cv2.resize(mask, (ow, oh), interpolation=cv2.INTER_LINEAR)up_mask = cv2.GaussianBlur(up_mask, (0, 0), max(1.5, min(oh, ow) * feather))a = np.clip(up_mask, 0.0, 1.0)[..., None]out = up_result.astype(np.float32) * a + orig_target.astype(np.float32) * (1.0 - a)return np.clip(out, 0, 255).astype(np.uint8)def image_to_bytes(image: np.ndarray, fmt: str = "PNG") -> bytes:"""Convert BGR numpy array to encoded bytes."""rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
43 unmodified lines44454647484950618 unmodified lines669670671672673674181 unmodified lines85685785885986086143 unmodified linesfrom core.blender import laplacian_blendfrom core.quality_checker import compute_quality_scorefrom core import supabase_storefrom utils.image_io import resize_keep_aspectREACT_BUILD = os.path.join("static", "react")LOCATIONS_DIR = "Location" # Location/Male/<loc>/img + Location/Female/<loc>/img618 unmodified lines# larger canvas mainly helps the final blend + the RealESRGAN 4x upscale.from core.super_res import _device as _sr_device_work_res = 1536 if _sr_device() == "cuda" else 1024source = resize_keep_aspect(source, _work_res)target = resize_keep_aspect(target, _work_res)181 unmodified linesexcept Exception as e:print(f"[swap] harmonize skipped: {e}")# -- 4K upscale for download (RealESRGAN x4, Lanczos fallback) --------hi_res = upscale_image(swapped, scale=4)43 unmodified lines44454647484950618 unmodified lines669670671672673674675676677678679181 unmodified lines86186286386486586686786886987087187287387443 unmodified linesfrom core.blender import laplacian_blendfrom core.quality_checker import compute_quality_scorefrom core import supabase_storefrom utils.image_io import resize_keep_aspect, composite_onto_originalREACT_BUILD = os.path.join("static", "react")LOCATIONS_DIR = "Location" # Location/Male/<loc>/img + Location/Female/<loc>/img618 unmodified lines# larger canvas mainly helps the final blend + the RealESRGAN 4x upscale.from core.super_res import _device as _sr_device_work_res = 1536 if _sr_device() == "cuda" else 1024# Keep the untouched full-resolution target: at the end only the region# the pipeline actually changed is pasted back onto it, so background and# body keep the original photo's detail instead of being downscaled here# and interpolated back up by the 4x pass.target_orig = targetsource = resize_keep_aspect(source, _work_res)target = resize_keep_aspect(target, _work_res)181 unmodified linesexcept Exception as e:print(f"[swap] harmonize skipped: {e}")# 9. Paste the changed region back onto the FULL-RESOLUTION target so the# background and body keep the original photo's detail rather than the# downscaled-then-interpolated version. No-op if nothing was resized.try:swapped = composite_onto_original(swapped, target, target_orig)except Exception as e:print(f"[swap] original-resolution composite skipped: {e}")# -- 4K upscale for download (RealESRGAN x4, Lanczos fallback) --------hi_res = upscale_image(swapped, scale=4)