创建Stable Diffusion Outpainting API遇报错,求解决方案
解决Stable Diffusion XL Outpainting功能实现的AttributeError问题
错误原因
你代码里调用的sample_posterior并不是StableDiffusionXLPipeline的内置方法,这个方法不存在,直接调用就会触发AttributeError。要实现类似Automatic1111的Outpainting(扩图加背景),需要先扩展图像画布,再用SDXL的Inpaint管道填充扩展区域。
解决方案
以下是修正后的完整代码,包含画布扩展、Inpaint模型加载和Outpainting执行的完整流程:
from PIL import Image import numpy as np from diffusers import StableDiffusionXLInpaintPipeline from diffusers.utils import load_image import torch def expand_canvas(image, expand_size=256): """扩展图像画布,在四周添加空白区域,用于Outpainting""" width, height = image.size new_width = width + 2 * expand_size new_height = height + 2 * expand_size # 创建新画布,背景用白色(也可以用透明或其他颜色) new_image = Image.new("RGB", (new_width, new_height), (255, 255, 255)) # 将原始图像粘贴到画布中心 new_image.paste(image, (expand_size, expand_size)) # 生成mask:空白区域为白色(需要填充的部分),原始图像区域为黑色 mask = Image.new("L", (new_width, new_height), 255) mask.paste(0, (expand_size, expand_size, expand_size + width, expand_size + height)) return new_image, mask def outpaint_with_model(image_path, model, prompt, negative_prompt): input_image = load_image(image_path) # 扩展画布,获取扩展后的图像和mask expanded_image, mask_image = expand_canvas(input_image) # 执行Inpaint(即Outpainting) outpainted_image = model( prompt=prompt, negative_prompt=negative_prompt, image=expanded_image, mask_image=mask_image, num_inference_steps=30, strength=0.9, guidance_scale=7.5 ).images[0] return outpainted_image def start(): model_path = "./model/realistic-model.safetensors" input_image_path = "./generated_images/generated_image_20240517_123639.png" # 加载SDXL Inpaint管道 model = StableDiffusionXLInpaintPipeline.from_single_file( model_path, torch_dtype=torch.float16 # 如果有GPU,用float16加速;没有则改成torch.float32 ) # 启用GPU加速(如果可用) model = model.to("cuda" if torch.cuda.is_available() else "cpu") # 定义Outpainting的提示词和反向提示词 prompt = "photorealistic outdoor background, sunny day, natural scenery" negative_prompt = "blurry, low quality, distorted, text" outpainted_image = outpaint_with_model(input_image_path, model, prompt, negative_prompt) outpainted_image.show() # 保存结果 outpainted_image.save("./outpainted_result.png") if __name__ == "__main__": start()
关键说明
- 画布扩展:
expand_canvas函数负责在原始图像四周添加空白区域,同时生成对应的mask(标记需要填充的区域) - 模型选择:必须使用
StableDiffusionXLInpaintPipeline,而不是普通的StableDiffusionXLPipeline,因为只有Inpaint管道支持基于mask的图像补全/扩图 - 参数调整:可以修改
expand_size调整扩图的范围,修改num_inference_steps(推理步数)、guidance_scale(引导系数)等参数优化生成效果 - GPU加速:如果有NVIDIA GPU,确保安装了CUDA和对应的PyTorch版本,启用
torch.float16和to("cuda")可以大幅提升速度
内容的提问来源于stack exchange,提问作者Maciek
相关产品推荐
相关产品推荐

