img2img.py 8.5 KB
Newer Older
1
import os
A
Artem Kotov 已提交
2
from pathlib import Path
3

4
import numpy as np
Z
Z_nonymous 已提交
5
from PIL import Image, ImageOps, ImageFilter, ImageEnhance, ImageChops, UnidentifiedImageError
6

A
AUTOMATIC 已提交
7
from modules import sd_samplers
8
from modules.generation_parameters_copypaste import create_override_settings_dict
9 10 11 12 13
from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images
from modules.shared import opts, state
import modules.shared as shared
import modules.processing as processing
from modules.ui import plaintext_to_html
A
AUTOMATIC 已提交
14
import modules.scripts
15

16

A
Artem Kotov 已提交
17
def process_batch(p, input_dir, output_dir, inpaint_mask_dir, args, to_scale=False, scale_by=1.0):
18 19
    processing.fix_seed(p)

20
    images = shared.listfiles(input_dir)
21

T
Thurion 已提交
22 23 24
    is_inpaint_batch = False
    if inpaint_mask_dir:
        inpaint_masks = shared.listfiles(inpaint_mask_dir)
25
        is_inpaint_batch = bool(inpaint_masks)
A
Andrii Skaliuk 已提交
26 27
        print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")

28 29
    print(f"Will process {len(images)} images, creating {p.n_iter * p.batch_size} new images for each.")

30 31
    save_normally = output_dir == ''

32
    p.do_not_save_grid = True
33
    p.do_not_save_samples = not save_normally
34 35 36 37 38

    state.job_count = len(images) * p.n_iter

    for i, image in enumerate(images):
        state.job = f"{i+1} out of {len(images)}"
39 40
        if state.skipped:
            state.skipped = False
41 42 43 44

        if state.interrupted:
            break

Z
Z_nonymous 已提交
45 46
        try:
            img = Image.open(image)
W
w-e-w 已提交
47 48
        except UnidentifiedImageError as e:
            print(e)
Z
Z_nonymous 已提交
49
            continue
50
        # Use the EXIF orientation of photos taken by smartphones.
51
        img = ImageOps.exif_transpose(img)
A
ruffed  
Artem Kotov 已提交
52

A
Artem Kotov 已提交
53 54 55
        if to_scale:
            p.width = int(img.width * scale_by)
            p.height = int(img.height * scale_by)
A
ruffed  
Artem Kotov 已提交
56

57 58
        p.init_images = [img] * p.batch_size

59
        image_path = Path(image)
A
Andrii Skaliuk 已提交
60 61
        if is_inpaint_batch:
            # try to find corresponding mask for an image using simple filename matching
62
            if len(inpaint_masks) == 1:
A
Andrii Skaliuk 已提交
63
                mask_image_path = inpaint_masks[0]
64 65
            else:
                # try to find corresponding mask for an image using simple filename matching
66
                mask_image_dir = Path(inpaint_mask_dir)
67 68 69
                masks_found = list(mask_image_dir.glob(f"{image_path.stem}.*"))

                if len(masks_found) == 0:
70 71
                    print(f"Warning: mask is not found for {image_path} in {mask_image_dir}. Skipping it.")
                    continue
72 73 74 75 76

                # it should contain only 1 matching mask
                # otherwise user has many masks with the same name but different extensions
                mask_image_path = masks_found[0]

A
Andrii Skaliuk 已提交
77 78 79
            mask_image = Image.open(mask_image_path)
            p.image_mask = mask_image

80 81 82 83 84
        proc = modules.scripts.scripts_img2img.run(p, *args)
        if proc is None:
            proc = process_images(p)

        for n, processed_image in enumerate(proc.images):
85
            filename = image_path.name
86 87 88 89 90

            if n > 0:
                left, right = os.path.splitext(filename)
                filename = f"{left}-{n}{right}"

91
            if not save_normally:
92
                os.makedirs(output_dir, exist_ok=True)
V
Vladimir Mandic 已提交
93 94
                if processed_image.mode == 'RGBA':
                    processed_image = processed_image.convert("RGB")
95
                processed_image.save(os.path.join(output_dir, filename))
96 97


98
def img2img(id_task: str, mode: int, prompt: str, negative_prompt: str, prompt_styles, init_img, sketch, init_img_with_mask, inpaint_color_sketch, inpaint_color_sketch_orig, init_img_inpaint, init_mask_inpaint, steps: int, sampler_index: int, mask_blur: int, mask_alpha: float, inpainting_fill: int, restore_faces: bool, tiling: bool, n_iter: int, batch_size: int, cfg_scale: float, image_cfg_scale: float, denoising_strength: float, seed: int, subseed: int, subseed_strength: float, seed_resize_from_h: int, seed_resize_from_w: int, seed_enable_extras: bool, selected_scale_tab: int, height: int, width: int, scale_by: float, resize_mode: int, inpaint_full_res: bool, inpaint_full_res_padding: int, inpainting_mask_invert: int, img2img_batch_input_dir: str, img2img_batch_output_dir: str, img2img_batch_inpaint_mask_dir: str, override_settings_texts, *args):
99 100
    override_settings = create_override_settings_dict(override_settings_texts)

101 102 103 104 105 106 107 108 109 110 111
    is_batch = mode == 5

    if mode == 0:  # img2img
        image = init_img.convert("RGB")
        mask = None
    elif mode == 1:  # img2img sketch
        image = sketch.convert("RGB")
        mask = None
    elif mode == 2:  # inpaint
        image, mask = init_img_with_mask["image"], init_img_with_mask["mask"]
        alpha_mask = ImageOps.invert(image.split()[-1]).convert('L').point(lambda x: 255 if x > 0 else 0, mode='1')
112 113
        mask = mask.convert('L').point(lambda x: 255 if x > 128 else 0, mode='1')
        mask = ImageChops.lighter(alpha_mask, mask).convert('L')
114 115 116 117 118 119 120 121 122 123 124 125 126
        image = image.convert("RGB")
    elif mode == 3:  # inpaint sketch
        image = inpaint_color_sketch
        orig = inpaint_color_sketch_orig or inpaint_color_sketch
        pred = np.any(np.array(image) != np.array(orig), axis=-1)
        mask = Image.fromarray(pred.astype(np.uint8) * 255, "L")
        mask = ImageEnhance.Brightness(mask).enhance(1 - mask_alpha / 100)
        blur = ImageFilter.GaussianBlur(mask_blur)
        image = Image.composite(image.filter(blur), orig, mask.filter(blur))
        image = image.convert("RGB")
    elif mode == 4:  # inpaint upload mask
        image = init_img_inpaint
        mask = init_mask_inpaint
127
    else:
128
        image = None
129 130
        mask = None

131
    # Use the EXIF orientation of photos taken by smartphones.
132
    if image is not None:
133
        image = ImageOps.exif_transpose(image)
134

A
Artem Kotov 已提交
135
    if selected_scale_tab == 1 and not is_batch:
136 137 138 139 140
        assert image, "Can't scale by because no image is selected"

        width = int(image.width * scale_by)
        height = int(image.height * scale_by)

141 142 143 144 145 146 147
    assert 0. <= denoising_strength <= 1., 'can only work with strength in [0.0, 1.0]'

    p = StableDiffusionProcessingImg2Img(
        sd_model=shared.sd_model,
        outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,
        outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,
        prompt=prompt,
148
        negative_prompt=negative_prompt,
149
        styles=prompt_styles,
150
        seed=seed,
151 152 153 154
        subseed=subseed,
        subseed_strength=subseed_strength,
        seed_resize_from_h=seed_resize_from_h,
        seed_resize_from_w=seed_resize_from_w,
155
        seed_enable_extras=seed_enable_extras,
156
        sampler_name=sd_samplers.samplers_for_img2img[sampler_index].name,
157 158 159 160 161 162
        batch_size=batch_size,
        n_iter=n_iter,
        steps=steps,
        cfg_scale=cfg_scale,
        width=width,
        height=height,
A
AUTOMATIC 已提交
163
        restore_faces=restore_faces,
164
        tiling=tiling,
165 166 167 168 169 170
        init_images=[image],
        mask=mask,
        mask_blur=mask_blur,
        inpainting_fill=inpainting_fill,
        resize_mode=resize_mode,
        denoising_strength=denoising_strength,
K
Kyle 已提交
171
        image_cfg_scale=image_cfg_scale,
172
        inpaint_full_res=inpaint_full_res,
173
        inpaint_full_res_padding=inpaint_full_res_padding,
A
AUTOMATIC 已提交
174
        inpainting_mask_invert=inpainting_mask_invert,
175
        override_settings=override_settings,
176
    )
177

D
dennissheng 已提交
178
    p.scripts = modules.scripts.scripts_img2img
179
    p.script_args = args
M
MalumaDev 已提交
180

181 182
    if shared.cmd_opts.enable_console_prompts:
        print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
183

184 185
    if mask:
        p.extra_generation_params["Mask blur"] = mask_blur
A
AUTOMATIC 已提交
186

187
    if is_batch:
188 189
        assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"

A
Artem Kotov 已提交
190
        process_batch(p, img2img_batch_input_dir, img2img_batch_output_dir, img2img_batch_inpaint_mask_dir, args, to_scale=selected_scale_tab == 1, scale_by=scale_by)
191

192
        processed = Processed(p, [], p.seed, "")
193
    else:
A
AUTOMATIC 已提交
194
        processed = modules.scripts.scripts_img2img.run(p, *args)
A
AUTOMATIC 已提交
195 196 197
        if processed is None:
            processed = process_images(p)

198 199
    p.close()

200
    shared.total_tqdm.clear()
201

202 203 204 205
    generation_info_js = processed.js()
    if opts.samples_log_stdout:
        print(generation_info_js)

A
AUTOMATIC 已提交
206 207 208
    if opts.do_not_show_images:
        processed.images = []

209
    return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments)