优化
This commit is contained in:
2026-10-27 14:43:23 +08:00
parent 4daf1df630
commit 064e3d2132
4 changed files with 461 additions and 290 deletions
+166 -56
View File
@@ -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,