优化
优化
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user