Path: blob/master/extensions-builtin/postprocessing-for-training/scripts/postprocessing_split_oversized.py
2448 views
import math12from modules import scripts_postprocessing, ui_components3import gradio as gr456def split_pic(image, inverse_xy, width, height, overlap_ratio):7if inverse_xy:8from_w, from_h = image.height, image.width9to_w, to_h = height, width10else:11from_w, from_h = image.width, image.height12to_w, to_h = width, height13h = from_h * to_w // from_w14if inverse_xy:15image = image.resize((h, to_w))16else:17image = image.resize((to_w, h))1819split_count = math.ceil((h - to_h * overlap_ratio) / (to_h * (1.0 - overlap_ratio)))20y_step = (h - to_h) / (split_count - 1)21for i in range(split_count):22y = int(y_step * i)23if inverse_xy:24splitted = image.crop((y, 0, y + to_h, to_w))25else:26splitted = image.crop((0, y, to_w, y + to_h))27yield splitted282930class ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):31name = "Split oversized images"32order = 40003334def ui(self):35with ui_components.InputAccordion(False, label="Split oversized images") as enable:36with gr.Row():37split_threshold = gr.Slider(label='Threshold', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_split_threshold")38overlap_ratio = gr.Slider(label='Overlap ratio', value=0.2, minimum=0.0, maximum=0.9, step=0.05, elem_id="postprocess_overlap_ratio")3940return {41"enable": enable,42"split_threshold": split_threshold,43"overlap_ratio": overlap_ratio,44}4546def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, split_threshold, overlap_ratio):47if not enable:48return4950width = pp.shared.target_width51height = pp.shared.target_height5253if not width or not height:54return5556if pp.image.height > pp.image.width:57ratio = (pp.image.width * height) / (pp.image.height * width)58inverse_xy = False59else:60ratio = (pp.image.height * width) / (pp.image.width * height)61inverse_xy = True6263if ratio >= 1.0 or ratio > split_threshold:64return6566result, *others = split_pic(pp.image, inverse_xy, width, height, overlap_ratio)6768pp.image = result69pp.extra_images = [pp.create_copy(x) for x in others]70717273