Created
February 17, 2023 17:26
-
-
Save takuma104/6cdb6d9aa27f67462f11554cccdf4b34 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# from https://github.com/lllyasviel/ControlNet/blob/main/gradio_canny2image.py | |
from share import * | |
import config | |
import cv2 | |
import einops | |
import gradio as gr | |
import numpy as np | |
import torch | |
from PIL import Image | |
from pytorch_lightning import seed_everything | |
from annotator.util import resize_image, HWC3 | |
from annotator.canny import apply_canny | |
from cldm.model import create_model, load_state_dict | |
from ldm.models.diffusion.ddim import DDIMSampler | |
from diffusers.utils import load_image | |
test_prompt = "best quality, extremely detailed, illustration, looking at viewer" | |
test_negative_prompt = ( | |
"longbody, lowres, bad anatomy, bad hands, missing fingers, " | |
+ "pubic hair,extra digit, fewer digits, cropped, worst quality, low quality" | |
) | |
canny_edged_image = load_image( | |
"https://huggingface.co/takuma104/controlnet_dev/resolve/main/vermeer_canny_edged.png" | |
) | |
@torch.no_grad() | |
def generate(prompt, n_prompt, seed, control, ddim_steps=20, eta=0.0, scale=9.0, H=512, W=512): | |
seed_everything(seed) | |
cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([prompt] * num_samples)]} | |
un_cond = {"c_concat": [control], "c_crossattn": [model.get_learned_conditioning([n_prompt] * num_samples)]} | |
shape = (4, H // 8, W // 8) | |
samples, intermediates = ddim_sampler.sample(ddim_steps, num_samples, | |
shape, cond, 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__': | |
num_samples = 1 | |
model = create_model('./models/cldm_v15.yaml').cpu() | |
model.load_state_dict(load_state_dict('./models/control_sd15_canny.pth', location='cpu')) | |
model = model.cuda() | |
ddim_sampler = DDIMSampler(model) | |
control = torch.from_numpy(np.array(canny_edged_image).copy()).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'vermeer_canny_edged_seed_{seed}.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment