KerasCV Stable Diffusion图像修复噪点边缘问题求助
KerasCV Stable Diffusion图像修复边缘噪点问题解决
问题描述
多次使用KerasCV Stable Diffusion API执行图像修复时,生成图像的顶部与左侧边缘始终存在噪点,仅使用默认参数调用API,相关代码、种子图像及输出图像如下:
运行代码
import keras_cv import numpy as np import tensorflow as tf from PIL import Image, ImageDraw import numpy as np from tensorflow import keras import matplotlib.pyplot as plt stable_diffusion = keras_cv.models.StableDiffusion() def plot_(images): plt.figure(figsize=(10, 10)) for i in range(len(images)): ax = plt.subplot(1, len(images), i + 1) plt.imshow(images[i]) plt.axis("off") def create_mask(img): w, h = img.shape[0], img.shape[1] x = np.roll(np.roll(np.array(img), h // 2, 0), w // 2, 1) mask = Image.fromarray(np.zeros_like(x)[:, :, 0]) draw = ImageDraw.Draw(mask) coords = [(w / 2, 0), (w, h / 2), (w / 2, h), (0, h / 2)] draw.polygon(coords, fill=255) return mask ### Seed Image: im size = (512, 512) im = im.resize(size) im = np.array(im) mask = create_mask(im) mask = np.where(np.array(mask)==0, 1, 0) mask = np.expand_dims(mask, axis=0) im = np.expand_dims(im, axis=0) generated = stable_diffusion.inpaint( f" pig on cart", image=im, mask=mask, ) plot_(generated)
种子图像

输出图像

解决方法
1. 修正掩码逻辑错误(核心问题)
KerasCV StableDiffusion的inpaint方法要求掩码中1表示需要修复的区域,0表示保留区域。你当前的代码把需要修复的255区域设为0,保留区域设为1,导致模型错误地在非修复区域生成内容,引发边缘噪点。
修改掩码处理代码:
# 原错误代码 # mask = np.where(np.array(mask)==0, 1, 0) # 修正为 mask = np.where(np.array(mask) == 255, 1, 0)
2. 柔化掩码边缘
硬边缘掩码容易导致修复区域和原始图像边界产生突兀过渡,进而出现噪点。给掩码添加高斯模糊,让边缘过渡更自然:
from PIL import ImageFilter def create_mask(img): w, h = img.shape[0], img.shape[1] mask = Image.fromarray(np.zeros((w, h), dtype=np.uint8)) draw = ImageDraw.Draw(mask) coords = [(w / 2, 0), (w, h / 2), (w / 2, h), (0, h / 2)] draw.polygon(coords, fill=255) # 添加高斯模糊柔化边缘,半径可根据需求调整 mask = mask.filter(ImageFilter.GaussianBlur(radius=2)) return mask
3. 添加图像边界Padding
Stable Diffusion模型对图像边缘的处理容易出现异常,先给原始图像和掩码添加padding,修复完成后再裁剪回原尺寸:
# 设置padding大小,可根据情况调整 pad_size = 10 # 对图像和掩码添加padding,图像用反射填充避免边缘失真 im_padded = np.pad(im, ((0,0), (pad_size, pad_size), (pad_size, pad_size), (0,0)), mode='reflect') # 掩码用0填充,确保padding区域不被修复 mask_padded = np.pad(mask, ((0,0), (pad_size, pad_size), (pad_size, pad_size)), mode='constant', constant_values=0) # 执行修复 generated_padded = stable_diffusion.inpaint( "pig on cart", image=im_padded, mask=mask_padded, ) # 裁剪回原尺寸 generated = generated_padded[:, pad_size:-pad_size, pad_size:-pad_size, :]
4. 调整推理参数
默认的推理步数和引导系数可能不足以生成高质量的修复结果,尝试增加步数并调整引导值:
generated = stable_diffusion.inpaint( "pig on cart", image=im, mask=mask, num_inference_steps=50, # 默认25,增加步数提升生成质量 guidance_scale=8.0 # 默认7.5,可在7-10之间调整,平衡文本相关性和图像质量 )
内容的提问来源于stack exchange,提问作者Artico
相关产品推荐
相关产品推荐

