Diffusers documentation

ControlNet

You are viewing main version, which requires installation from source. If you'd like regular pip install, checkout the latest stable version (v0.43.0).
Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

ControlNet

يوجّه ControlNet نموذج الانتشار المُدرَّب مسبقًا باستخدام صورة تحكم بنيوية (حواف، عمق، أو وضعية) مع الحفاظ على موجه نصي. يقوم بتجميد النموذج الأساسي وإضافة شبكة متوازية تُوجّه المُزيل للضوضاء عبر بقاياها، مما يمنحك تحكمًا في التخطيط دون الحاجة إلى ضبط دقيق.

حمّل نموذج ControlNet للتحكم الذي تحتاجه (على سبيل المثال canny)، ثم مرره كـcontrolnet= إلى from_pretrained(). استخدم controlnet_conditioning_scale لضبط مدى قوة توجيه التحكم لعملية التوليد.

تتوفر شبكات ControlNet للعديد من النماذج مثل Flux وHunyuan-DiT وStable Diffusion 3 وغيرها. تستخدم الأمثلة في هذا الدليل Flux وStable Diffusion XL. للاطلاع على T2I-Adapter الخاص بنقاط التفتيش الأقدم من عائلة Stable Diffusion، راجع المُكيّفات القديمة. يُفضَّل استخدام ControlNet لأعمال التوليد القابل للتحكم الجديدة.

تُظهر التبويبات أدناه ControlNet لتوليد الصور من النص، وتحويل الصورة إلى صورة، والتعبئة (Inpainting).

النص إلى صورة
صورة إلى صورة
التلوين

أنشئ صورة كاني باستخدام opencv-python.

import cv2
import numpy as np
from PIL import Image
from diffusers.utils import load_image

original_image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png"
)

image = np.array(original_image)

low_threshold = 100
high_threshold = 200

image = cv2.Canny(image, low_threshold, high_threshold)
image = image[:, :, None]
image = np.concatenate([image, image, image], axis=2)
canny_image = Image.fromarray(image)

مرّر صورة canny إلى خط الأنابيب. استخدم معامل controlnet_conditioning_scale لتحديد مقدار الوزن الذي تريد منحه للتحكم.

import torch
from diffusers.utils import load_image
from diffusers import FluxControlNetPipeline, FluxControlNetModel

controlnet = FluxControlNetModel.from_pretrained(
    "InstantX/FLUX.1-dev-Controlnet-Canny", dtype=torch.bfloat16
)
pipeline = FluxControlNetPipeline.from_pretrained(
    "black-forest-labs/FLUX.1-dev", controlnet=controlnet, dtype=torch.bfloat16
).to("cuda")  # or "mps", "xpu", "cpu"

prompt = """
A photorealistic overhead image of a cat reclining sideways in a flamingo pool floatie holding a margarita. 
The cat is floating leisurely in the pool and completely relaxed and happy.
"""

pipeline(
    prompt, 
    control_image=canny_image,
    controlnet_conditioning_scale=0.5,
    num_inference_steps=50, 
    guidance_scale=3.5,
).images[0]
Generated image (prompt only)
الصورة الأصلية
Control image (Canny edges)
صورة كان
Generated image (ControlNet + prompt)
صورة مولّدة

Multi-ControlNet

قم بتكوين عدة وحدات ControlNet (على سبيل المثال canny + depth) عن طريق تمريرها كقائمة. قم بتقناع المناطق المتداخلة عندما يكون ذلك ممكنًا، وضبط كل controlnet_conditioning_scale. أنشئ canny_image باستخدام OpenCV Canny (كما في النص إلى صورة) وdepth_image باستخدام DPT (كما في الصورة إلى صورة). أعد تحجيم كل صورة تحكم إلى حجم خط الأنابيب قبل استدعاء خط الأنابيب.

import cv2
import torch
import numpy as np
from PIL import Image
from transformers import DPTImageProcessor, DPTForDepthEstimation
from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel, AutoencoderKL
from diffusers.utils import load_image

original_image = load_image(
    "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/non-enhanced-prompt.png"
)
image = np.array(original_image)
canny_image = Image.fromarray(
    np.concatenate([cv2.Canny(image, 100, 200)[:, :, None]] * 3, axis=2)
)

device = "cuda"  # or "mps", "xpu", "cpu"
depth_estimator = DPTForDepthEstimation.from_pretrained("Intel/dpt-hybrid-midas").to(device)
feature_extractor = DPTImageProcessor.from_pretrained("Intel/dpt-hybrid-midas")

def get_depth_map(image):
    image = feature_extractor(images=image, return_tensors="pt").pixel_values.to(device)
    with torch.no_grad(), torch.autocast(device):
        depth_map = depth_estimator(image).predicted_depth

    depth_map = torch.nn.functional.interpolate(
        depth_map.unsqueeze(1),
        size=(1024, 1024),
        mode="bicubic",
        align_corners=False,
    )
    depth_min = torch.amin(depth_map, dim=[1, 2, 3], keepdim=True)
    depth_max = torch.amax(depth_map, dim=[1, 2, 3], keepdim=True)
    depth_map = (depth_map - depth_min) / (depth_max - depth_min)
    image = torch.cat([depth_map] * 3, dim=1)
    image = image.permute(0, 2, 3, 1).cpu().numpy()[0]
    image = Image.fromarray((image * 255.0).clip(0, 255).astype(np.uint8))
    return image

depth_image = get_depth_map(original_image.resize((1024, 1024)))

controlnets = [
    ControlNetModel.from_pretrained(
        "diffusers/controlnet-canny-sdxl-1.0", dtype=torch.float16
    ),
    ControlNetModel.from_pretrained(
        "diffusers/controlnet-depth-sdxl-1.0-small", dtype=torch.float16
    ),
]

vae = AutoencoderKL.from_pretrained("madebyollin/sdxl-vae-fp16-fix", dtype=torch.float16)
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
    "stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnets, vae=vae, dtype=torch.float16
).to(device)

prompt = """
a relaxed rabbit sitting on a striped towel next to a pool with a tropical drink nearby, 
bright sunny day, vacation scene, 35mm photograph, film, professional, 4k, highly detailed
"""
negative_prompt = "lowres, bad anatomy, worst quality, low quality, deformed, ugly"

images = [canny_image.resize((1024, 1024)), depth_image.resize((1024, 1024))]

pipeline(
    prompt,
    negative_prompt=negative_prompt,
    image=images,
    num_inference_steps=100,
    controlnet_conditioning_scale=[0.5, 0.5],
).images[0]
Canny image
صورة كان
Depth map
خريطة العمق
Generated image (ControlNet + prompt)
صورة مولّدة

وضع التخمين

يولّد وضع التخمين صورةً من عنصر التحكم وحده عندما لا تملك (أو لا ترغب في استخدام) موجه نصي. يقوم هذا الوضع بتقليص بقايا ControlNet حسب عمق الكتلة، بدءًا من حوالي 0.1 في الكتل السفلية المبكرة وصولًا إلى 1.0 في الكتلة الوسطى. وهذا يمنع الطبقات المبكرة من فرض قيود مفرطة، بينما تواصل الكتل الأعمق حمل البنية.

import torch
from diffusers.utils import load_image
from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel

controlnet = ControlNetModel.from_pretrained(
  "diffusers/controlnet-canny-sdxl-1.0", dtype=torch.float16
)
pipeline = StableDiffusionXLControlNetPipeline.from_pretrained(
  "stabilityai/stable-diffusion-xl-base-1.0",
  controlnet=controlnet,
  dtype=torch.float16
).to("cuda")  # or "mps", "xpu", "cpu"

canny_image = load_image("https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/canny-cat.png")
pipeline(
  "",
  image=canny_image,
  guess_mode=True
).images[0]
Canny image
صورة كان
Generated image (Guess mode)
صورة مولّدة
Update on GitHub