stable-diffusion-webui
70 строк · 2.4 Кб
1import math
2
3from modules import scripts_postprocessing, ui_components
4import gradio as gr
5
6
7def split_pic(image, inverse_xy, width, height, overlap_ratio):
8if inverse_xy:
9from_w, from_h = image.height, image.width
10to_w, to_h = height, width
11else:
12from_w, from_h = image.width, image.height
13to_w, to_h = width, height
14h = from_h * to_w // from_w
15if inverse_xy:
16image = image.resize((h, to_w))
17else:
18image = image.resize((to_w, h))
19
20split_count = math.ceil((h - to_h * overlap_ratio) / (to_h * (1.0 - overlap_ratio)))
21y_step = (h - to_h) / (split_count - 1)
22for i in range(split_count):
23y = int(y_step * i)
24if inverse_xy:
25splitted = image.crop((y, 0, y + to_h, to_w))
26else:
27splitted = image.crop((0, y, to_w, y + to_h))
28yield splitted
29
30
31class ScriptPostprocessingSplitOversized(scripts_postprocessing.ScriptPostprocessing):
32name = "Split oversized images"
33order = 4000
34
35def ui(self):
36with ui_components.InputAccordion(False, label="Split oversized images") as enable:
37with gr.Row():
38split_threshold = gr.Slider(label='Threshold', value=0.5, minimum=0.0, maximum=1.0, step=0.05, elem_id="postprocess_split_threshold")
39overlap_ratio = gr.Slider(label='Overlap ratio', value=0.2, minimum=0.0, maximum=0.9, step=0.05, elem_id="postprocess_overlap_ratio")
40
41return {
42"enable": enable,
43"split_threshold": split_threshold,
44"overlap_ratio": overlap_ratio,
45}
46
47def process(self, pp: scripts_postprocessing.PostprocessedImage, enable, split_threshold, overlap_ratio):
48if not enable:
49return
50
51width = pp.shared.target_width
52height = pp.shared.target_height
53
54if not width or not height:
55return
56
57if pp.image.height > pp.image.width:
58ratio = (pp.image.width * height) / (pp.image.height * width)
59inverse_xy = False
60else:
61ratio = (pp.image.height * width) / (pp.image.width * height)
62inverse_xy = True
63
64if ratio >= 1.0 or ratio > split_threshold:
65return
66
67result, *others = split_pic(pp.image, inverse_xy, width, height, overlap_ratio)
68
69pp.image = result
70pp.extra_images = [pp.create_copy(x) for x in others]
71
72