soft_inpainting.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. import numpy as np
  2. import gradio as gr
  3. import math
  4. from modules.ui_components import InputAccordion
  5. import modules.scripts as scripts
  6. from modules.torch_utils import float64
  7. class SoftInpaintingSettings:
  8. def __init__(self,
  9. mask_blend_power,
  10. mask_blend_scale,
  11. inpaint_detail_preservation,
  12. composite_mask_influence,
  13. composite_difference_threshold,
  14. composite_difference_contrast):
  15. self.mask_blend_power = mask_blend_power
  16. self.mask_blend_scale = mask_blend_scale
  17. self.inpaint_detail_preservation = inpaint_detail_preservation
  18. self.composite_mask_influence = composite_mask_influence
  19. self.composite_difference_threshold = composite_difference_threshold
  20. self.composite_difference_contrast = composite_difference_contrast
  21. def add_generation_params(self, dest):
  22. dest[enabled_gen_param_label] = True
  23. dest[gen_param_labels.mask_blend_power] = self.mask_blend_power
  24. dest[gen_param_labels.mask_blend_scale] = self.mask_blend_scale
  25. dest[gen_param_labels.inpaint_detail_preservation] = self.inpaint_detail_preservation
  26. dest[gen_param_labels.composite_mask_influence] = self.composite_mask_influence
  27. dest[gen_param_labels.composite_difference_threshold] = self.composite_difference_threshold
  28. dest[gen_param_labels.composite_difference_contrast] = self.composite_difference_contrast
  29. # ------------------- Methods -------------------
  30. def processing_uses_inpainting(p):
  31. # TODO: Figure out a better way to determine if inpainting is being used by p
  32. if getattr(p, "image_mask", None) is not None:
  33. return True
  34. if getattr(p, "mask", None) is not None:
  35. return True
  36. if getattr(p, "nmask", None) is not None:
  37. return True
  38. return False
  39. def latent_blend(settings, a, b, t):
  40. """
  41. Interpolates two latent image representations according to the parameter t,
  42. where the interpolated vectors' magnitudes are also interpolated separately.
  43. The "detail_preservation" factor biases the magnitude interpolation towards
  44. the larger of the two magnitudes.
  45. """
  46. import torch
  47. # NOTE: We use inplace operations wherever possible.
  48. if len(t.shape) == 3:
  49. # [4][w][h] to [1][4][w][h]
  50. t2 = t.unsqueeze(0)
  51. # [4][w][h] to [1][1][w][h] - the [4] seem redundant.
  52. t3 = t[0].unsqueeze(0).unsqueeze(0)
  53. else:
  54. t2 = t
  55. t3 = t[:, 0][:, None]
  56. one_minus_t2 = 1 - t2
  57. one_minus_t3 = 1 - t3
  58. # Linearly interpolate the image vectors.
  59. a_scaled = a * one_minus_t2
  60. b_scaled = b * t2
  61. image_interp = a_scaled
  62. image_interp.add_(b_scaled)
  63. result_type = image_interp.dtype
  64. del a_scaled, b_scaled, t2, one_minus_t2
  65. # Calculate the magnitude of the interpolated vectors. (We will remove this magnitude.)
  66. # 64-bit operations are used here to allow large exponents.
  67. current_magnitude = torch.norm(image_interp, p=2, dim=1, keepdim=True).to(float64(image_interp)).add_(0.00001)
  68. # Interpolate the powered magnitudes, then un-power them (bring them back to a power of 1).
  69. a_magnitude = torch.norm(a, p=2, dim=1, keepdim=True).to(float64(a)).pow_(settings.inpaint_detail_preservation) * one_minus_t3
  70. b_magnitude = torch.norm(b, p=2, dim=1, keepdim=True).to(float64(b)).pow_(settings.inpaint_detail_preservation) * t3
  71. desired_magnitude = a_magnitude
  72. desired_magnitude.add_(b_magnitude).pow_(1 / settings.inpaint_detail_preservation)
  73. del a_magnitude, b_magnitude, t3, one_minus_t3
  74. # Change the linearly interpolated image vectors' magnitudes to the value we want.
  75. # This is the last 64-bit operation.
  76. image_interp_scaling_factor = desired_magnitude
  77. image_interp_scaling_factor.div_(current_magnitude)
  78. image_interp_scaling_factor = image_interp_scaling_factor.to(result_type)
  79. image_interp_scaled = image_interp
  80. image_interp_scaled.mul_(image_interp_scaling_factor)
  81. del current_magnitude
  82. del desired_magnitude
  83. del image_interp
  84. del image_interp_scaling_factor
  85. del result_type
  86. return image_interp_scaled
  87. def get_modified_nmask(settings, nmask, sigma):
  88. """
  89. Converts a negative mask representing the transparency of the original latent vectors being overlaid
  90. to a mask that is scaled according to the denoising strength for this step.
  91. Where:
  92. 0 = fully opaque, infinite density, fully masked
  93. 1 = fully transparent, zero density, fully unmasked
  94. We bring this transparency to a power, as this allows one to simulate N number of blending operations
  95. where N can be any positive real value. Using this one can control the balance of influence between
  96. the denoiser and the original latents according to the sigma value.
  97. NOTE: "mask" is not used
  98. """
  99. import torch
  100. return torch.pow(nmask, (sigma ** settings.mask_blend_power) * settings.mask_blend_scale)
  101. def apply_adaptive_masks(
  102. settings: SoftInpaintingSettings,
  103. nmask,
  104. latent_orig,
  105. latent_processed,
  106. overlay_images,
  107. width, height,
  108. paste_to):
  109. import torch
  110. import modules.processing as proc
  111. import modules.images as images
  112. from PIL import Image, ImageOps, ImageFilter
  113. # TODO: Bias the blending according to the latent mask, add adjustable parameter for bias control.
  114. if len(nmask.shape) == 3:
  115. latent_mask = nmask[0].float()
  116. else:
  117. latent_mask = nmask[:, 0].float()
  118. # convert the original mask into a form we use to scale distances for thresholding
  119. mask_scalar = 1 - (torch.clamp(latent_mask, min=0, max=1) ** (settings.mask_blend_scale / 2))
  120. mask_scalar = (0.5 * (1 - settings.composite_mask_influence)
  121. + mask_scalar * settings.composite_mask_influence)
  122. mask_scalar = mask_scalar / (1.00001 - mask_scalar)
  123. mask_scalar = mask_scalar.cpu().numpy()
  124. latent_distance = torch.norm(latent_processed - latent_orig, p=2, dim=1)
  125. kernel, kernel_center = get_gaussian_kernel(stddev_radius=1.5, max_radius=2)
  126. masks_for_overlay = []
  127. for i, (distance_map, overlay_image) in enumerate(zip(latent_distance, overlay_images)):
  128. converted_mask = distance_map.float().cpu().numpy()
  129. converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
  130. percentile_min=0.9, percentile_max=1, min_width=1)
  131. converted_mask = weighted_histogram_filter(converted_mask, kernel, kernel_center,
  132. percentile_min=0.25, percentile_max=0.75, min_width=1)
  133. # The distance at which opacity of original decreases to 50%
  134. if len(mask_scalar.shape) == 3:
  135. if mask_scalar.shape[0] > i:
  136. half_weighted_distance = settings.composite_difference_threshold * mask_scalar[i]
  137. else:
  138. half_weighted_distance = settings.composite_difference_threshold * mask_scalar[0]
  139. else:
  140. half_weighted_distance = settings.composite_difference_threshold * mask_scalar
  141. converted_mask = converted_mask / half_weighted_distance
  142. converted_mask = 1 / (1 + converted_mask ** settings.composite_difference_contrast)
  143. converted_mask = smootherstep(converted_mask)
  144. converted_mask = 1 - converted_mask
  145. converted_mask = 255. * converted_mask
  146. converted_mask = converted_mask.astype(np.uint8)
  147. converted_mask = Image.fromarray(converted_mask)
  148. converted_mask = images.resize_image(2, converted_mask, width, height)
  149. converted_mask = proc.create_binary_mask(converted_mask, round=False)
  150. # Remove aliasing artifacts using a gaussian blur.
  151. converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
  152. # Expand the mask to fit the whole image if needed.
  153. if paste_to is not None:
  154. converted_mask = proc.uncrop(converted_mask,
  155. (overlay_image.width, overlay_image.height),
  156. paste_to)
  157. masks_for_overlay.append(converted_mask)
  158. image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
  159. image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
  160. mask=ImageOps.invert(converted_mask.convert('L')))
  161. overlay_images[i] = image_masked.convert('RGBA')
  162. return masks_for_overlay
  163. def apply_masks(
  164. settings,
  165. nmask,
  166. overlay_images,
  167. width, height,
  168. paste_to):
  169. import torch
  170. import modules.processing as proc
  171. import modules.images as images
  172. from PIL import Image, ImageOps, ImageFilter
  173. converted_mask = nmask[0].float()
  174. converted_mask = torch.clamp(converted_mask, min=0, max=1).pow_(settings.mask_blend_scale / 2)
  175. converted_mask = 255. * converted_mask
  176. converted_mask = converted_mask.cpu().numpy().astype(np.uint8)
  177. converted_mask = Image.fromarray(converted_mask)
  178. converted_mask = images.resize_image(2, converted_mask, width, height)
  179. converted_mask = proc.create_binary_mask(converted_mask, round=False)
  180. # Remove aliasing artifacts using a gaussian blur.
  181. converted_mask = converted_mask.filter(ImageFilter.GaussianBlur(radius=4))
  182. # Expand the mask to fit the whole image if needed.
  183. if paste_to is not None:
  184. converted_mask = proc.uncrop(converted_mask,
  185. (width, height),
  186. paste_to)
  187. masks_for_overlay = []
  188. for i, overlay_image in enumerate(overlay_images):
  189. masks_for_overlay[i] = converted_mask
  190. image_masked = Image.new('RGBa', (overlay_image.width, overlay_image.height))
  191. image_masked.paste(overlay_image.convert("RGBA").convert("RGBa"),
  192. mask=ImageOps.invert(converted_mask.convert('L')))
  193. overlay_images[i] = image_masked.convert('RGBA')
  194. return masks_for_overlay
  195. def weighted_histogram_filter(img, kernel, kernel_center, percentile_min=0.0, percentile_max=1.0, min_width=1.0):
  196. """
  197. Generalization convolution filter capable of applying
  198. weighted mean, median, maximum, and minimum filters
  199. parametrically using an arbitrary kernel.
  200. Args:
  201. img (nparray):
  202. The image, a 2-D array of floats, to which the filter is being applied.
  203. kernel (nparray):
  204. The kernel, a 2-D array of floats.
  205. kernel_center (nparray):
  206. The kernel center coordinate, a 1-D array with two elements.
  207. percentile_min (float):
  208. The lower bound of the histogram window used by the filter,
  209. from 0 to 1.
  210. percentile_max (float):
  211. The upper bound of the histogram window used by the filter,
  212. from 0 to 1.
  213. min_width (float):
  214. The minimum size of the histogram window bounds, in weight units.
  215. Must be greater than 0.
  216. Returns:
  217. (nparray): A filtered copy of the input image "img", a 2-D array of floats.
  218. """
  219. # Converts an index tuple into a vector.
  220. def vec(x):
  221. return np.array(x)
  222. kernel_min = -kernel_center
  223. kernel_max = vec(kernel.shape) - kernel_center
  224. def weighted_histogram_filter_single(idx):
  225. idx = vec(idx)
  226. min_index = np.maximum(0, idx + kernel_min)
  227. max_index = np.minimum(vec(img.shape), idx + kernel_max)
  228. window_shape = max_index - min_index
  229. class WeightedElement:
  230. """
  231. An element of the histogram, its weight
  232. and bounds.
  233. """
  234. def __init__(self, value, weight):
  235. self.value: float = value
  236. self.weight: float = weight
  237. self.window_min: float = 0.0
  238. self.window_max: float = 1.0
  239. # Collect the values in the image as WeightedElements,
  240. # weighted by their corresponding kernel values.
  241. values = []
  242. for window_tup in np.ndindex(tuple(window_shape)):
  243. window_index = vec(window_tup)
  244. image_index = window_index + min_index
  245. centered_kernel_index = image_index - idx
  246. kernel_index = centered_kernel_index + kernel_center
  247. element = WeightedElement(img[tuple(image_index)], kernel[tuple(kernel_index)])
  248. values.append(element)
  249. def sort_key(x: WeightedElement):
  250. return x.value
  251. values.sort(key=sort_key)
  252. # Calculate the height of the stack (sum)
  253. # and each sample's range they occupy in the stack
  254. sum = 0
  255. for i in range(len(values)):
  256. values[i].window_min = sum
  257. sum += values[i].weight
  258. values[i].window_max = sum
  259. # Calculate what range of this stack ("window")
  260. # we want to get the weighted average across.
  261. window_min = sum * percentile_min
  262. window_max = sum * percentile_max
  263. window_width = window_max - window_min
  264. # Ensure the window is within the stack and at least a certain size.
  265. if window_width < min_width:
  266. window_center = (window_min + window_max) / 2
  267. window_min = window_center - min_width / 2
  268. window_max = window_center + min_width / 2
  269. if window_max > sum:
  270. window_max = sum
  271. window_min = sum - min_width
  272. if window_min < 0:
  273. window_min = 0
  274. window_max = min_width
  275. value = 0
  276. value_weight = 0
  277. # Get the weighted average of all the samples
  278. # that overlap with the window, weighted
  279. # by the size of their overlap.
  280. for i in range(len(values)):
  281. if window_min >= values[i].window_max:
  282. continue
  283. if window_max <= values[i].window_min:
  284. break
  285. s = max(window_min, values[i].window_min)
  286. e = min(window_max, values[i].window_max)
  287. w = e - s
  288. value += values[i].value * w
  289. value_weight += w
  290. return value / value_weight if value_weight != 0 else 0
  291. img_out = img.copy()
  292. # Apply the kernel operation over each pixel.
  293. for index in np.ndindex(img.shape):
  294. img_out[index] = weighted_histogram_filter_single(index)
  295. return img_out
  296. def smoothstep(x):
  297. """
  298. The smoothstep function, input should be clamped to 0-1 range.
  299. Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
  300. """
  301. return x * x * (3 - 2 * x)
  302. def smootherstep(x):
  303. """
  304. The smootherstep function, input should be clamped to 0-1 range.
  305. Turns a diagonal line (f(x) = x) into a sigmoid-like curve.
  306. """
  307. return x * x * x * (x * (6 * x - 15) + 10)
  308. def get_gaussian_kernel(stddev_radius=1.0, max_radius=2):
  309. """
  310. Creates a Gaussian kernel with thresholded edges.
  311. Args:
  312. stddev_radius (float):
  313. Standard deviation of the gaussian kernel, in pixels.
  314. max_radius (int):
  315. The size of the filter kernel. The number of pixels is (max_radius*2+1) ** 2.
  316. The kernel is thresholded so that any values one pixel beyond this radius
  317. is weighted at 0.
  318. Returns:
  319. (nparray, nparray): A kernel array (shape: (N, N)), its center coordinate (shape: (2))
  320. """
  321. # Evaluates a 0-1 normalized gaussian function for a given square distance from the mean.
  322. def gaussian(sqr_mag):
  323. return math.exp(-sqr_mag / (stddev_radius * stddev_radius))
  324. # Helper function for converting a tuple to an array.
  325. def vec(x):
  326. return np.array(x)
  327. """
  328. Since a gaussian is unbounded, we need to limit ourselves
  329. to a finite range.
  330. We taper the ends off at the end of that range so they equal zero
  331. while preserving the maximum value of 1 at the mean.
  332. """
  333. zero_radius = max_radius + 1.0
  334. gauss_zero = gaussian(zero_radius * zero_radius)
  335. gauss_kernel_scale = 1 / (1 - gauss_zero)
  336. def gaussian_kernel_func(coordinate):
  337. x = coordinate[0] ** 2.0 + coordinate[1] ** 2.0
  338. x = gaussian(x)
  339. x -= gauss_zero
  340. x *= gauss_kernel_scale
  341. x = max(0.0, x)
  342. return x
  343. size = max_radius * 2 + 1
  344. kernel_center = max_radius
  345. kernel = np.zeros((size, size))
  346. for index in np.ndindex(kernel.shape):
  347. kernel[index] = gaussian_kernel_func(vec(index) - kernel_center)
  348. return kernel, kernel_center
  349. # ------------------- Constants -------------------
  350. default = SoftInpaintingSettings(1, 0.5, 4, 0, 0.5, 2)
  351. enabled_ui_label = "Soft inpainting"
  352. enabled_gen_param_label = "Soft inpainting enabled"
  353. enabled_el_id = "soft_inpainting_enabled"
  354. ui_labels = SoftInpaintingSettings(
  355. "Schedule bias",
  356. "Preservation strength",
  357. "Transition contrast boost",
  358. "Mask influence",
  359. "Difference threshold",
  360. "Difference contrast")
  361. ui_info = SoftInpaintingSettings(
  362. "Shifts when preservation of original content occurs during denoising.",
  363. "How strongly partially masked content should be preserved.",
  364. "Amplifies the contrast that may be lost in partially masked regions.",
  365. "How strongly the original mask should bias the difference threshold.",
  366. "How much an image region can change before the original pixels are not blended in anymore.",
  367. "How sharp the transition should be between blended and not blended.")
  368. gen_param_labels = SoftInpaintingSettings(
  369. "Soft inpainting schedule bias",
  370. "Soft inpainting preservation strength",
  371. "Soft inpainting transition contrast boost",
  372. "Soft inpainting mask influence",
  373. "Soft inpainting difference threshold",
  374. "Soft inpainting difference contrast")
  375. el_ids = SoftInpaintingSettings(
  376. "mask_blend_power",
  377. "mask_blend_scale",
  378. "inpaint_detail_preservation",
  379. "composite_mask_influence",
  380. "composite_difference_threshold",
  381. "composite_difference_contrast")
  382. # ------------------- Script -------------------
  383. class Script(scripts.Script):
  384. def __init__(self):
  385. self.section = "inpaint"
  386. self.masks_for_overlay = None
  387. self.overlay_images = None
  388. def title(self):
  389. return "Soft Inpainting"
  390. def show(self, is_img2img):
  391. return scripts.AlwaysVisible if is_img2img else False
  392. def ui(self, is_img2img):
  393. if not is_img2img:
  394. return
  395. with InputAccordion(False, label=enabled_ui_label, elem_id=enabled_el_id) as soft_inpainting_enabled:
  396. with gr.Group():
  397. gr.Markdown(
  398. """
  399. Soft inpainting allows you to **seamlessly blend original content with inpainted content** according to the mask opacity.
  400. **High _Mask blur_** values are recommended!
  401. """)
  402. power = \
  403. gr.Slider(label=ui_labels.mask_blend_power,
  404. info=ui_info.mask_blend_power,
  405. minimum=0,
  406. maximum=8,
  407. step=0.1,
  408. value=default.mask_blend_power,
  409. elem_id=el_ids.mask_blend_power)
  410. scale = \
  411. gr.Slider(label=ui_labels.mask_blend_scale,
  412. info=ui_info.mask_blend_scale,
  413. minimum=0,
  414. maximum=8,
  415. step=0.05,
  416. value=default.mask_blend_scale,
  417. elem_id=el_ids.mask_blend_scale)
  418. detail = \
  419. gr.Slider(label=ui_labels.inpaint_detail_preservation,
  420. info=ui_info.inpaint_detail_preservation,
  421. minimum=1,
  422. maximum=32,
  423. step=0.5,
  424. value=default.inpaint_detail_preservation,
  425. elem_id=el_ids.inpaint_detail_preservation)
  426. gr.Markdown(
  427. """
  428. ### Pixel Composite Settings
  429. """)
  430. mask_inf = \
  431. gr.Slider(label=ui_labels.composite_mask_influence,
  432. info=ui_info.composite_mask_influence,
  433. minimum=0,
  434. maximum=1,
  435. step=0.05,
  436. value=default.composite_mask_influence,
  437. elem_id=el_ids.composite_mask_influence)
  438. dif_thresh = \
  439. gr.Slider(label=ui_labels.composite_difference_threshold,
  440. info=ui_info.composite_difference_threshold,
  441. minimum=0,
  442. maximum=8,
  443. step=0.25,
  444. value=default.composite_difference_threshold,
  445. elem_id=el_ids.composite_difference_threshold)
  446. dif_contr = \
  447. gr.Slider(label=ui_labels.composite_difference_contrast,
  448. info=ui_info.composite_difference_contrast,
  449. minimum=0,
  450. maximum=8,
  451. step=0.25,
  452. value=default.composite_difference_contrast,
  453. elem_id=el_ids.composite_difference_contrast)
  454. with gr.Accordion("Help", open=False):
  455. gr.Markdown(
  456. f"""
  457. ### {ui_labels.mask_blend_power}
  458. The blending strength of original content is scaled proportionally with the decreasing noise level values at each step (sigmas).
  459. This ensures that the influence of the denoiser and original content preservation is roughly balanced at each step.
  460. This balance can be shifted using this parameter, controlling whether earlier or later steps have stronger preservation.
  461. - **Below 1**: Stronger preservation near the end (with low sigma)
  462. - **1**: Balanced (proportional to sigma)
  463. - **Above 1**: Stronger preservation in the beginning (with high sigma)
  464. """)
  465. gr.Markdown(
  466. f"""
  467. ### {ui_labels.mask_blend_scale}
  468. Skews whether partially masked image regions should be more likely to preserve the original content or favor inpainted content.
  469. This may need to be adjusted depending on the {ui_labels.mask_blend_power}, CFG Scale, prompt and Denoising strength.
  470. - **Low values**: Favors generated content.
  471. - **High values**: Favors original content.
  472. """)
  473. gr.Markdown(
  474. f"""
  475. ### {ui_labels.inpaint_detail_preservation}
  476. This parameter controls how the original latent vectors and denoised latent vectors are interpolated.
  477. With higher values, the magnitude of the resulting blended vector will be closer to the maximum of the two interpolated vectors.
  478. This can prevent the loss of contrast that occurs with linear interpolation.
  479. - **Low values**: Softer blending, details may fade.
  480. - **High values**: Stronger contrast, may over-saturate colors.
  481. """)
  482. gr.Markdown(
  483. """
  484. ## Pixel Composite Settings
  485. Masks are generated based on how much a part of the image changed after denoising.
  486. These masks are used to blend the original and final images together.
  487. If the difference is low, the original pixels are used instead of the pixels returned by the inpainting process.
  488. """)
  489. gr.Markdown(
  490. f"""
  491. ### {ui_labels.composite_mask_influence}
  492. This parameter controls how much the mask should bias this sensitivity to difference.
  493. - **0**: Ignore the mask, only consider differences in image content.
  494. - **1**: Follow the mask closely despite image content changes.
  495. """)
  496. gr.Markdown(
  497. f"""
  498. ### {ui_labels.composite_difference_threshold}
  499. This value represents the difference at which the original pixels will have less than 50% opacity.
  500. - **Low values**: Two images patches must be almost the same in order to retain original pixels.
  501. - **High values**: Two images patches can be very different and still retain original pixels.
  502. """)
  503. gr.Markdown(
  504. f"""
  505. ### {ui_labels.composite_difference_contrast}
  506. This value represents the contrast between the opacity of the original and inpainted content.
  507. - **Low values**: The blend will be more gradual and have longer transitions, but may cause ghosting.
  508. - **High values**: Ghosting will be less common, but transitions may be very sudden.
  509. """)
  510. self.infotext_fields = [(soft_inpainting_enabled, enabled_gen_param_label),
  511. (power, gen_param_labels.mask_blend_power),
  512. (scale, gen_param_labels.mask_blend_scale),
  513. (detail, gen_param_labels.inpaint_detail_preservation),
  514. (mask_inf, gen_param_labels.composite_mask_influence),
  515. (dif_thresh, gen_param_labels.composite_difference_threshold),
  516. (dif_contr, gen_param_labels.composite_difference_contrast)]
  517. self.paste_field_names = []
  518. for _, field_name in self.infotext_fields:
  519. self.paste_field_names.append(field_name)
  520. return [soft_inpainting_enabled,
  521. power,
  522. scale,
  523. detail,
  524. mask_inf,
  525. dif_thresh,
  526. dif_contr]
  527. def process(self, p, enabled, power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr):
  528. if not enabled:
  529. return
  530. if not processing_uses_inpainting(p):
  531. return
  532. # Shut off the rounding it normally does.
  533. p.mask_round = False
  534. settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
  535. # p.extra_generation_params["Mask rounding"] = False
  536. settings.add_generation_params(p.extra_generation_params)
  537. def on_mask_blend(self, p, mba: scripts.MaskBlendArgs, enabled, power, scale, detail_preservation, mask_inf,
  538. dif_thresh, dif_contr):
  539. if not enabled:
  540. return
  541. if not processing_uses_inpainting(p):
  542. return
  543. if mba.is_final_blend:
  544. mba.blended_latent = mba.current_latent
  545. return
  546. settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
  547. # todo: Why is sigma 2D? Both values are the same.
  548. mba.blended_latent = latent_blend(settings,
  549. mba.init_latent,
  550. mba.current_latent,
  551. get_modified_nmask(settings, mba.nmask, mba.sigma[0]))
  552. def post_sample(self, p, ps: scripts.PostSampleArgs, enabled, power, scale, detail_preservation, mask_inf,
  553. dif_thresh, dif_contr):
  554. if not enabled:
  555. return
  556. if not processing_uses_inpainting(p):
  557. return
  558. nmask = getattr(p, "nmask", None)
  559. if nmask is None:
  560. return
  561. from modules import images
  562. from modules.shared import opts
  563. settings = SoftInpaintingSettings(power, scale, detail_preservation, mask_inf, dif_thresh, dif_contr)
  564. # since the original code puts holes in the existing overlay images,
  565. # we have to rebuild them.
  566. self.overlay_images = []
  567. for img in p.init_images:
  568. image = images.flatten(img, opts.img2img_background_color)
  569. if p.paste_to is None and p.resize_mode != 3:
  570. image = images.resize_image(p.resize_mode, image, p.width, p.height)
  571. self.overlay_images.append(image.convert('RGBA'))
  572. if len(p.init_images) == 1:
  573. self.overlay_images = self.overlay_images * p.batch_size
  574. if getattr(ps.samples, 'already_decoded', False):
  575. self.masks_for_overlay = apply_masks(settings=settings,
  576. nmask=nmask,
  577. overlay_images=self.overlay_images,
  578. width=p.width,
  579. height=p.height,
  580. paste_to=p.paste_to)
  581. else:
  582. self.masks_for_overlay = apply_adaptive_masks(settings=settings,
  583. nmask=nmask,
  584. latent_orig=p.init_latent,
  585. latent_processed=ps.samples,
  586. overlay_images=self.overlay_images,
  587. width=p.width,
  588. height=p.height,
  589. paste_to=p.paste_to)
  590. def postprocess_maskoverlay(self, p, ppmo: scripts.PostProcessMaskOverlayArgs, enabled, power, scale,
  591. detail_preservation, mask_inf, dif_thresh, dif_contr):
  592. if not enabled:
  593. return
  594. if not processing_uses_inpainting(p):
  595. return
  596. if self.masks_for_overlay is None:
  597. return
  598. if self.overlay_images is None:
  599. return
  600. ppmo.mask_for_overlay = self.masks_for_overlay[ppmo.index]
  601. ppmo.overlay_image = self.overlay_images[ppmo.index]