Files
vosr2_core/ttp.py
T
2026-10-20 15:33:43 +08:00

203 lines
8.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
ttp.py — TTP_Image_Tile_Batch / TTP_Image_Assy 的独立移植。
逻辑与 Comfyui_TTP_Toolset 1.0.5 逐行对齐(PIL 渐变蒙版混合),
仅将 ComfyUI 的 tensor2pil/pil2tensor 换成本地实现。
tensor 约定与 ComfyUI IMAGE 一致: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 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):
"""等价 TTP_Image_Tile_Batch.tile_image。
返回 (tiles BHWC, positions [(l,t,r,b)], original_size (w,h), grid_size (cols,rows))。
"""
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
if img_width <= tile_width and img_height <= tile_height:
return (
pil2tensor(image).unsqueeze(0),
[(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)
tiles, positions = [], []
for y in range(num_rows):
for x in range(num_cols):
left = x * step_x
upper = y * step_y
right = min(left + tile_width, img_width)
lower = min(upper + tile_height, img_height)
if right - left < tile_width:
left = max(0, img_width - tile_width)
if lower - upper < tile_height:
upper = max(0, img_height - tile_height)
tiles.append(pil2tensor(image.crop((left, upper, right, lower))))
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)。
工作流 A06 中 dummy 分块的对象是纯黑 EmptyImage,其位置信息只取决于
尺寸参数,因此无需真实栅格化,直接复用同一套切分数学。
"""
_, 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
class _Assembler:
"""TTP_Image_Assy 的混合逻辑(原样移植)。"""
@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
@classmethod
def blend_tiles(cls, tile1, tile2, overlap_size, direction, padding):
blend_size = padding
if blend_size > overlap_size:
blend_size = overlap_size
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
offset_total = overlap_size - blend_size
offset_left = offset_total // 2
offset_right = offset_total - offset_left
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
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
def assemble(tiles_bhwc: torch.Tensor, positions, original_size, grid_size, padding: int) -> torch.Tensor:
"""等价 TTP_Image_Assy.assemble_image。tiles 尺寸应与 positions 对应块一致。"""
num_cols, num_rows = grid_size
reconstructed = Image.new("RGB", original_size)
# 逐行水平混合
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)
# 逐行垂直混合
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
return pil2tensor(final_image).unsqueeze(0)