Views
No views yet











1from diffusers import ControlNetModel, StableDiffusionXLControlNetPipeline, AutoencoderKL
2from diffusers import DDIMScheduler, EulerAncestralDiscreteScheduler
3from PIL import Image
4import torch
5import random
6import numpy as np
7import cv2
8
9
10from controlnet_aux import MidasDetector, ZoeDetector
11
12
13processor_zoe = ZoeDetector.from_pretrained("lllyasviel/Annotators")
14processor_midas = MidasDetector.from_pretrained("lllyasviel/Annotators")
15
16
17controlnet_conditioning_scale = 1.0
18prompt = "your prompt, the longer the better, you can describe it as detail as possible"
19negative_prompt = 'longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality'
20
21eulera_scheduler = EulerAncestralDiscreteScheduler.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0", subfolder="scheduler")
22
23
24controlnet = ControlNetModel.from_pretrained(
25 "xinsir/controlnet-depth-sdxl-1.0",
26 torch_dtype=torch.float16
27)
28
29# when test with other base model, you need to change the vae also.
30vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", torch_dtype=torch.float16)
31
32pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
33 "stabilityai/stable-diffusion-xl-base-1.0",
34 controlnet=controlnet,
35 vae=vae,
36 safety_checker=None,
37 torch_dtype=torch.float16,
38 scheduler=eulera_scheduler,
39)
40
41# need to resize the image resolution to 1024 * 1024 or same bucket resolution to get the best performance
42
43img = cv2.imread("your original image path")
44
45if random.random() > 0.5:
46 controlnet_img = processor_zoe(img, output_type='cv2')
47else:
48 controlnet_img = processor_midas(img, output_type='cv2')
49
50
51height, width, _ = controlnet_img.shape
52ratio = np.sqrt(1024. * 1024. / (width * height))
53new_width, new_height = int(width * ratio), int(height * ratio)
54controlnet_img = cv2.resize(controlnet_img, (new_width, new_height))
55controlnet_img = Image.fromarray(controlnet_img)
56
57
58images = pipe(
59 prompt,
60 negative_prompt=negative_prompt,
61 image=controlnet_img,
62 controlnet_conditioning_scale=controlnet_conditioning_scale,
63 width=new_width,
64 height=new_height,
65 num_inference_steps=30,
66 ).images
67
68images[0].save(f"your image save path, png format is usually better than jpg or webp in terms of image quality but got much bigger")