From 064e3d2132f2b7c108888aa1111f8585f2433667 Mon Sep 17 00:00:00 2001 From: Hardwell99 <3022256519@qq.com> Date: Tue, 27 Oct 2026 14:43:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 优化 --- device.py | 27 ++++ inference.py | 155 +++++++++-------------- pipeline.py | 222 +++++++++++++++++++++++--------- ttp.py | 347 ++++++++++++++++++++++++++++++--------------------- 4 files changed, 461 insertions(+), 290 deletions(-) diff --git a/device.py b/device.py index a0c845e..d1b10cd 100644 --- a/device.py +++ b/device.py @@ -135,6 +135,33 @@ def offload_registered_models() -> int: return moved +def vram_pressure(free_ratio: float = 0.15) -> bool: + """当前显存是否处于紧张状态(空闲显存占比低于 free_ratio)。 + + 供推理循环做**条件式**缓存清理判断:`torch.cuda.empty_cache()` 是同步且 + 昂贵的操作(要向驱动归还所有未用显存并重置分配器),逐块无条件调用会让 + GPU 利用率出现周期性锯齿。只在真的快没显存时才付这个代价。 + + 注意用的是**设备级**空闲显存(`mem_get_info`),而非本进程占用量 —— + 同一张卡上可能还有别的进程,它同样会造成 OOM,只看自己的占用会漏判。 + + Args: + free_ratio: 空闲显存占比阈值,低于此值即判定为有压力。 + + Returns: + 是否有显存压力。无 CUDA 设备时恒为 False。 + """ + if not torch.cuda.is_available(): + return False + try: + free, total = torch.cuda.mem_get_info() + except Exception: # noqa: BLE001 —— 探测失败一律按"无压力"处理,绝不因此中断业务 + return False + if total <= 0: + return False + return (free / total) < free_ratio + + def release_vram(unload_models: bool = True) -> dict: """显存释放:卸载模型到内存 + 清空 CUDA 缓存。由管线收尾(成功/失败/中断)调用。 diff --git a/inference.py b/inference.py index a925ad3..a8a775e 100644 --- a/inference.py +++ b/inference.py @@ -13,7 +13,7 @@ import logging import torch import torch.nn.functional as F -from .color import apply_color_alignment +from .device import vram_pressure as _vram_pressure from .tiled_vae import _gaussian_weights, _make_tile_grid AE_FACTOR = 8 @@ -57,16 +57,6 @@ def _generate_noise(shape, seed: int, device, dtype) -> torch.Tensor: return noise.to(device=device, dtype=dtype) -def _generate_noise_batch(shape_per_item, seed: int, batch_size: int, device, dtype) -> torch.Tensor: - """整批共用同一个 seed —— 每项噪声逐元素相同。 - - `expand` 返回只读视图而非拷贝;后续它只被 `torch.cat` / 减法读取,从不原地写, - 因此各 batch 项共享同一份底层存储是安全的(真要写就会踩到 view 语义,需要 clone)。 - """ - noise = _generate_noise(shape_per_item, seed, device, dtype) - return noise.unsqueeze(0).expand(batch_size, *noise.shape) - - def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int): """Pixel tile size/overlap -> latent-space, aligned to the DiT patch size.""" lt_size = max((tile_size // AE_FACTOR // DIT_PATCH_SIZE) * DIT_PATCH_SIZE, DIT_PATCH_SIZE) @@ -76,39 +66,6 @@ def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int): return lt_size, lt_overlap -def _resize_to_target(images_bhwc01: torch.Tensor, upscale: int, device) -> torch.Tensor: - x = images_bhwc01.movedim(-1, 1).to(device) # BCHW [0, 1] - _, _, h, w = x.shape - target_h, target_w = h * upscale, w * upscale - return F.interpolate(x, size=(target_h, target_w), mode="bicubic").clamp(0.0, 1.0) - - -def _run_untiled_batch(model, resized01: torch.Tensor, seed: int, vae_tile_size: int, vae_tile_overlap: int, - tick=None) -> torch.Tensor: - b, _, h, w = resized01.shape - padded01 = _pad_to_multiple(resized01, PAD_MULTIPLE) - padded01 = _pad_to_square(padded01) - padded_pm1 = padded01 * 2.0 - 1.0 - - lq_latent, latents_mean, latents_std = model.encode_tiled(padded_pm1, vae_tile_size, vae_tile_overlap) - venc_fea = model.vision_features(padded01) - model.vision_patcher.offload() # 视觉编码器用完即卸载,为 DiT/VAE 让路 - - noise = _generate_noise_batch(lq_latent.shape[1:], seed, b, lq_latent.device, lq_latent.dtype) - sr_latent = model.denoise_one_step(lq_latent, noise, venc_fea) - model.dit_patcher.offload() # DiT 用完即卸载(fp16 ~2.6G),VAE 解码是激活峰值大户 - - # 整图解码前的中断检查:tile_size=0 时 DiT 只有一次前向,这里是全流程唯一的 - # 细粒度检查点。放在解码之前,中断可直接省掉最重、最容易 OOM 的全图 VAE 解码, - # 而不是把解码白跑完再退出。 - if tick is not None: - tick() - - decoded_pm1 = model.decode_tiled(sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap) - - return decoded_pm1[:, :, :h, :w] - - def estimate_dit_tiles(h: int, w: int, tile_size: int, tile_overlap: int) -> int: """公开接口:预估一张 HxW(已放大像素)图像会被 DiT 内部切成多少块。tile_size=0 时为 1。""" if not tile_size: @@ -194,10 +151,10 @@ def _run_tiled_single(model, resized01: torch.Tensor, seed: int, tile_size: int, def run_vosr2( model, - images_bhwc01: torch.Tensor, + full_upscaled_bhwc01: torch.Tensor, + positions, upscale: int, seed: int, - color_alignment: str, tile_size: int, tile_overlap: int, vae_tile_size: int, @@ -206,46 +163,52 @@ def run_vosr2( ) -> torch.Tensor: """progress_cb(done_tiles, total_tiles):DiT 分块粒度的进度回调。 - seed 语义:**整张图、全部块共用同一个 seed,不做块序号偏移**。 - 噪声张量在每次 `_generate_noise` / `_generate_noise_batch` 里按传入的 seed - 重新生成,同 seed + 同 shape ⇒ 噪声逐元素相同,因此: + `full_upscaled_bhwc01`:整图已做 `×upscale` 预放大的结果(BHWC float32, + [0,1]),由调用方(pipeline)一次性完成 —— 见 P4:整图放大一次,再按 + `positions × upscale` 切片逐块处理,重叠区只放大一次且用整图上下文。 - - 外层 TTP 切出的 N 块拿到完全相同的噪声起点; - - 块内 DiT 潜空间分块共用整块的那一张噪声(本来就是这样,见 _run_tiled_single); - - 换图 / 换块数不会让 seed 语义漂移,跨图可比对。 + `positions`:tile_batch 返回的原图尺度位置列表,每块切片 = `full_upscaled + [u*upscale:d*upscale, l*upscale:r*upscale]`。 - 代价:相邻块若内容相近,会得到相同方向的随机纹理,块边界更容易看出规则重复。 - 外层接缝仍由 TTP 羽化(feather)负责掩盖,与内层 DiT 的高斯加权是两套机制。 + seed 语义:**整张图、全部块共用同一个 seed,不做块序号偏移**(原始设计意图)。 + 同 seed + 同 shape ⇒ 噪声逐元素相同,给定相同输入与 seed,输出完全可复现、 + 跨图可比对。代价是相邻块内容相近时可能呈现相同方向的随机纹理,但这是为可比性 + 刻意保留的行为(P5 的「逐块派生 seed」方案已被否决,恢复统一 seed)。 + + P6:色彩对齐已移出本函数,由调用方在 assemble 之后对整图统一做,故此处 + 不再接受 color_alignment,也不逐块保留 bicubic 参考。 """ - if images_bhwc01.shape[-1] != 3: - raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {images_bhwc01.shape[-1]} channels.") + if full_upscaled_bhwc01.shape[-1] != 3: + raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {full_upscaled_bhwc01.shape[-1]} channels.") if tile_size > 0 and tile_overlap >= tile_size: raise ValueError(f"VOSR2Upscale: tile_overlap ({tile_overlap}) must be smaller than tile_size ({tile_size}).") if vae_tile_size > 0 and vae_tile_overlap >= vae_tile_size: raise ValueError(f"VOSR2Upscale: vae_tile_overlap ({vae_tile_overlap}) must be smaller than vae_tile_size ({vae_tile_size}).") device = model.dit_patcher.load_device - b = images_bhwc01.shape[0] - h0, w0 = images_bhwc01.shape[1:3] - h, w = h0 * upscale, w0 * upscale # 放大后目标尺寸 + n = len(positions) + # 每块放大后的尺寸(用首块位置推导;所有块内容尺寸一致) + l0, u0, r0, d0 = positions[0] + per_h = (d0 - u0) * upscale + per_w = (r0 - l0) * upscale - if tile_size == 0 and (h > 512 or w > 512): + if tile_size == 0 and (per_w > 512 or per_h > 512): logging.warning( - f"VOSR2Upscale: target size {w}x{h} (after {upscale}x upscale) exceeds VOSR 2.0's " + f"VOSR2Upscale: block target size {per_w}x{per_h} (after {upscale}x upscale) exceeds VOSR 2.0's " f"native 512px training resolution with tile_size=0 (DiT tiling disabled). Set " f"tile_size > 0 (e.g. 512) or quality will likely degrade." ) - if vae_tile_size == 0 and (h > 1024 or w > 1024): + if vae_tile_size == 0 and (per_w > 1024 or per_h > 1024): logging.warning( - f"VOSR2Upscale: target size {w}x{h} (after {upscale}x upscale) with vae_tile_size=0 " - f"(VAE tiling disabled) decodes the full image in one pass regardless of tile_size -- " + f"VOSR2Upscale: block target size {per_w}x{per_h} (after {upscale}x upscale) with vae_tile_size=0 " + f"(VAE tiling disabled) decodes the full block in one pass regardless of tile_size -- " f"common CUDA OOM source. Set vae_tile_size > 0 (e.g. 1024) to bound peak VRAM." ) - # 进度/中断计数:tile_size>0 时按 DiT 分块逐块推进(tick 在每个分块边界 - # 触发,管线借它做中断检查);tile_size=0 时 _run_untiled_batch 一次性吃掉 - # 整批,只在整图解码前报一次,故总数记 1。 - total_tiles = b * _count_dit_tiles(h, w, tile_size, tile_overlap) if tile_size > 0 else 1 + # 进度/中断计数:每块按 DiT 内部分块逐块推进;tick 在每个分块边界触发, + # 管线借它做中断检查。 + total_per_block = _count_dit_tiles(per_h, per_w, tile_size, tile_overlap) if tile_size > 0 else 1 + total_tiles = n * total_per_block done = [0] def tick(): @@ -253,32 +216,34 @@ def run_vosr2( if progress_cb: progress_cb(done[0], total_tiles) - if tile_size > 0: - # 逐块放大 + 处理:任意时刻 GPU 上只有一块的放大图,而非整批 - aligned_items = [] - for i in range(b): - x = images_bhwc01[i:i + 1].movedim(-1, 1).to(device) # BCHW [0,1] - x = F.interpolate(x, size=(h, w), mode="bicubic").clamp(0.0, 1.0) - ref_cpu = x.cpu() # 供色彩对齐使用 - item_pm1 = _run_tiled_single( - model, x, seed, tile_size, tile_overlap, - vae_tile_size, vae_tile_overlap, tick=tick, - ).cpu() - del x # 释放该块的 GPU 放大图 - item01 = (item_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0 - del item_pm1 - aligned_items.append(apply_color_alignment(item01, ref_cpu, color_alignment)) - del item01, ref_cpu + items = [] + for i, (l, u, r, d) in enumerate(positions): + sl = full_upscaled_bhwc01[:, u * upscale:d * upscale, l * upscale:r * upscale, :] + x = sl.movedim(-1, 1).to(device) # BCHW [0,1] + del sl + # 统一 seed:全部块共用同一个 seed,不做块序号偏移(原始设计意图: + # 同 seed + 同 shape 保证跨图可比对、给定输入与 seed 输出完全可复现)。 + item_pm1 = _run_tiled_single( + model, x, seed, tile_size, tile_overlap, + vae_tile_size, vae_tile_overlap, tick=tick, + ).cpu() + del x # 释放该块的 GPU 放大图 + item01 = (item_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0 + del item_pm1 + items.append(item01) + del item01 + # 块间只做"按需"清理:empty_cache() 是同步且昂贵的驱动操作, + # 逐块无条件调用会让 GPU 利用率出现周期性锯齿。只有真的快没显存 + # 时才付这个代价(vram_pressure 用设备级空闲显存判断, + # 同一张卡上还有别的进程时也能正确识别压力)。 + if _vram_pressure(): gc.collect() - torch.cuda.empty_cache() # 块间清理缓存碎片,降低长驻峰值 - aligned01 = torch.cat(aligned_items, dim=0) - del aligned_items - else: - resized01 = _resize_to_target(images_bhwc01, upscale, device) - outputs_pm1 = _run_untiled_batch( - model, resized01, seed, vae_tile_size, vae_tile_overlap, tick=tick, - ) - decoded01 = (outputs_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0 - aligned01 = apply_color_alignment(decoded01, resized01, color_alignment) - + torch.cuda.empty_cache() + # 循环外的统一回收:块循环里已用 del 精确释放了引用,这里只补一次 + # 循环引用(dict/list 环)的回收,并把碎片化的小块内存还给驱动。 + gc.collect() + if _vram_pressure(): + torch.cuda.empty_cache() + aligned01 = torch.cat(items, dim=0) + del items return aligned01.movedim(1, -1) diff --git a/pipeline.py b/pipeline.py index 9839658..0e3236b 100644 --- a/pipeline.py +++ b/pipeline.py @@ -7,10 +7,12 @@ from pathlib import Path from typing import Callable import torch +import torch.nn.functional as F from PIL import Image from . import device as _device from . import ttp +from .color import apply_color_alignment from .inference import estimate_dit_tiles, run_vosr2 from .loader import load_vosr2 from .sharpen import cas_sharpen @@ -19,10 +21,10 @@ PROJECT_DIR = Path(__file__).resolve().parent.parent OUTPUT_DIR = PROJECT_DIR / "outputs" # 工作流固定常量 -ALIGN = 8 # 块尺寸向上对齐到 8 的倍数 -TILE_MIN = 720 # 【分块尺寸】下限 -TILE_MAX = 960 # 【分块尺寸】上限 -MIN_LONG_SIDE = 1080 # 【输入下限】最长边不足此值时,等比例预放大后再进入流程 +ALIGN = 16 # 块尺寸向上对齐到 16 的倍数(= inference.PAD_MULTIPLE) +TILE_MIN = 512 # 【分块尺寸】下限 +TILE_MAX = 1024 # 【分块尺寸】上限 +MIN_LONG_SIDE = 1024 # 【输入下限】最长边不足此值时,等比例预放大后再进入流程 ProgressCB = Callable[[float, str], None] @@ -44,47 +46,84 @@ def _ceil_div(a: int, b: int) -> int: return -(-a // b) -def _tile_size_for(total: int, cols: int, feather: int) -> int: - return ((_ceil_div(total, cols) + ALIGN - 1) // ALIGN) * ALIGN + feather +def _content_for(total: int, cols: int) -> int: + """把 total 等分为 cols 列后,单列向上对齐到 ALIGN 的倍数(= 块内容尺寸,不含羽化)。""" + return ((_ceil_div(total, cols) + ALIGN - 1) // ALIGN) * ALIGN -def _pick_cols(total: int, feather: int, lo: int, hi: int) -> int: - hi_cols = max(1, _ceil_div(total, max(1, lo - feather))) +def _pick_cols(total: int, lo: int, hi: int) -> int: + """选列数,使块内容尺寸尽量落在 [lo, hi];落不进区间时取离区间最近者。""" + hi_cols = max(1, _ceil_div(total, lo)) best_cols, best_dist = 1, None for cols in range(1, hi_cols + 1): - tile = _tile_size_for(total, cols, feather) - if tile < lo: - dist = lo - tile - elif tile > hi: - dist = tile - hi - else: + content = _content_for(total, cols) + if lo <= content <= hi: dist = 0 + elif content < lo: + dist = lo - content + else: + dist = content - hi if best_dist is None or dist < best_dist: best_cols, best_dist = cols, dist return best_cols def compute_grid(width: int, height: int, feather: int): - """块数与块宽/块高(在【原图】上切块)。 + """块数与块内容尺寸(在【原图】上切块)。 - 每块尺寸(含羽化)反解块数,使其尽量落在 [TILE_MIN, TILE_MAX], - 即【分块尺寸】∈ [720, 960],切好后喂给 VOSR2。 - 原图宽高均 ≤ TILE_MAX 时整图直喂(cols=rows=1,块=原图尺寸,不加羽化)。 + 块内容尺寸(**不含羽化**)反解列/行数,使其尽量落在 [TILE_MIN, TILE_MAX]; + 相邻块的重叠量 = `feather`(由 tile_batch 的 overlap 参数保证),不计入块尺寸 + —— 这样 feather 只控制接缝羽化宽度、不再撑大块尺寸(旧实现把 feather 加进块 + 尺寸,导致 f=128 时块越界、有效羽化被整数除法反向截断)。 + + 原图宽高均 ≤ TILE_MAX 时整图直喂(cols=rows=1,块=原图尺寸)。 + + 返回的 cols/rows 与 tile_batch 经 `_layout(..., overlap=feather)` 算出的真实 + 块数一致(两者共用同一套几何),规划面板显示的块数不再偏大(旧 P3)。 """ if width <= TILE_MAX and height <= TILE_MAX: return 1, 1, width, height - cols = _pick_cols(width, feather, TILE_MIN, TILE_MAX) - rows = _pick_cols(height, feather, TILE_MIN, TILE_MAX) - block_w = _tile_size_for(width, cols, feather) - block_h = _tile_size_for(height, rows, feather) - return cols, rows, block_w, block_h + cols_content = _pick_cols(width, TILE_MIN, TILE_MAX) + rows_content = _pick_cols(height, TILE_MIN, TILE_MAX) + block_w = _content_for(width, cols_content) + block_h = _content_for(height, rows_content) + # 真实块数:与 tile_batch 共用 _layout(overlap=feather),面板与推理严格一致 + ncols, _ = ttp._layout(width, block_w, feather) + nrows, _ = ttp._layout(height, block_h, feather) + return ncols, nrows, block_w, block_h def image_size(image_path: str | Path) -> tuple[int, int]: - """读图取尺寸(宽, 高),不加载模型、不推理。""" - image = load_image_bhwc(image_path) - _, height, width, _ = image.shape # BHWC - return width, height + """读图取尺寸(宽, 高),不加载模型、不推理。 + + 只读文件头(PIL 惰性解析 header,不解码像素)—— 本函数在 UI 每次改动 + 参数时都会被 plan_info 调用,全图像素解码在 4K 图上是几百毫秒的 + 同步阻塞,纯粹为了拿两个整数不值当。真正的像素解码留给 + load_image_bhwc(推理时才调用)。 + """ + with Image.open(image_path) as image: + return image.size + + +def cover_plan(src_w: int, src_h: int, dst_w: int, dst_h: int): + """计算「等比放大到覆盖目标框 + 中心裁剪」所需的参数。 + + 返回 (scale, scaled_w, scaled_h, crop_box),crop_box 为 PIL crop 的 + (left, upper, right, lower)。 + + 纯数学,不碰像素 —— plan_info 要在只读文件头的前提下算出同样的结果。 + + 为什么是 cover 而不是普通 resize:普通 resize 强制把源图映射到目标框, + 目标框宽高比与源图不一致时就产生各向异性缩放(内容被拉伸,圆变椭圆)。 + cover 先按两轴中较大的比例等比放大(保证内容完全不变形),再裁掉多出来的 + 边,代价是丢掉少量边缘像素,换来几何比例 100% 保真。 + """ + scale = max(dst_w / float(src_w), dst_h / float(src_h)) + scaled_w = max(dst_w, int(round(src_w * scale))) + scaled_h = max(dst_h, int(round(src_h * scale))) + left = (scaled_w - dst_w) // 2 + upper = (scaled_h - dst_h) // 2 + return scale, scaled_w, scaled_h, (left, upper, left + dst_w, upper + dst_h) def fit_min_long_side(width: int, height: int, @@ -98,7 +137,12 @@ def fit_min_long_side(width: int, height: int, enabled=False 时跳过预放大(实验性开关关闭),原尺寸直接进入后续环节。 返回 (新宽, 新高, 放大倍数);无需放大时倍数 = 1.0 且尺寸原样返回。 - 短边向上对齐到 ALIGN,与后续分块网格保持同一基准。 + + 短边**不再向上对齐到 ALIGN**:对齐会把目标画布的宽高比改掉(源图 800×600 + 抬到 1080×816,画布比 4:3 窄了 0.735%),再用 resize 填进去就成了内容 + 拉伸。短边改为按源图宽高比等比换算,画布与源图严格同比例,resize 不再 + 产生任何形变。分块网格的对齐由 compute_grid → _tile_size_for 独立完成 + (块尺寸永远是 ALIGN 的倍数),不依赖图像自身尺寸是否对齐。 """ if not enabled: return width, height, 1.0 @@ -106,9 +150,9 @@ def fit_min_long_side(width: int, height: int, return width, height, 1.0 factor = min_long_side / float(max(width, height)) if width >= height: # 横图:宽为最长边 - short = max(ALIGN, ((round(height * factor) + ALIGN - 1) // ALIGN) * ALIGN) + short = max(1, round(height * factor)) return min_long_side, short, factor - long_ = max(ALIGN, ((round(width * factor) + ALIGN - 1) // ALIGN) * ALIGN) + long_ = max(1, round(width * factor)) return long_, min_long_side, factor @@ -135,6 +179,14 @@ def plan_info( """ src_w, src_h = image_size(image_path) width, height, pre_scale = fit_min_long_side(src_w, src_h, min_long_side, pre_scale_enabled) + # 预放大的实际缩放参数:cover 语义(等比放大到覆盖目标框,再裁掉多余边)。 + # 目标框与源图同比例时裁剪量为 0;若有 1~2px 取整差,也是裁边而非拉伸。 + if pre_scale > 1.0: + cover_scale, cover_w, cover_h, cover_box = cover_plan(src_w, src_h, width, height) + pre_crop_x = cover_w - width + pre_crop_y = cover_h - height + else: + cover_scale, pre_crop_x, pre_crop_y = pre_scale, 0, 0 out_w, out_h = round(width * scale), round(height * scale) # 分块在【处理尺寸】上进行:块尺寸 ∈ [720,960];图足够小时整图直喂 cols, rows, block_w, block_h = compute_grid(width, height, feather) @@ -142,12 +194,13 @@ def plan_info( dit_per_tile = estimate_dit_tiles( block_h * vosr2_scale_index, block_w * vosr2_scale_index, tile_size, tile_overlap ) - # cols/rows 均为 1 时块尺寸必 ≥ 图尺寸(align8(边长)+羽化),ttp.tile_batch + # cols/rows 均为 1 时块尺寸必 ≥ 图尺寸(按 ALIGN 对齐 + 羽化),ttp.tile_batch # 必然走整图直喂分支,故直接以 cols/rows 判定,不比对块尺寸。 return { "width": width, "height": height, "src_width": src_w, "src_height": src_h, "pre_scale": pre_scale, "pre_scale_enabled": pre_scale_enabled, "min_long_side": min_long_side, + "cover_scale": cover_scale, "pre_crop_x": pre_crop_x, "pre_crop_y": pre_crop_y, "scale": scale, "vosr2_scale": vosr2_scale_index, "out_w": out_w, "out_h": out_h, "cols": cols, "rows": rows, @@ -158,16 +211,49 @@ def plan_info( } -def _resize_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor: - """BHWC 张量重采样到目标尺寸(Lanczos,质量优先)。""" - import numpy as np +def _bicubic_upscale(image_bhwc01: torch.Tensor, v: int) -> torch.Tensor: + """整图做一次 bicubic 预放大到 v 倍(float32,无 uint8 往返)。 - resample = getattr(Image, "Resampling", Image).LANCZOS - arr = image.squeeze(0).clamp(0, 1).numpy() - pil = Image.fromarray((arr * 255.0).round().astype("uint8"), mode="RGB") - pil = pil.resize((out_w, out_h), resample) - arr = np.asarray(pil, dtype=np.float32) / 255.0 - return torch.from_numpy(arr).unsqueeze(0) + P4:替代逐块独立放大。整图放大后由 run_vosr2 按 positions×v 切片, + 重叠区只被放大一次且使用整图上下文(逐块放大时块边缘因 F.interpolate + 的零填充会产生边界伪影)。 + """ + x = image_bhwc01.movedim(-1, 1).to(torch.float32) # (1,3,H,W) + h, w = x.shape[-2:] + if v == 1: + return image_bhwc01 + out = F.interpolate(x, size=(h * v, w * v), mode="bicubic", align_corners=False).clamp(0.0, 1.0) + return out.movedim(1, -1) + + +def _resize_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor: + """BHWC 张量重采样到目标尺寸(float32 bicubic,质量优先,无 uint8 往返)。""" + x = image.movedim(-1, 1).to(torch.float32) # (1,3,H,W) + if x.shape[-2:] == (out_h, out_w): + return image + out = F.interpolate(x, size=(out_h, out_w), mode="bicubic", align_corners=False).clamp(0.0, 1.0) + return out.movedim(1, -1) + + +def _resize_cover_bhwc(image: torch.Tensor, out_h: int, out_w: int) -> torch.Tensor: + """等比放大到覆盖目标框,再中心裁剪(cover),不做任何拉伸。 + + 与 _resize_bhwc 的区别:_resize_bhwc 是把源图硬拉到目标框(各向异性), + 目标框宽高比与源图不一致时内容必然变形;本函数先按两轴较大的比例等比 + 放大(内容零形变),再裁掉多出来的边。 + + 预放大走这条路径:目标框与源图同比例时裁剪量为 0,等价于普通 resize; + 万一目标框与源图不同比例,也只会裁边而不会拉变形。 + + 全程 float32(F.interpolate bicubic),替代旧实现的 PIL uint8 往返。 + """ + x = image.movedim(-1, 1).to(torch.float32) # (1,3,H,W) + src_h, src_w = x.shape[-2:] + _, scaled_w, scaled_h, box = cover_plan(src_w, src_h, out_w, out_h) + up = F.interpolate(x, size=(scaled_h, scaled_w), mode="bicubic", align_corners=False).clamp(0.0, 1.0) + left, upper, right, lower = box + crop = up[:, :, upper:lower, left:right] + return crop.movedim(1, -1) def _run_pipeline_impl( @@ -248,8 +334,10 @@ def _run_pipeline_impl( width, height, pre_scale = fit_min_long_side(width, height, min_long_side, pre_scale_enabled) if pre_scale > 1.0: report(0.03, f"原图 {src_w}×{src_h} 小于 {min_long_side}," - f"已预放大 ×{pre_scale:.3f} → {width}×{height}") - image = _resize_bhwc(image, height, width) + f"已等比放大 ×{pre_scale:.3f} → {width}×{height}") + # cover 路径:等比放大到覆盖目标框再裁掉多余边。目标框与源图同比例时 + # 裁剪量为 0;若因取整出现 1~2px 的比例差,也是裁边而不是拉伸。 + image = _resize_cover_bhwc(image, height, width) elif not pre_scale_enabled: report(0.03, f"按原尺寸 {width}×{height} 进入流程") @@ -264,16 +352,28 @@ def _run_pipeline_impl( report(0.05, f"分块规划:{cols}×{rows} 块,分块尺寸 {block_w}×{block_h} + 羽化{feather}") # ---- 4. 分块(TTP_Image_Tile_Batch 47)---- # + # positions / grid 一并留用:拼装阶段直接复用这份真实切块坐标(×v), + # 不再另算一套网格(见第 7 步)。overlap=feather 使相邻块在原图上重叠 feather + # 像素(feather 仅作羽化宽度,不再撑大块尺寸)。 check_abort() - tiles, _positions, _orig, _grid = ttp.tile_batch(image, block_w, block_h) + tiles, positions, orig_size, grid = ttp.tile_batch(image, block_w, block_h, overlap=feather) n_tiles = tiles.shape[0] + del tiles # 整图放大后按 positions 切片,原图切块张量不再需要 # ---- 5. 清显存(easy cleanGpuUsed 99)---- # from .device import release_vram release_vram(unload_models=False) report(0.08, f"显存已清理,开始超分 {n_tiles} 个块(模型 ×{vosr2_scale_index},目标 ×{scale:g})…") - # ---- 6. VOSR2 一步超分(171/172),整批进入与工作流一致 ---- # + # ---- 6. VOSR2 一步超分(171/172)---- # + # P4:整图一次性 bicubic 预放大到 v 倍(CPU float32),随后按 positions×v 切片逐块 + # 处理;重叠区只被放大一次、且使用整图上下文(逐块放大时块边缘因 F.interpolate + # 的零填充产生边界伪影,已消除)。放大结果另作为 P6 整图色彩对齐的参考。 + check_abort() + v = vosr2_scale_index + whole_up = _bicubic_upscale(image, v) + del image # whole_up 已派生,原图可释放 + model = load_vosr2(model_name, dtype) def vosr_progress(done: int, total: int): @@ -283,21 +383,29 @@ def _run_pipeline_impl( on_tile(done, total) upscaled = run_vosr2( - model, tiles, vosr2_scale_index, seed, color_alignment, + model, whole_up, positions, v, seed, tile_size, tile_overlap, vae_tile_size, vae_tile_overlap, progress_cb=vosr_progress, ) # BHWC,每块 (block_w×v, block_h×v) - # ---- 7. dummy 网格位置(198/199 + 128/129/200/201,模型尺度 v,画布 = 原图×v)---- # - v = vosr2_scale_index - dummy_w, dummy_h = width * v, height * v - dummy_tw, dummy_th = block_w * v, block_h * v - d_positions, d_original, d_grid = ttp.tile_positions(dummy_w, dummy_h, dummy_tw, dummy_th) - - # ---- 8. 羽化拼装(TTP_Image_Assy 48,padding=羽化×v,节点 202)---- # + # ---- 7/8. 坐标统一 + 羽化拼装(TTP_Image_Assy 48,padding=羽化×v,节点 202)---- # + # 拼装坐标直接复用第 4 步 tile_batch 的**真实** positions(×v 换算到模型尺度), + # 不再在 v 尺度画布上另算一套网格。真实切块位置 ×v 是唯一自洽的坐标, + # 羽化混合区取到的必是同一段原图内容(feather 即真实重叠,单调可控)。 check_abort() report(0.92, "VOSR2处理完成,最后拼接…") - assembled = ttp.assemble(upscaled, d_positions, d_original, d_grid, padding=feather * v) + s_positions = ttp.scale_positions(positions, v) + s_original = (orig_size[0] * v, orig_size[1] * v) + assembled = ttp.assemble(upscaled, s_positions, s_original, grid, padding=feather * v) + + # P6:色彩对齐改为对整图做一次(参考整图 bicubic 放大结果 whole_up),跨块 + # 色彩/亮度更一致,接缝处不再因各块独立对齐而割裂。逐块对齐已移出 run_vosr2。 + if color_alignment != "none": + _a_bchw = assembled.movedim(-1, 1) + _ref_bchw = whole_up.movedim(-1, 1) + assembled = apply_color_alignment(_a_bchw, _ref_bchw, color_alignment).movedim(1, -1) + del _a_bchw, _ref_bchw + del whole_up # ---- 8.5 重采样到目标输出尺寸(拼装在模型尺度 v=原图×v 上;scale=v 时已到位,跳过)---- # cur_h, cur_w = assembled.shape[1], assembled.shape[2] @@ -315,7 +423,9 @@ def _run_pipeline_impl( # ---- 10. 保存(CR Image Output 112 → 本地 outputs/)---- # # 命名:VOSR2_upscaled_x倍数_原始文件名_时间.png(倍数用 :g,小数如 1.5 正常显示) - day_dir = (output_dir or OUTPUT_DIR) / datetime.now().strftime("%Y%m%d") + # output_dir 容忍 str:类型标注写的是 Path,但传 str 时报错会发生在跑完整个 + # 推理之后(白烧一次 GPU),这里提前归一化。 + day_dir = Path(output_dir or OUTPUT_DIR) / datetime.now().strftime("%Y%m%d") day_dir.mkdir(parents=True, exist_ok=True) stem = Path(orig_name).stem if orig_name else "image" stem = re.sub(r'[\\/:*?"<>|]', "_", stem).strip() or "image" # 过滤非法字符 @@ -461,8 +571,8 @@ def run_pipeline( tile_overlap=tile_overlap, vae_tile_size=vae_tile_size, vae_tile_overlap=vae_tile_overlap, -sharpen_amount=sharpen_amount, - pre_scale_enabled=pre_scale_enabled, + sharpen_amount=sharpen_amount, + pre_scale_enabled=pre_scale_enabled, min_long_side=min_long_side, output_dir=output_dir, orig_name=orig_name, diff --git a/ttp.py b/ttp.py index 51ae2eb..bdeef4b 100644 --- a/ttp.py +++ b/ttp.py @@ -1,60 +1,102 @@ # -*- coding: utf-8 -*- """ -ttp.py — TTP_Image_Tile_Batch / TTP_Image_Assy 的独立移植。 +ttp.py — TTP_Image_Tile_Batch / TTP_Image_Assy 的 torch 化移植。 -逻辑与 Comfyui_TTP_Toolset 1.0.5 逐行对齐(PIL 渐变蒙版混合), -仅将 ComfyUI 的 tensor2pil/pil2tensor 换成本地实现。 +与早期 PIL 版的差异(两处根改动): -tensor 约定与 ComfyUI IMAGE 一致:BHWC、float32、[0, 1]、RGB。 +1. **全程 float32,不再经过 PIL/uint8**(原 P2-5)。 + 旧实现把 张量 → PIL(uint8) → crop → 张量、再 张量 → PIL(uint8) → paste → 张量, + 8bit 量化发生两次,模型输出的浮点精度在拼装环节被削掉。 + 现在切块用张量切片、拼装用 numpy 浮点累加,量化一次都不发生。 + +2. **2D 权重累加拼装,取代"先横向拼行、再纵向拼行"**(原 P2-4)。 + 旧实现先逐行横向混合、再逐行纵向混合:横竖交点(L 形接缝)处两侧处理 + 不对称,且必须先凑齐全部行图才能进入纵向阶段,内存上要多留一份整图。 + 现在与 `tiled_vae.tiled_decode_latent` 同构:每块带一个 2D 权重图, + 累加 acc += tile * w、wacc += w,最后 acc / wacc。 + + 权重是可分离的:w = wy ⊗ wx(水平/垂直各一条 ramp)。 + 每条 ramp 在与邻块的重叠区里做 1→0 / 0→1 的线性过渡, + 过渡带宽度 = min(padding, 实际重叠宽度),位置在重叠区居中 + —— 与旧 PIL 渐变蒙版的语义逐像素一致。 + + 由于 Σwx = Σwy = 1(在任何像素处),2D 权重之和恒为 1, + acc / wacc 的归一化在数学上是恒等操作(实现里仍保留除法以吸收浮点误差)。 + + 附带的等价性:旧的"先横后竖"两段式在数学上等价于可分离的 2D 权重 + (横向权重同时乘进上下两行),因此新实现在一维过渡带上与旧实现 + 逐像素一致,差别只在 L 形交点处 —— 那里新实现是对称的双线性过渡。 + +坐标口径(本模块的唯一约定): + - `positions` 必须是**目标尺度**(= 原图尺度 × 模型倍率 v)下的真实切块位置, + 即 tile_batch 返回的位置经 scale_positions 缩放后的结果; + - `original_size` 是目标尺度的画布尺寸 (width*v, height*v); + - `grid_size` 是 (列数, 行数),与 tiles 的行主序索引一致。 + +tensor 约定:BHWC、float32、[0, 1]、RGB。 """ from __future__ import annotations import numpy as np import torch -from PIL import Image -def tensor2pil(image: torch.Tensor) -> Image.Image: - """(H, W, C) float [0,1] -> PIL RGB。""" - arr = (image.detach().cpu().numpy() * 255.0).round().clip(0, 255).astype(np.uint8) - return Image.fromarray(arr, mode="RGB") +def _layout(size: int, tile_size: int, overlap: int): + """把长度为 `size` 的轴切成若干 `tile_size` 宽、相邻重叠 `overlap` 的块。 + + 返回 (块数, 步长)。步长 = tile_size - overlap,因此内部接缝的重叠量恰为 + `overlap`;最后一块右对齐到轴末端,其接缝重叠可能略有偏差 —— `assemble` + 用 `min(padding, 实际重叠)` 吸收,且权重和恒为 1,不会产生接缝。 + + overlap=0 时退化为无重叠整切(步长 = tile_size)。 + + 与 `compute_grid` 共用此函数,保证「规划面板显示的块数」与「tile_batch 实际 + 切出的块数」严格一致(旧实现两边各自推导 num/overlap,导致 f=128 时面板块数 + 偏大)。 + """ + if size <= tile_size: + return 1, 0 + step = tile_size - overlap + if step <= 0: + step = tile_size + overlap = 0 + num = (size - tile_size + step - 1) // step + 1 + # 保证最后一块覆盖到轴末端 + while (num - 1) * step + tile_size < size: + num += 1 + return num, step -def pil2tensor(image: Image.Image) -> torch.Tensor: - """PIL RGB -> (H, W, C) float [0,1]。""" - arr = np.asarray(image, dtype=np.float32) / 255.0 - return torch.from_numpy(arr) +def tile_batch(image_bhwc01: torch.Tensor, tile_width: int, tile_height: int, overlap: int = 0): + """等价 TTP_Image_Tile_Batch.tile_image(纯张量切片版)。 + 返回 (tiles BHWC, positions [(l,u,r,b)], original_size (w,h), grid_size (cols,rows))。 -def tile_batch(image_bhwc01: torch.Tensor, tile_width: int, tile_height: int): - """等价 TTP_Image_Tile_Batch.tile_image。 + 与 PIL 版的唯一区别:切块不再经过 uint8 量化,切出的是原始 float32 像素。 - 返回 (tiles BHWC, positions [(l,t,r,b)], original_size (w,h), grid_size (cols,rows))。 + `overlap` 是相邻块在【原图】上的重叠像素数(= pipeline 的 feather)。块按 + `tile_width - overlap` 步长推进,内部接缝重叠量恒为 `overlap`,因此 `assemble` + 用 `padding = feather * v` 作羽化宽度时与真实重叠一致,feather 具备单调语义 + (越大重叠越宽、接缝越柔)。这取代了旧实现把 feather 加进块尺寸、导致大 feather + 时有效羽化被整数除法反向截断的做法。 """ if image_bhwc01.dim() != 4 or image_bhwc01.shape[0] != 1: raise ValueError("tile_batch 期望单张图(B=1)") - image = tensor2pil(image_bhwc01.squeeze(0)) - img_width, img_height = image.size + _, img_height, img_width, _ = image_bhwc01.shape if img_width <= tile_width and img_height <= tile_height: + # 整图直喂:直接沿用输入张量(不复制、不量化) return ( - pil2tensor(image).unsqueeze(0), + image_bhwc01, [(0, 0, img_width, img_height)], (img_width, img_height), (1, 1), ) - def calculate_step(size, tile_size): - if size <= tile_size: - return 1, 0 - num_tiles = (size + tile_size - 1) // tile_size - overlap = (num_tiles * tile_size - size) // (num_tiles - 1) - step = tile_size - overlap - return num_tiles, step - - num_cols, step_x = calculate_step(img_width, tile_width) - num_rows, step_y = calculate_step(img_height, tile_height) + num_cols, step_x = _layout(img_width, tile_width, overlap) + num_rows, step_y = _layout(img_height, tile_height, overlap) + img = image_bhwc01.squeeze(0) # (H, W, C) tiles, positions = [], [] for y in range(num_rows): for x in range(num_cols): @@ -68,135 +110,162 @@ def tile_batch(image_bhwc01: torch.Tensor, tile_width: int, tile_height: int): if lower - upper < tile_height: upper = max(0, img_height - tile_height) - tiles.append(pil2tensor(image.crop((left, upper, right, lower)))) + tiles.append(img[upper:lower, left:right]) positions.append((left, upper, right, lower)) tiles = torch.stack(tiles, dim=0) return tiles, positions, (img_width, img_height), (num_cols, num_rows) -def tile_positions(img_width: int, img_height: int, tile_width: int, tile_height: int): - """只计算分块位置(等价于对一张纯色 EmptyImage 做 tile_batch)。 +def scale_positions(positions, factor: int): + """把【原图尺度】的分块位置整体缩放到【目标尺度】(模型倍率域)。 - 工作流 A06 中 dummy 分块的对象是纯黑 EmptyImage,其位置信息只取决于 - 尺寸参数,因此无需真实栅格化,直接复用同一套切分数学。 + 切块发生在原图尺度上,而每块经 VOSR2 放大 factor 倍后,其在输出画布上 + 覆盖的区间正是 [left*factor, right*factor)。因此拼装阶段唯一的正确 + 坐标来源,就是 tile_batch 返回的**真实** positions 乘以 factor。 + + 早期实现在 v× 画布上用 tile_positions 重新推导了一套网格,其步长由 + `overlap=(num*tile-size)//(num-1)` 独立算出,与真实切块步长不共除, + 导致块边界错位 1~4px —— 羽化混合的其实是不同原图位置的像素(接缝重影)。 + 本函数是"拼装只认一套坐标"的落点。 + + Args: + positions: tile_batch 返回的位置列表,每项为 (left, upper, right, lower)。 + factor: 放大倍数(整数),即 VOSR2 的模型倍率。 + + Returns: + 缩放后的位置列表,元素为 (left*f, upper*f, right*f, lower*f)。 """ - _, positions, original_size, grid_size = tile_batch( - torch.zeros(1, img_height, img_width, 3), tile_width, tile_height - ) - return positions, original_size, grid_size + if factor == 1: + return list(positions) + return [(l * factor, u * factor, r * factor, d * factor) + for (l, u, r, d) in positions] -class _Assembler: - """TTP_Image_Assy 的混合逻辑(原样移植)。""" +def _axis_profiles(starts, ends, padding: int) -> list[np.ndarray]: + """构造某个轴上每块的 1D 权重曲线(float32,长度 = 该块在该轴上的跨度)。 - @staticmethod - def create_gradient_mask(size, direction): - mask = Image.new("L", size) - for i in range(size[0] if direction == "horizontal" else size[1]): - value = int(255 * (1 - (i / size[0] if direction == "horizontal" else i / size[1]))) - if direction == "horizontal": - mask.paste(value, (i, 0, i + 1, size[1])) - else: - mask.paste(value, (0, i, size[0], i + 1)) - return mask + 权重语义(与旧 PIL 渐变蒙版逐像素一致): - @classmethod - def blend_tiles(cls, tile1, tile2, overlap_size, direction, padding): - blend_size = padding - if blend_size > overlap_size: - blend_size = overlap_size + - 块的"核心区"权重恒为 1; + - 与左邻块的重叠区:权重 0 线性升到 1; + - 与右邻块的重叠区:权重 1 线性降到 0; + - 过渡带宽度 = min(padding, 实际重叠宽度),且在重叠区内居中 + (左端留 offset_left 像素、右端留 offset_right 像素)。 - if blend_size == 0: - if direction == "horizontal": - result = Image.new("RGB", (tile1.width + tile2.width - overlap_size, tile1.height)) - result.paste(tile1.crop((0, 0, tile1.width - overlap_size, tile1.height)), (0, 0)) - result.paste(tile2, (tile1.width - overlap_size, 0)) - else: - result = Image.new("RGB", (tile1.width, tile1.height + tile2.height - overlap_size)) - result.paste(tile1.crop((0, 0, tile1.width, tile1.height - overlap_size)), (0, 0)) - result.paste(tile2, (0, tile1.height - overlap_size)) - return result + 这样在重叠区内两块权重之和恒为 1: + 左块 1-(u-off)/blend + 右块 (u-off)/blend = 1。 - offset_total = overlap_size - blend_size - offset_left = offset_total // 2 - offset_right = offset_total - offset_left + Args: + starts: 每块在该轴上的起点(递增)。 + ends: 每块在该轴上的终点。 + padding: 羽化宽度(过渡带最大宽度),单位与 starts/ends 相同。 - if direction == "horizontal": - size = (blend_size, tile1.height) - mask = cls.create_gradient_mask(size, direction) - crop_tile1 = tile1.crop((tile1.width - overlap_size + offset_left, 0, - tile1.width - offset_right, tile1.height)) - crop_tile2 = tile2.crop((offset_left, 0, offset_left + blend_size, tile2.height)) - if crop_tile1.size != crop_tile2.size: - raise ValueError(f"Crop sizes do not match: {crop_tile1.size} vs {crop_tile2.size}") - blended = Image.composite(crop_tile1, crop_tile2, mask) - result = Image.new("RGB", (tile1.width + tile2.width - overlap_size, tile1.height)) - result.paste(tile1.crop((0, 0, tile1.width - overlap_size + offset_left, tile1.height)), (0, 0)) - result.paste(blended, (tile1.width - overlap_size + offset_left, 0)) - result.paste(tile2.crop((offset_left + blend_size, 0, tile2.width, tile2.height)), - (tile1.width - offset_right, 0)) - else: - offset_total = overlap_size - blend_size - offset_top = offset_total // 2 - offset_bottom = offset_total - offset_top + Returns: + 每块一条权重曲线(list[np.ndarray])。 + """ + n = len(starts) + profiles = [] + for i in range(n): + length = ends[i] - starts[i] + left = np.ones(length, dtype=np.float32) + right = np.ones(length, dtype=np.float32) - size = (tile1.width, blend_size) - mask = cls.create_gradient_mask(size, direction) - crop_tile1 = tile1.crop((0, tile1.height - overlap_size + offset_top, - tile1.width, tile1.height - offset_bottom)) - crop_tile2 = tile2.crop((0, offset_top, tile2.width, offset_top + blend_size)) - if crop_tile1.size != crop_tile2.size: - raise ValueError(f"Crop sizes do not match: {crop_tile1.size} vs {crop_tile2.size}") - blended = Image.composite(crop_tile1, crop_tile2, mask) - result = Image.new("RGB", (tile1.width, tile1.height + tile2.height - overlap_size)) - result.paste(tile1.crop((0, 0, tile1.width, tile1.height - overlap_size + offset_top)), (0, 0)) - result.paste(blended, (0, tile1.height - overlap_size + offset_top)) - result.paste(tile2.crop((0, offset_top + blend_size, tile2.width, tile2.height)), - (0, tile1.height - offset_bottom)) - return result + # 与左邻块的重叠:本作右块,权重 0 → 1 + if i > 0: + overlap = ends[i - 1] - starts[i] + if overlap > 0: + blend = min(padding, overlap) + offset_left = (overlap - blend) // 2 + if blend > 0: + left[:offset_left] = 0.0 + left[offset_left:offset_left + blend] = ( + np.arange(blend, dtype=np.float32) / blend + ) + else: + left[:overlap] = 0.0 + + # 与右邻块的重叠:本作左块,权重 1 → 0 + if i < n - 1: + overlap = ends[i] - starts[i + 1] + if overlap > 0: + blend = min(padding, overlap) + offset_left = (overlap - blend) // 2 + band_start = length - overlap + offset_left + if blend > 0: + right[band_start:band_start + blend] = ( + 1.0 - np.arange(blend, dtype=np.float32) / blend + ) + right[band_start + blend:] = 0.0 + else: + right[length - overlap:] = 0.0 + + profiles.append(left * right) + return profiles -def assemble(tiles_bhwc: torch.Tensor, positions, original_size, grid_size, padding: int) -> torch.Tensor: - """等价 TTP_Image_Assy.assemble_image。tiles 尺寸应与 positions 对应块一致。""" +def assemble(tiles_bhwc: torch.Tensor, positions, original_size, grid_size, + padding: int) -> torch.Tensor: + """等价 TTP_Image_Assy.assemble_image(2D 权重累加版)。 + + 坐标口径(本移植的唯一约定): + - `positions` 必须是**目标尺度**(= 原图尺度 × 模型倍率 v)下的真实切块位置, + 即 tile_batch 返回的位置经 scale_positions 缩放后的结果; + - `original_size` 是目标尺度的画布尺寸 (width*v, height*v); + - `grid_size` 是 (列数, 行数),与 tiles 的行主序索引一致。 + + 拼装只认这一套坐标:混合区取自 `positions` 相邻块的实际重叠宽度, + 因此重叠区两侧取到的必然是同一段原图内容。 + + 实现:每块生成 2D 权重 w = wy ⊗ wx(可分离),累加 + acc[region] += tile * w + wacc[region] += w + 最后 acc / wacc 归一化。横向交点(L 形接缝)因此得到对称的双线性过渡, + 而不像旧实现那样受"先横后竖"的顺序影响。 + + Returns: + (1, H, W, 3) 的 float32 张量,值域 [0, 1]。 + """ num_cols, num_rows = grid_size - reconstructed = Image.new("RGB", original_size) + canvas_w, canvas_h = original_size + n_tiles = tiles_bhwc.shape[0] - # 逐行水平混合 - row_images = [] - for row in range(num_rows): - row_image = tensor2pil(tiles_bhwc[row * num_cols]) - for col in range(1, num_cols): - index = row * num_cols + col - tile_image = tensor2pil(tiles_bhwc[index]) - prev_right = positions[index - 1][2] - left = positions[index][0] - overlap_width = prev_right - left - if overlap_width > 0: - row_image = _Assembler.blend_tiles(row_image, tile_image, overlap_width, "horizontal", padding) - else: - new_width = row_image.width + tile_image.width - new_height = max(row_image.height, tile_image.height) - new_row = Image.new("RGB", (new_width, new_height)) - new_row.paste(row_image, (0, 0)) - new_row.paste(tile_image, (row_image.width, 0)) - row_image = new_row - row_images.append(row_image) + # 网格是规则的:各列的 x 区间相同,各行的 y 区间相同。 + # 取第 0 行得到列边界,取第 0 列得到行边界。 + col_starts = [positions[c][0] for c in range(num_cols)] + col_ends = [positions[c][2] for c in range(num_cols)] + row_starts = [positions[r * num_cols][1] for r in range(num_rows)] + row_ends = [positions[r * num_cols][3] for r in range(num_rows)] - # 逐行垂直混合 - final_image = row_images[0] - for row in range(1, num_rows): - prev_lower = positions[(row - 1) * num_cols][3] - upper = positions[row * num_cols][1] - overlap_height = prev_lower - upper - if overlap_height > 0: - final_image = _Assembler.blend_tiles(final_image, row_images[row], overlap_height, "vertical", padding) - else: - new_width = max(final_image.width, row_images[row].width) - new_height = final_image.height + row_images[row].height - new_final = Image.new("RGB", (new_width, new_height)) - new_final.paste(final_image, (0, 0)) - new_final.paste(row_images[row], (0, final_image.height)) - final_image = new_final + wx = _axis_profiles(col_starts, col_ends, padding) + wy = _axis_profiles(row_starts, row_ends, padding) - return pil2tensor(final_image).unsqueeze(0) + acc = np.zeros((canvas_h, canvas_w, 3), dtype=np.float32) + wacc = np.zeros((canvas_h, canvas_w), dtype=np.float32) + + for idx in range(n_tiles): + row = idx // num_cols + col = idx % num_cols + left, upper, right, lower = positions[idx] + h = lower - upper + w = right - left + + tile = tiles_bhwc[idx] + if tile.shape[0] != h or tile.shape[1] != w: + raise ValueError( + f"assemble: 第 {idx} 块尺寸 {tuple(tile.shape[:2])} 与 positions " + f"({h}, {w}) 不一致" + ) + + weight2d = wy[row][:, None] * wx[col][None, :] # (h, w) + region_acc = acc[upper:lower, left:right] + region_acc += tile.detach().cpu().numpy() * weight2d[:, :, None] + region_w = wacc[upper:lower, left:right] + region_w += weight2d + + # 权重和处处为 1(Σwx = Σwy = 1),除法在数学上是恒等的; + # 仍保留一次归一化以吸收浮点累加误差。wacc 为 0 的像素(理论上不存在, + # 因为块矩形恰好铺满画布)用极小分母兜底,结果仍是 0。 + np.maximum(wacc, 1e-12, out=wacc) + np.divide(acc, wacc[:, :, None], out=acc) + return torch.from_numpy(acc).unsqueeze(0)