File size: 3,317 Bytes
75805ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a49d82c
75805ca
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# from https://github.com/lllyasviel/ControlNet/blob/main/gradio_canny2image.py

import einops
import numpy as np
import torch
from PIL import Image
import sys
import os

sys.path.append('../../../ControlNet')

from share import *
from pytorch_lightning import seed_everything
from cldm.model import create_model, load_state_dict
from cldm.ddim_hacked import DDIMSampler
from diffusers.utils import load_image

test_prompt = "best quality, extremely detailed"
test_negative_prompt = "lowres, bad anatomy, worst quality, low quality"

@torch.no_grad()
def generate(prompt, n_prompt, seed, control, ddim_steps=20, eta=0.0, scale=9.0, H=512, W=512, strength = 1.0, guess_mode=False):
    seed_everything(seed)

    cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt] * num_samples)]}
    un_cond = {"c_concat": None if guess_mode else [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]}
    shape = (4, H // 8, W // 8)
    
    model.control_scales = [strength * (0.825 ** float(12 - i)) for i in range(13)] if guess_mode else ([strength] * 13)  # Magic number. IDK why. Perhaps because 0.825**12<0.01 but 0.826**12>0.01
    latent = torch.randn((1,) + shape, device="cpu", generator=torch.Generator(device="cpu").manual_seed(seed)).cuda()
    samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples,
                                                    shape, cond, x_T=latent,
                                                    verbose=False, eta=eta,
                                                    unconditional_guidance_scale=scale,
                                                    unconditional_conditioning=un_cond)
    x_samples = model.decode_first_stage(samples)
    x_samples = (einops.rearrange(x_samples, 'b c h w -> b h w c') * 127.5 + 127.5).cpu().numpy().clip(0, 255).astype(np.uint8)
 
    return Image.fromarray(x_samples[0])

if __name__ == '__main__':
    model_name = sys.argv[1]

    control_image_folder = '../gen_compare/control_images/converted/'
    output_image_folder = 'output_images/ref/'
    os.makedirs(output_image_folder, exist_ok=True)

    num_samples = 1
    model = create_model('../../../ControlNet/models/cldm_v15.yaml').cpu()
    model.load_state_dict(load_state_dict(f'../../ControlNet/models/control_sd15_{model_name}.pth', location='cpu'))
    model = model.cuda()
    ddim_sampler = DDIMSampler(model)

    image_types = {'bird', 'human', 'room', 'vermeer'}

    for image_type in image_types:
        control_image = Image.open(f'{control_image_folder}control_{image_type}_{model_name}.png')
        control = np.array(control_image)[:,:,::-1].copy()
        control = torch.from_numpy(control).float().cuda() / 255.0
        control = torch.stack([control for _ in range(num_samples)], dim=0)
        control = einops.rearrange(control, 'b h w c -> b c h w').clone()

        for seed in range(4):
            image = generate(test_prompt, test_negative_prompt, seed=seed, control=control)
            image.save(f'{output_image_folder}output_{image_type}_{model_name}_{seed}.png')
            image = generate("", "", seed=seed, control=control, guess_mode=True, scale=4.0, ddim_steps=50)
            image.save(f'{output_image_folder}output_{image_type}_{model_name}_{seed}_gm.png')