img2img.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. import os
  2. from pathlib import Path
  3. import numpy as np
  4. from PIL import Image, ImageOps, ImageFilter, ImageEnhance, ImageChops, UnidentifiedImageError
  5. from modules import sd_samplers
  6. from modules.generation_parameters_copypaste import create_override_settings_dict
  7. from modules.processing import Processed, StableDiffusionProcessingImg2Img, process_images
  8. from modules.shared import opts, state
  9. import modules.shared as shared
  10. import modules.processing as processing
  11. from modules.ui import plaintext_to_html
  12. import modules.scripts
  13. def process_batch(p, input_dir, output_dir, inpaint_mask_dir, args, to_scale=False, scale_by=1.0):
  14. processing.fix_seed(p)
  15. images = shared.listfiles(input_dir)
  16. is_inpaint_batch = False
  17. if inpaint_mask_dir:
  18. inpaint_masks = shared.listfiles(inpaint_mask_dir)
  19. is_inpaint_batch = bool(inpaint_masks)
  20. if is_inpaint_batch:
  21. print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")
  22. print(f"Will process {len(images)} images, creating {p.n_iter * p.batch_size} new images for each.")
  23. save_normally = output_dir == ''
  24. p.do_not_save_grid = True
  25. p.do_not_save_samples = not save_normally
  26. state.job_count = len(images) * p.n_iter
  27. for i, image in enumerate(images):
  28. state.job = f"{i+1} out of {len(images)}"
  29. if state.skipped:
  30. state.skipped = False
  31. if state.interrupted:
  32. break
  33. try:
  34. img = Image.open(image)
  35. except UnidentifiedImageError as e:
  36. print(e)
  37. continue
  38. # Use the EXIF orientation of photos taken by smartphones.
  39. img = ImageOps.exif_transpose(img)
  40. if to_scale:
  41. p.width = int(img.width * scale_by)
  42. p.height = int(img.height * scale_by)
  43. p.init_images = [img] * p.batch_size
  44. image_path = Path(image)
  45. if is_inpaint_batch:
  46. # try to find corresponding mask for an image using simple filename matching
  47. if len(inpaint_masks) == 1:
  48. mask_image_path = inpaint_masks[0]
  49. else:
  50. # try to find corresponding mask for an image using simple filename matching
  51. mask_image_dir = Path(inpaint_mask_dir)
  52. masks_found = list(mask_image_dir.glob(f"{image_path.stem}.*"))
  53. if len(masks_found) == 0:
  54. print(f"Warning: mask is not found for {image_path} in {mask_image_dir}. Skipping it.")
  55. continue
  56. # it should contain only 1 matching mask
  57. # otherwise user has many masks with the same name but different extensions
  58. mask_image_path = masks_found[0]
  59. mask_image = Image.open(mask_image_path)
  60. p.image_mask = mask_image
  61. proc = modules.scripts.scripts_img2img.run(p, *args)
  62. if proc is None:
  63. proc = process_images(p)
  64. for n, processed_image in enumerate(proc.images):
  65. filename = image_path.name
  66. if n > 0:
  67. left, right = os.path.splitext(filename)
  68. filename = f"{left}-{n}{right}"
  69. if not save_normally:
  70. os.makedirs(output_dir, exist_ok=True)
  71. if processed_image.mode == 'RGBA':
  72. processed_image = processed_image.convert("RGB")
  73. processed_image.save(os.path.join(output_dir, filename))
  74. 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):
  75. override_settings = create_override_settings_dict(override_settings_texts)
  76. is_batch = mode == 5
  77. if mode == 0: # img2img
  78. image = init_img.convert("RGB")
  79. mask = None
  80. elif mode == 1: # img2img sketch
  81. image = sketch.convert("RGB")
  82. mask = None
  83. elif mode == 2: # inpaint
  84. image, mask = init_img_with_mask["image"], init_img_with_mask["mask"]
  85. alpha_mask = ImageOps.invert(image.split()[-1]).convert('L').point(lambda x: 255 if x > 0 else 0, mode='1')
  86. mask = mask.convert('L').point(lambda x: 255 if x > 128 else 0, mode='1')
  87. mask = ImageChops.lighter(alpha_mask, mask).convert('L')
  88. image = image.convert("RGB")
  89. elif mode == 3: # inpaint sketch
  90. image = inpaint_color_sketch
  91. orig = inpaint_color_sketch_orig or inpaint_color_sketch
  92. pred = np.any(np.array(image) != np.array(orig), axis=-1)
  93. mask = Image.fromarray(pred.astype(np.uint8) * 255, "L")
  94. mask = ImageEnhance.Brightness(mask).enhance(1 - mask_alpha / 100)
  95. blur = ImageFilter.GaussianBlur(mask_blur)
  96. image = Image.composite(image.filter(blur), orig, mask.filter(blur))
  97. image = image.convert("RGB")
  98. elif mode == 4: # inpaint upload mask
  99. image = init_img_inpaint
  100. mask = init_mask_inpaint
  101. else:
  102. image = None
  103. mask = None
  104. # Use the EXIF orientation of photos taken by smartphones.
  105. if image is not None:
  106. image = ImageOps.exif_transpose(image)
  107. if selected_scale_tab == 1 and not is_batch:
  108. assert image, "Can't scale by because no image is selected"
  109. width = int(image.width * scale_by)
  110. height = int(image.height * scale_by)
  111. assert 0. <= denoising_strength <= 1., 'can only work with strength in [0.0, 1.0]'
  112. p = StableDiffusionProcessingImg2Img(
  113. sd_model=shared.sd_model,
  114. outpath_samples=opts.outdir_samples or opts.outdir_img2img_samples,
  115. outpath_grids=opts.outdir_grids or opts.outdir_img2img_grids,
  116. prompt=prompt,
  117. negative_prompt=negative_prompt,
  118. styles=prompt_styles,
  119. seed=seed,
  120. subseed=subseed,
  121. subseed_strength=subseed_strength,
  122. seed_resize_from_h=seed_resize_from_h,
  123. seed_resize_from_w=seed_resize_from_w,
  124. seed_enable_extras=seed_enable_extras,
  125. sampler_name=sd_samplers.samplers_for_img2img[sampler_index].name,
  126. batch_size=batch_size,
  127. n_iter=n_iter,
  128. steps=steps,
  129. cfg_scale=cfg_scale,
  130. width=width,
  131. height=height,
  132. restore_faces=restore_faces,
  133. tiling=tiling,
  134. init_images=[image],
  135. mask=mask,
  136. mask_blur=mask_blur,
  137. inpainting_fill=inpainting_fill,
  138. resize_mode=resize_mode,
  139. denoising_strength=denoising_strength,
  140. image_cfg_scale=image_cfg_scale,
  141. inpaint_full_res=inpaint_full_res,
  142. inpaint_full_res_padding=inpaint_full_res_padding,
  143. inpainting_mask_invert=inpainting_mask_invert,
  144. override_settings=override_settings,
  145. )
  146. p.scripts = modules.scripts.scripts_img2img
  147. p.script_args = args
  148. if shared.cmd_opts.enable_console_prompts:
  149. print(f"\nimg2img: {prompt}", file=shared.progress_print_out)
  150. if mask:
  151. p.extra_generation_params["Mask blur"] = mask_blur
  152. if is_batch:
  153. assert not shared.cmd_opts.hide_ui_dir_config, "Launched with --hide-ui-dir-config, batch img2img disabled"
  154. 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)
  155. processed = Processed(p, [], p.seed, "")
  156. else:
  157. processed = modules.scripts.scripts_img2img.run(p, *args)
  158. if processed is None:
  159. processed = process_images(p)
  160. p.close()
  161. shared.total_tqdm.clear()
  162. generation_info_js = processed.js()
  163. if opts.samples_log_stdout:
  164. print(generation_info_js)
  165. if opts.do_not_show_images:
  166. processed.images = []
  167. return processed.images, generation_info_js, plaintext_to_html(processed.info), plaintext_to_html(processed.comments)