Path: blob/master/scripts/outpainting_mk_2.py
3055 views
import math12import numpy as np3import skimage45import modules.scripts as scripts6import gradio as gr7from PIL import Image, ImageDraw89from modules import images10from modules.processing import Processed, process_images11from modules.shared import opts, state121314# this function is taken from https://github.com/parlance-zz/g-diffuser-bot15def get_matched_noise(_np_src_image, np_mask_rgb, noise_q=1, color_variation=0.05):16# helper fft routines that keep ortho normalization and auto-shift before and after fft17def _fft2(data):18if data.ndim > 2: # has channels19out_fft = np.zeros((data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128)20for c in range(data.shape[2]):21c_data = data[:, :, c]22out_fft[:, :, c] = np.fft.fft2(np.fft.fftshift(c_data), norm="ortho")23out_fft[:, :, c] = np.fft.ifftshift(out_fft[:, :, c])24else: # one channel25out_fft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128)26out_fft[:, :] = np.fft.fft2(np.fft.fftshift(data), norm="ortho")27out_fft[:, :] = np.fft.ifftshift(out_fft[:, :])2829return out_fft3031def _ifft2(data):32if data.ndim > 2: # has channels33out_ifft = np.zeros((data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128)34for c in range(data.shape[2]):35c_data = data[:, :, c]36out_ifft[:, :, c] = np.fft.ifft2(np.fft.fftshift(c_data), norm="ortho")37out_ifft[:, :, c] = np.fft.ifftshift(out_ifft[:, :, c])38else: # one channel39out_ifft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128)40out_ifft[:, :] = np.fft.ifft2(np.fft.fftshift(data), norm="ortho")41out_ifft[:, :] = np.fft.ifftshift(out_ifft[:, :])4243return out_ifft4445def _get_gaussian_window(width, height, std=3.14, mode=0):46window_scale_x = float(width / min(width, height))47window_scale_y = float(height / min(width, height))4849window = np.zeros((width, height))50x = (np.arange(width) / width * 2. - 1.) * window_scale_x51for y in range(height):52fy = (y / height * 2. - 1.) * window_scale_y53if mode == 0:54window[:, y] = np.exp(-(x ** 2 + fy ** 2) * std)55else:56window[:, y] = (1 / ((x ** 2 + 1.) * (fy ** 2 + 1.))) ** (std / 3.14) # hey wait a minute that's not gaussian5758return window5960def _get_masked_window_rgb(np_mask_grey, hardness=1.):61np_mask_rgb = np.zeros((np_mask_grey.shape[0], np_mask_grey.shape[1], 3))62if hardness != 1.:63hardened = np_mask_grey[:] ** hardness64else:65hardened = np_mask_grey[:]66for c in range(3):67np_mask_rgb[:, :, c] = hardened[:]68return np_mask_rgb6970width = _np_src_image.shape[0]71height = _np_src_image.shape[1]72num_channels = _np_src_image.shape[2]7374_np_src_image[:] * (1. - np_mask_rgb)75np_mask_grey = (np.sum(np_mask_rgb, axis=2) / 3.)76img_mask = np_mask_grey > 1e-677ref_mask = np_mask_grey < 1e-37879windowed_image = _np_src_image * (1. - _get_masked_window_rgb(np_mask_grey))80windowed_image /= np.max(windowed_image)81windowed_image += np.average(_np_src_image) * np_mask_rgb # / (1.-np.average(np_mask_rgb)) # rather than leave the masked area black, we get better results from fft by filling the average unmasked color8283src_fft = _fft2(windowed_image) # get feature statistics from masked src img84src_dist = np.absolute(src_fft)85src_phase = src_fft / src_dist8687# create a generator with a static seed to make outpainting deterministic / only follow global seed88rng = np.random.default_rng(0)8990noise_window = _get_gaussian_window(width, height, mode=1) # start with simple gaussian noise91noise_rgb = rng.random((width, height, num_channels))92noise_grey = (np.sum(noise_rgb, axis=2) / 3.)93noise_rgb *= color_variation # the colorfulness of the starting noise is blended to greyscale with a parameter94for c in range(num_channels):95noise_rgb[:, :, c] += (1. - color_variation) * noise_grey9697noise_fft = _fft2(noise_rgb)98for c in range(num_channels):99noise_fft[:, :, c] *= noise_window100noise_rgb = np.real(_ifft2(noise_fft))101shaped_noise_fft = _fft2(noise_rgb)102shaped_noise_fft[:, :, :] = np.absolute(shaped_noise_fft[:, :, :]) ** 2 * (src_dist ** noise_q) * src_phase # perform the actual shaping103104brightness_variation = 0. # color_variation # todo: temporarily tying brightness variation to color variation for now105contrast_adjusted_np_src = _np_src_image[:] * (brightness_variation + 1.) - brightness_variation * 2.106107# scikit-image is used for histogram matching, very convenient!108shaped_noise = np.real(_ifft2(shaped_noise_fft))109shaped_noise -= np.min(shaped_noise)110shaped_noise /= np.max(shaped_noise)111shaped_noise[img_mask, :] = skimage.exposure.match_histograms(shaped_noise[img_mask, :] ** 1., contrast_adjusted_np_src[ref_mask, :], channel_axis=1)112shaped_noise = _np_src_image[:] * (1. - np_mask_rgb) + shaped_noise * np_mask_rgb113114matched_noise = shaped_noise[:]115116return np.clip(matched_noise, 0., 1.)117118119120class Script(scripts.Script):121def title(self):122return "Outpainting mk2"123124def show(self, is_img2img):125return is_img2img126127def ui(self, is_img2img):128if not is_img2img:129return None130131info = gr.HTML("<p style=\"margin-bottom:0.75em\">Recommended settings: Sampling Steps: 80-100, Sampler: Euler a, Denoising strength: 0.8</p>")132133pixels = gr.Slider(label="Pixels to expand", minimum=8, maximum=256, step=8, value=128, elem_id=self.elem_id("pixels"))134mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=8, elem_id=self.elem_id("mask_blur"))135direction = gr.CheckboxGroup(label="Outpainting direction", choices=['left', 'right', 'up', 'down'], value=['left', 'right', 'up', 'down'], elem_id=self.elem_id("direction"))136noise_q = gr.Slider(label="Fall-off exponent (lower=higher detail)", minimum=0.0, maximum=4.0, step=0.01, value=1.0, elem_id=self.elem_id("noise_q"))137color_variation = gr.Slider(label="Color variation", minimum=0.0, maximum=1.0, step=0.01, value=0.05, elem_id=self.elem_id("color_variation"))138139return [info, pixels, mask_blur, direction, noise_q, color_variation]140141def run(self, p, _, pixels, mask_blur, direction, noise_q, color_variation):142initial_seed_and_info = [None, None]143144process_width = p.width145process_height = p.height146147p.inpaint_full_res = False148p.inpainting_fill = 1149p.do_not_save_samples = True150p.do_not_save_grid = True151152left = pixels if "left" in direction else 0153right = pixels if "right" in direction else 0154up = pixels if "up" in direction else 0155down = pixels if "down" in direction else 0156157if left > 0 or right > 0:158mask_blur_x = mask_blur159else:160mask_blur_x = 0161162if up > 0 or down > 0:163mask_blur_y = mask_blur164else:165mask_blur_y = 0166167p.mask_blur_x = mask_blur_x*4168p.mask_blur_y = mask_blur_y*4169170init_img = p.init_images[0]171target_w = math.ceil((init_img.width + left + right) / 64) * 64172target_h = math.ceil((init_img.height + up + down) / 64) * 64173174if left > 0:175left = left * (target_w - init_img.width) // (left + right)176177if right > 0:178right = target_w - init_img.width - left179180if up > 0:181up = up * (target_h - init_img.height) // (up + down)182183if down > 0:184down = target_h - init_img.height - up185186def expand(init, count, expand_pixels, is_left=False, is_right=False, is_top=False, is_bottom=False):187is_horiz = is_left or is_right188is_vert = is_top or is_bottom189pixels_horiz = expand_pixels if is_horiz else 0190pixels_vert = expand_pixels if is_vert else 0191192images_to_process = []193output_images = []194for n in range(count):195res_w = init[n].width + pixels_horiz196res_h = init[n].height + pixels_vert197process_res_w = math.ceil(res_w / 64) * 64198process_res_h = math.ceil(res_h / 64) * 64199200img = Image.new("RGB", (process_res_w, process_res_h))201img.paste(init[n], (pixels_horiz if is_left else 0, pixels_vert if is_top else 0))202mask = Image.new("RGB", (process_res_w, process_res_h), "white")203draw = ImageDraw.Draw(mask)204draw.rectangle((205expand_pixels + mask_blur_x if is_left else 0,206expand_pixels + mask_blur_y if is_top else 0,207mask.width - expand_pixels - mask_blur_x if is_right else res_w,208mask.height - expand_pixels - mask_blur_y if is_bottom else res_h,209), fill="black")210211np_image = (np.asarray(img) / 255.0).astype(np.float64)212np_mask = (np.asarray(mask) / 255.0).astype(np.float64)213noised = get_matched_noise(np_image, np_mask, noise_q, color_variation)214output_images.append(Image.fromarray(np.clip(noised * 255., 0., 255.).astype(np.uint8), mode="RGB"))215216target_width = min(process_width, init[n].width + pixels_horiz) if is_horiz else img.width217target_height = min(process_height, init[n].height + pixels_vert) if is_vert else img.height218p.width = target_width if is_horiz else img.width219p.height = target_height if is_vert else img.height220221crop_region = (2220 if is_left else output_images[n].width - target_width,2230 if is_top else output_images[n].height - target_height,224target_width if is_left else output_images[n].width,225target_height if is_top else output_images[n].height,226)227mask = mask.crop(crop_region)228p.image_mask = mask229230image_to_process = output_images[n].crop(crop_region)231images_to_process.append(image_to_process)232233p.init_images = images_to_process234235latent_mask = Image.new("RGB", (p.width, p.height), "white")236draw = ImageDraw.Draw(latent_mask)237draw.rectangle((238expand_pixels + mask_blur_x * 2 if is_left else 0,239expand_pixels + mask_blur_y * 2 if is_top else 0,240mask.width - expand_pixels - mask_blur_x * 2 if is_right else res_w,241mask.height - expand_pixels - mask_blur_y * 2 if is_bottom else res_h,242), fill="black")243p.latent_mask = latent_mask244245proc = process_images(p)246247if initial_seed_and_info[0] is None:248initial_seed_and_info[0] = proc.seed249initial_seed_and_info[1] = proc.info250251for n in range(count):252output_images[n].paste(proc.images[n], (0 if is_left else output_images[n].width - proc.images[n].width, 0 if is_top else output_images[n].height - proc.images[n].height))253output_images[n] = output_images[n].crop((0, 0, res_w, res_h))254255return output_images256257batch_count = p.n_iter258batch_size = p.batch_size259p.n_iter = 1260state.job_count = batch_count * ((1 if left > 0 else 0) + (1 if right > 0 else 0) + (1 if up > 0 else 0) + (1 if down > 0 else 0))261all_processed_images = []262263for i in range(batch_count):264imgs = [init_img] * batch_size265state.job = f"Batch {i + 1} out of {batch_count}"266267if left > 0:268imgs = expand(imgs, batch_size, left, is_left=True)269if right > 0:270imgs = expand(imgs, batch_size, right, is_right=True)271if up > 0:272imgs = expand(imgs, batch_size, up, is_top=True)273if down > 0:274imgs = expand(imgs, batch_size, down, is_bottom=True)275276all_processed_images += imgs277278all_images = all_processed_images279280combined_grid_image = images.image_grid(all_processed_images)281unwanted_grid_because_of_img_count = len(all_processed_images) < 2 and opts.grid_only_if_multiple282if opts.return_grid and not unwanted_grid_because_of_img_count:283all_images = [combined_grid_image] + all_processed_images284285res = Processed(p, all_images, initial_seed_and_info[0], initial_seed_and_info[1])286287if opts.samples_save:288for img in all_processed_images:289images.save_image(img, p.outpath_samples, "", res.seed, p.prompt, opts.samples_format, info=res.info, p=p)290291if opts.grid_save and not unwanted_grid_because_of_img_count:292images.save_image(combined_grid_image, p.outpath_grids, "grid", res.seed, p.prompt, opts.grid_format, info=res.info, short_filename=not opts.grid_extended_filename, grid=True, p=p)293294return res295296297