ControlNet is a type of model for controlling image diffusion models by conditioning the model with an additional input image. There are many types of conditioning inputs (canny edge, user sketching, human pose, depth, and more) you can use to control a diffusion model. This is hugely useful because it affords you greater control over image generation, making it easier to generate specific images without experimenting with different text prompts or denoising values as much.
Check out Section 3.5 of the paper for a list of ControlNet implementations on various conditioning inputs. You can find the official Stable Diffusion ControlNet conditioned models on ’s Hub profile, and more ones on the Hub.
For Stable Diffusion XL (SDXL) ControlNet models, you can find them on the 🌍 Hub organization, or you can browse ones on the Hub.
A ControlNet model has two sets of weights (or blocks) connected by a zero-convolution layer:
a locked copy keeps everything a large pretrained diffusion model has learned
a trainable copy is trained on the additional conditioning input
Since the locked copy preserves the pretrained model, training and implementing a ControlNet on a new conditioning input is as fast as finetuning any other model because you aren’t training the model from scratch.
This guide will show you how to use ControlNet for text-to-image, image-to-image, inpainting, and more! There are many types of ControlNet conditioning inputs to choose from, but in this guide we’ll only focus on several of them. Feel free to experiment with other conditioning inputs!
Before you begin, make sure you have the following libraries installed:
Copied
# uncomment to install the necessary libraries in Colab
#!pip install diffusers transformers accelerate safetensors opencv-python
Text-to-image
For text-to-image, you normally pass a text prompt to the model. But with ControlNet, you can specify an additional conditioning input. Let’s condition the model with a canny image, a white outline of an image on a black background. This way, the ControlNet can use the canny image as a control to guide the model to generate an image with the same outline.
Load an image and use the library to extract the canny image:
Now pass your prompt and canny image to the pipeline:
Copied
output = pipe(
"the mona lisa", image=canny_image
).images[0]
Image-to-image
For image-to-image, you’d typically pass an initial image and a prompt to the pipeline to generate a new image. With ControlNet, you can pass an additional conditioning input to guide the model. Let’s condition the model with a depth map, an image which contains spatial information. This way, the ControlNet can use the depth map as a control to guide the model to generate an image that preserves spatial information.
Load an image and use the depth-estimationPipeline from 🌍 Transformers to extract the depth map of an image:
Now pass your prompt, initial image, and depth map to the pipeline:
Copied
output = pipe(
"lego batman and robin", image=image, control_image=depth_map,
).images[0]
Inpainting
For inpainting, you need an initial image, a mask image, and a prompt describing what to replace the mask with. ControlNet models allow you to add another control image to condition a model with. Let’s condition the model with a canny image, a white outline of an image on a black background. This way, the ControlNet can use the canny image as a control to guide the model to generate an image with the same outline.
Create a function to prepare the control image from the initial and mask images. This’ll create a tensor to mark the pixels in init_image as masked if the corresponding pixel in mask_image is over a certain threshold.
Now pass your prompt, initial image, mask image, and control image to the pipeline:
Copied
output = pipe(
"corgi face with large ears, detailed, pixar, animated, disney",
num_inference_steps=20,
eta=1.0,
image=init_image,
mask_image=mask_image,
control_image=control_image,
).images[0]
Guess mode
Guess mode adjusts the scale of the output residuals from a ControlNet by a fixed ratio depending on the block depth. The shallowest DownBlock corresponds to 0.1, and as the blocks get deeper, the scale increases exponentially such that the scale of the MidBlock output becomes 1.0.
Guess mode does not have any impact on prompt conditioning and you can still provide a prompt if you want.
You can compose multiple ControlNet conditionings from different image inputs to create a MultiControlNet. To get better results, it is often helpful to:
mask conditionings such that they don’t overlap (for example, mask the area of a canny image where the pose conditioning is located)
In this example, you’ll combine a canny image and a human pose estimation image to generate a new image.
Prepare the canny image conditioning:
Copied
from diffusers.utils import load_image
from PIL import Image
import numpy as np
import cv2
canny_image = load_image(
"https://boincai.com/datasets/boincai/documentation-images/resolve/main/diffusers/landscape.png"
)
canny_image = np.array(canny_image)
low_threshold = 100
high_threshold = 200
canny_image = cv2.Canny(canny_image, low_threshold, high_threshold)
# zero out middle columns of image where pose will be overlayed
zero_start = canny_image.shape[1] // 4
zero_end = zero_start + canny_image.shape[1] // 2
canny_image[:, zero_start:zero_end] = 0
canny_image = canny_image[:, :, None]
canny_image = np.concatenate([canny_image, canny_image, canny_image], axis=2)
canny_image = Image.fromarray(canny_image).resize((1024, 1024))
Prepare the human pose estimation conditioning:
Copied
from controlnet_aux import OpenposeDetector
from diffusers.utils import load_image
openpose = OpenposeDetector.from_pretrained("lllyasviel/ControlNet")
openpose_image = load_image(
"https://boincai.com/datasets/boincai/documentation-images/resolve/main/diffusers/person.png"
)
openpose_image = openpose(openpose_image).resize((1024, 1024))
Now you can pass your prompt (an optional negative prompt if you’re using one), canny image, and pose image to the pipeline:
Copied
prompt = "a giant standing in a fantasy landscape, best quality"
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
generator = torch.manual_seed(1)
images = [openpose_image, canny_image]
images = pipe(
prompt,
image=images,
num_inference_steps=25,
generator=generator,
negative_prompt=negative_prompt,
num_images_per_prompt=3,
controlnet_conditioning_scale=[1.0, 0.8],
).images[0]
original image
canny image
Next, load a ControlNet model conditioned on canny edge detection and pass it to the . Use the faster and enable model offloading to speed up inference and reduce memory usage.
You’ll use the for this task, which is different from the because it allows you to pass an initial image as the starting point for the image generation process.
Next, load a ControlNet model conditioned on depth maps and pass it to the . Use the faster and enable model offloading to speed up inference and reduce memory usage.
original image
generated image
original image
mask image
Load a ControlNet model conditioned on inpainting and pass it to the . Use the faster and enable model offloading to speed up inference and reduce memory usage.
does not require supplying a prompt to a ControlNet at all! This forces the ControlNet encoder to do it’s best to “guess” the contents of the input control map (depth map, pose estimation, canny edge, etc.).
Set guess_mode=True in the pipeline, and it is to set the guidance_scale value between 3.0 and 5.0.
regular mode with prompt
guess mode without prompt
There aren’t too many ControlNet models compatible with Stable Diffusion XL (SDXL) at the moment, but we’ve trained two full-sized ControlNet models for SDXL conditioned on canny edge detection and depth maps. We’re also experimenting with creating smaller versions of these SDXL-compatible ControlNet models so it is easier to run on resource-constrained hardware. You can find these checkpoints on the 🌍 Hub organization!
canny image
original image
Load a SDXL ControlNet model conditioned on canny edge detection and pass it to the . You can also enable model offloading to reduce memory usage.
The parameter determines how much weight to assign to the conditioning inputs. A value of 0.5 is recommended for good generalization, but feel free to experiment with this number!
You can use in guess mode as well by setting the parameter to True:
Replace the SDXL model with a model like to use multiple conditioning inputs with Stable Diffusion models.
experiment with the parameter to determine how much weight to assign to each conditioning input
original image
canny image
human pose image
original image
Load a list of ControlNet models that correspond to each conditioning, and pass them to the . Use the faster and enable model offloading to reduce memory usage.