当前位置:   article > 正文

[linux-sd-webui]之img2img_inpaint_full_res_padding

inpaint_full_res_padding

AUTOMATIC1111 GUI: A Beginner's Guide - Stable Diffusion ArtAUTOMATIC1111 (A1111 for short) Stable Diffusion webui is the de facto GUI for advanced users. Thanks to the passionate community, most new features come tohttps://stable-diffusion-art.com/automatic1111/#Text-to-image_tab1.参数

  1. id_task='task(w9j5f4nn7lpfojk)',
  2. mode=0,
  3. prompt='a highly detailed tower designed by Zaha hadid with few metal and lots of glass,roads around with much traffic,in a city with a lot of greenery,aerial view, stunning sunny lighting, foggy atmosphere, vivid colors, Photo-grade rendering, Realistic style,8k,high res,highly detialed, ray tracing,vray render,masterpiece, best quality,rendered by Mir. and Brick visual',
  4. negative_prompt='',
  5. prompt_styles=[],
  6. init_img=Image.open(),
  7. sketch=None, # 可以勾画初始草图
  8. init_img_with_mask=None,
  9. inpaint_color_sketch=None,
  10. inpaint_color_sketch_orig=None,
  11. init_img_inpaint=None,
  12. init_mask_inpaint=None,
  13. steps=20,
  14. sampler_index=0,
  15. mask_blur=4,
  16. mask_alpha=0,
  17. inpainting_fill=1,
  18. restore_faces=False,
  19. tiling=False,
  20. n_iter=1,
  21. batch_size=1,
  22. cfg_scale=7,
  23. image_cfg_scale=1.5,
  24. denoising_strength=0.75,# 控制图像变化的程度,如果=0,没有任何变化,如果=1,则新图像不会跟随输入图像,0.75是个很好的起点
  25. seed=-1,
  26. subseed=-1,
  27. subseed_strength=0,
  28. seed_resize_from_h=0,
  29. seed_resize_from_w=0,
  30. seed_enable_extras=False,
  31. selected_scale_tab=0,
  32. height=512,
  33. width=512,
  34. scale_by=1,
  35. resize_mode=0, # 0(just resize):缩放输入图像以适应新的图像尺寸,会拉伸或者挤压图像,1(crop and resize):使画布适应输入图像,多余部分删除,保留原始图像的纵横比,3(resize and fill):将输入图像适应画布,额外部分用输入图像平均颜色填充,保留纵横比,4(just resize(latent upscale)):类似于just resize,但缩放是在隐空间中完成,使用>0.5的denoising strength以避免图像模糊。
  36. inpaint_full_res=0,
  37. inpaint_full_res_padding=32,
  38. inpainting_mask_invert=0,
  39. img2img_batch_input_dir="",
  40. img2img_batch_output_dir='',
  41. img2img_batch_inpaint_mask_dir='',
  42. override_settings_texts=[]

inpaint upload:允许上传单独的mask,而不是绘制。

main.py

  1. import sys
  2. import logging
  3. logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
  4. from modules import paths, timer, import_hook, errors
  5. startup_timer = timer.Timer()
  6. from modules import shared, devices, sd_samplers, upscaler, extensions, localization, ui_tempdir, ui_extra_networks
  7. import modules.scripts
  8. import modules.sd_models
  9. import modules.img2img
  10. from PIL import Image
  11. from modules.shared import cmd_opts
  12. def initialize():
  13. extensions.list_extensions()
  14. localization.list_localizations(cmd_opts.localizations_dir)
  15. startup_timer.record("list extensions")
  16. modules.sd_models.setup_model() # 加载模型
  17. startup_timer.record("list SD models")
  18. modules.scripts.load_scripts()
  19. startup_timer.record("load scripts")
  20. try:
  21. modules.sd_models.load_model()
  22. except Exception as e:
  23. errors.display(e, "loading stable diffusion model")
  24. print("", file=sys.stderr)
  25. print("Stable diffusion model failed to load, exiting", file=sys.stderr)
  26. exit(1)
  27. startup_timer.record("load SD checkpoint")
  28. def webui():
  29. initialize()
  30. image, _, _, _ = modules.img2img.img2img(
  31. id_task='task(w9j5f4nn7lpfojk)',
  32. mode=0,
  33. prompt='a highly detailed tower designed by Zaha hadid with few metal and lots of glass,roads around with much traffic,in a city with a lot of greenery,aerial view, stunning sunny lighting, foggy atmosphere, vivid colors, Photo-grade rendering, Realistic style,8k,high res,highly detialed, ray tracing,vray render,masterpiece, best quality,rendered by Mir. and Brick visual',
  34. negative_prompt='',
  35. prompt_styles=[],
  36. init_img=Image.open(),
  37. sketch=None,
  38. init_img_with_mask=None,
  39. inpaint_color_sketch=None,
  40. inpaint_color_sketch_orig=None,
  41. init_img_inpaint=None,
  42. init_mask_inpaint=None,
  43. steps=20,
  44. sampler_index=0,
  45. mask_blur=4,
  46. mask_alpha=0,
  47. inpainting_fill=1,
  48. restore_faces=False,
  49. tiling=False,
  50. n_iter=1,
  51. batch_size=1,
  52. cfg_scale=7,
  53. image_cfg_scale=1.5,
  54. denoising_strength=0.75,
  55. seed=-1,
  56. subseed=-1,
  57. subseed_strength=0,
  58. seed_resize_from_h=0,
  59. seed_resize_from_w=0,
  60. seed_enable_extras=False,
  61. selected_scale_tab=0,
  62. height=512,
  63. width=512,
  64. scale_by=1,
  65. resize_mode=0,
  66. inpaint_full_res=0,
  67. inpaint_full_res_padding=32,
  68. inpainting_mask_invert=0,
  69. img2img_batch_input_dir="",
  70. img2img_batch_output_dir='',
  71. img2img_batch_inpaint_mask_dir='',
  72. override_settings_texts=[]
  73. )
  74. for i in range(len(image)):
  75. image[i].save(f"{i}.png")
  76. if __name__ == "__main__":
  77. webui()

modules/img2img.py

  1. import math
  2. import os
  3. import sys
  4. import traceback
  5. import numpy as np
  6. from PIL import Image, ImageOps, ImageFilter, ImageEnhance, ImageChops, UnidentifiedImageError
  7. from modules import devices, sd_samplers
  8. from modules.generation_parameters_copypaste import create_override_settings_dict
  9. from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images
  10. from modules.shared import opts, state
  11. import modules.shared as shared
  12. import modules.processing as processing
  13. from modules.ui import plaintext_to_html
  14. import modules.images as images
  15. import modules.scripts
  16. def process_batch(p, input_dir, output_dir, inpaint_mask_dir, args):
  17. processing.fix_seed(p)
  18. images = shared.listfiles(input_dir)
  19. is_inpaint_batch = False
  20. if inpaint_mask_dir:
  21. inpaint_masks = shared.listfiles(inpaint_mask_dir)
  22. is_inpaint_batch = len(inpaint_masks) > 0
  23. if is_inpaint_batch:
  24. print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")
  25. print(f"Will process {len(images)} images, creating {p.n_iter * p.batch_size} new images for each.")
  26. save_normally = output_dir == ''
  27. p.do_not_save_grid = True
  28. p.do_not_save_samples = not save_normally
  29. state.job_count = len(images) * p.n_iter
  30. for i, image in enumerate(images):
  31. state.job = f"{i+1} out of {len(images)}"
  32. if state.skipped:
  33. state.skipped = False
  34. if state.interrupted:
  35. break
  36. try:
  37. img = Image.open(image)
  38. except UnidentifiedImageError:
  39. continue
  40. # Use the EXIF orientation of photos taken by smartphones.
  41. img = ImageOps.exif_transpose(img)
  42. p.init_images = [img] * p.batch_size
  43. if is_inpaint_batch:
  44. # try to find corresponding mask for an image using simple filename matching
  45. mask_image_path = os.path.join(inpaint_mask_dir, os.path.basename(image))
  46. # if not found use first one ("same mask for all images" use-case)
  47. if not mask_image_path in inpaint_masks:
  48. mask_image_path = inpaint_masks[0]
  49. mask_image = Image.open(mask_image_path)
  50. p.image_mask = mask_image
  51. proc = modules.scripts.scripts_img2img.run(p, *args)
  52. if proc is None:
  53. proc = process_images(p)
  54. for n, processed_image in enumerate(proc.images):
  55. filename = os.path.basename(image)
  56. if n > 0:
  57. left, right = os.path.splitext(filename)
  58. filename = f"{left}-{n}{right}"
  59. if not save_normally:
  60. os.makedirs(output_dir, exist_ok=True)
  61. if processed_image.mode == 'RGBA':
  62. processed_image = processed_image.convert("RGB")
  63. processed_image.save(os.path.join(output_dir, filename))
  64. 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):
  65. args = (
  66. (0, '<ul>\n<li><code>CFG Scale</code> should be 2 or lower.</li>\n</ul>\n', True, True, '', '', True, 50, True, 1, 0, False, 4, 0.5, 'Linear', 'None', '<p style="margin-bottom:0.75em">Recommended settings: Sampling Steps: 80-100, Sampler: Euler a, Denoising strength: 0.8</p>', 128, 8, ['left', 'right', 'up', 'down'], 1, 0.05, 128, 4, 0, ['left', 'right', 'up', 'down'], False, False, 'positive', 'comma', 0, False, False, '', '<p style="margin-bottom:0.75em">Will upscale the image by the selected scale factor; use width and height sliders to set tile size</p>', 64, 0, 2, 1, '', [], 0, '', [], 0, '', [], True, False, False, False, 0))
  67. override_settings = create_override_settings_dict(override_settings_texts)
  68. is_batch = mode == 5
  69. if mode == 0: # img2img
  70. image = init_img.convert("RGB")
  71. mask = None
  72. elif mode == 1: # img2img sketch
  73. image = sketch.convert("RGB")
  74. mask = None
  75. elif mode == 2: # inpaint
  76. image, mask = init_img_with_mask["image"], init_img_with_mask["mask"]
  77. alpha_mask = ImageOps.invert(image.split()[-1]).convert('L').point(lambda x: 255 if x > 0 else 0, mode='1')
  78. mask = ImageChops.lighter(alpha_mask, mask.convert('L')).convert('L')
  79. image = image.convert("RGB")
  80. elif mode == 3: # inpaint sketch
  81. image = inpaint_color_sketch
  82. orig = inpaint_color_sketch_orig or inpaint_color_sketch
  83. pred = np.any(np.array(image) != np.array(orig), axis=-1)
  84. mask = Image.fromarray(pred.astype(np.uint8) * 255, "L")
  85. mask = ImageEnhance.Brightness(mask).enhance(1 - mask_alpha / 100)
  86. blur = ImageFilter.GaussianBlur(mask_blur)
  87. image = Image.composite(image.filter(blur), orig, mask.filter(blur))
  88. image = image.convert("RGB")
  89. elif mode == 4: # inpaint upload mask
  90. image = init_img_inpaint
  91. mask = init_mask_inpaint
  92. else:
  93. image = None
  94. mask = None
  95. # Use the EXIF orientation of photos taken by smartphones.
  96. if image is not None:
  97. image = ImageOps.exif_transpose(image)
  98. if selected_scale_tab == 1:
  99. assert image, "Can't scale by because no image is selected"
  100. width = int(image.width * scale_by)
  101. height = int(image.height * scale_by)
  102. assert 0. <= denoising_strength <= 1., 'can only work with strength in [0.0, 1.0]'
  103. p = StableDiffusionProcessingImg2Img(
  104. sd_model=shared.sd_model,
  105. outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,
  106. outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,
  107. prompt=prompt,
  108. negative_prompt=negative_prompt,
  109. styles=prompt_styles,
  110. seed=seed,
  111. subseed=subseed,
  112. subseed_strength=subseed_strength,
  113. seed_resize_from_h=seed_resize_from_h,
  114. seed_resize_from_w=seed_resize_from_w,
  115. seed_enable_extras=seed_enable_extras,
  116. sampler_name=sd_samplers.samplers_for_img2img[sampler_index].name,
  117. batch_size=batch_size,
  118. n_iter=n_iter,
  119. steps=steps,
  120. cfg_scale=cfg_scale,
  121. width=width,
  122. height=height,
  123. restore_faces=restore_faces,
  124. tiling=tiling,
  125. init_images=[image],
  126. mask=mask,
  127. mask_blur=mask_blur,
  128. inpainting_fill=inpainting_fill,
  129. resize_mode=resize_mode,
  130. denoising_strength=denoising_strength,
  131. image_cfg_scale=image_cfg_scale,
  132. inpaint_full_res=inpaint_full_res,
  133. inpaint_full_res_padding=inpaint_full_res_padding,
  134. inpainting_mask_invert=inpainting_mask_invert,
  135. override_settings=override_settings,
  136. )
  137. p.scripts = modules.scripts.scripts_img2img # scriptrunner
  138. p.script_args = args
  139. if shared.cmd_opts.enable_console_prompts:
  140. print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
  141. if mask:
  142. p.extra_generation_params["Mask blur"] = mask_blur
  143. if is_batch:
  144. assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"
  145. process_batch(p, img2img_batch_input_dir, img2img_batch_output_dir, img2img_batch_inpaint_mask_dir, args)
  146. processed = Processed(p, [], p.seed, "")
  147. else:
  148. processed = modules.scripts.scripts_img2img.run(p, *args)
  149. if processed is None:
  150. processed = process_images(p)
  151. p.close()
  152. shared.total_tqdm.clear()
  153. generation_info_js = processed.js()
  154. if opts.samples_log_stdout:
  155. print(generation_info_js)
  156. if opts.do_not_show_images:
  157. processed.images = []
  158. return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments)
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55238
推荐阅读
相关标签
  

闽ICP备14008679号