patrickvonplaten's picture
up
04c5ec4
#!/usr/bin/env python3
#!/usr/bin/env python3
from diffusers import StableDiffusionPipeline, DDIMScheduler
from time import time
from PIL import Image
from einops import rearrange
import numpy as np
import torch
from torch import autocast
from torchvision.utils import make_grid
torch.manual_seed(42)
prompts = ["a photograph of an astronaut riding a horse"]
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-3", revision="fp16", torch_dtype=torch.float16, use_auth_token=True) # make sure you're logged in with `huggingface-cli login`
#scheduler = DDIMScheduler(beta_start=0.00085, beta_end=0.012, beta_schedule="scaled_linear", clip_sample=False, set_alpha_to_one=False)
#pipe.scheduler = scheduler
pipe.to("cuda")
all_images = []
num_rows = 1
num_columns = 4
for prompt in prompts:
with autocast("cuda"):
images = pipe(num_columns * [prompt], guidance_scale=7.5, output_type="np")["sample"] # image here is in [PIL format](https://pillow.readthedocs.io/en/stable/)
all_images.append(torch.from_numpy(images))
# additionally, save as grid
grid = torch.stack(all_images, 0)
grid = rearrange(grid, 'n b h w c -> (n b) h w c')
grid = rearrange(grid, 'n h w c -> n c h w')
grid = make_grid(grid, nrow=num_rows)
# to image
grid = 255. * rearrange(grid, 'c h w -> h w c').cpu().numpy()
image = Image.fromarray(grid.astype(np.uint8))
image.save(f"../images/diffusers/batch_{round(time())}.png")