【AutoencoderKL】基于stable-diffusion-v1.4的vae对图像重构

模型地址:https://huggingface.co/CompVis/stable-diffusion-v1-4/tree/main/vae

主要参考:Using-Stable-Diffusion-VAE-to-encode-satellite-images

sd1.4 vae

下载到本地

python 复制代码
from diffusers import AutoencoderKL
from PIL import Image
import  torch
import torchvision.transforms as T

#  ./huggingface/stable-diffusion-v1-4/vae 切换为任意本地路径
vae = AutoencoderKL.from_pretrained("./huggingface/stable-diffusion-v1-4/vae",variant='fp16')
# c:\Users\zeng\Downloads\vae_config.json

def encode_img(input_img):
    # Single image -> single latent in a batch (so size 1, 4, 64, 64)
        # Transform the image to a tensor and normalize it
    transform = T.Compose([
        # T.Resize((256, 256)),
        T.ToTensor()
    ])
    input_img = transform(input_img)
    if len(input_img.shape)<4:
        input_img = input_img.unsqueeze(0)
    with torch.no_grad():
        latent = vae.encode(input_img*2 - 1) # Note scaling
    return 0.18215 * latent.latent_dist.sample()



def decode_img(latents):
    # bath of latents -> list of images
    latents = (1 / 0.18215) * latents
    with torch.no_grad():
        image = vae.decode(latents).sample
    image = (image / 2 + 0.5).clamp(0, 1)
    image = image.detach().cpu()
    # image = T.Resize(original_size)(image.squeeze())
    return T.ToPILImage()(image.squeeze())

if __name__ == '__main__':
    # Load an example image
    input_img = Image.open("huge.jpg")
    original_size = input_img.size
    print('original_size',original_size)

    # Encode and decode the image
    latents = encode_img(input_img)
    reconstructed_img = decode_img(latents)

    # Save the reconstructed image
    reconstructed_img.save("reconstructed_example2.jpg")
    # Concatenate the original and reconstructed images
    concatenated_img = Image.new('RGB', (original_size[0] * 2, original_size[1]))
    concatenated_img.paste(input_img, (0, 0))
    concatenated_img.paste(reconstructed_img, (original_size[0], 0))
    # Save the concatenated image
    concatenated_img.save("concatenated_example2.jpg")
相关推荐
吐个泡泡v4 天前
深度学习中的“压缩与解压“艺术:自编码器与VAE详解
深度学习·vae·生成模型·自编码器
九河_7 天前
关于DiT模型的一些思考
transformer·vae·diffusion·dit
天下弈星~4 个月前
变分自编码器VAE的Pytorch实现
图像处理·pytorch·python·深度学习·vae·图像生成·变分自编码器
AI生成未来4 个月前
ICCV 2025|单视频生成动态4D场景!中科大&微软突破4D生成瓶颈,动画效果炸裂来袭!
vae·3d场景·4d场景
墨绿色的摆渡人5 个月前
具身智能零碎知识点(五):VAE中对使用KL散度的理解
人工智能·vae·具身智能
阿维的博客日记7 个月前
VAE和Stable Diffusion的关系
stable diffusion·vae
阿正的梦工坊9 个月前
变分自编码器(Variational Autoencoder, VAE)中的解码器(Decoder)详解
人工智能·深度学习·算法·机器学习·vae
聚梦小课堂1 年前
简单聊聊AI绘画中的SD(Stable Diffusion)是什么
ai作画·stable diffusion·sd·vae·技术原理·ai绘画原理·免费技术分享
肥猪猪爸1 年前
VAE的原理及MNIST数据生成
人工智能·pytorch·深度学习·机器学习·计算机视觉·ai作画·vae
许野平1 年前
SD(Stable Diffusion)模型的基本工作数据流
stable diffusion·transformer·sd·vae·diffusion