Level 3 In-Depth AI · Generative AI
Text-to-Image in Practice
How to get the image you want from a text-to-image model. Covers writing prompts and negative prompts, the guidance scale, steps and seeds, editing images with img2img and inpainting, controlling layout with ControlNet, and teaching a model a style or subject with LoRA. Also covers the rights and disclosure questions you should settle before publishing.
- Level
- ●●●●● Easy
- Reading
- 15 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 44 concepts →
- Quiz
- 5 questions ↓
Read first
Latent Diffusion and Stable DiffusionThis leads to
—The full path from zero — 44 concepts before this one
- What Is AI?
- Probability Basics
- Vectors
- Derivatives and Slopes
- How Machines Learn
- Probability Distributions
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Dot Product, Norms and Similarity
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Entropy, Cross-Entropy and KL Divergence
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Recurrent Neural Networks
- Backpropagation
- Activation Functions
- Word Embeddings
- What Generative Models Do
- Autoencoders
- Vanishing and Exploding Gradients
- Normalization Layers: BatchNorm and LayerNorm
- Image Classification
- Diffusion Models
- Variational Autoencoders
- LSTMs and GRUs
- Residual Connections
- Sequence-to-Sequence Models
- Attention
- Self-Attention and Multi-Head Attention
- Positional Encodings
- The Transformer
- BERT and Encoder Models
- Vision Transformers
- Sentence Embeddings
- CLIP and Contrastive Learning
- Latent Diffusion and Stable Diffusion
- Text-to-Image in Practice
Read them roughly in this order. See it on the concept map →
Why it matters
Image generators are now ordinary tools. Designers sketch concepts with them, marketers make product shots and variations, game studios explore characters, and people illustrate presentations, posts and stories. Hosted products (Midjourney, ChatGPT's and Gemini's image tools, Adobe Firefly) hide the settings. Open models (Stable Diffusion, FLUX, and others) expose every one, through the Python diffusers library or visual tools such as ComfyUI and Automatic1111.
Either way, the same handful of controls decide whether you get what you want: the prompt, the negative prompt, the guidance scale, the seed and steps, a starting image (img2img), a mask (inpainting), a structure map (ControlNet), and fine-tuned weights (LoRA). Each one connects directly to the mechanism explained in Latent Diffusion and Stable Diffusion. Knowing what a control does inside the model turns trial and error into deliberate adjustment.
This chapter is practical. If you are not technical, the Creating Images, Audio and Video with AI chapter covers hosted tools without code. Here we use open models and diffusers, because they show every knob.
The intuition
Think of the model as a very fast, very literal illustrator who has seen billions of captioned pictures but has never met you.
- The prompt is your brief. The illustrator responds to words that commonly appeared in captions of the kind of image you want.
- The negative prompt is the list of things you don't want. The model is pushed away from those.
- The guidance scale is how strictly the illustrator follows the brief, versus improvising.
- The seed fixes the random starting noise. Same seed, same settings, same picture, so you can change one thing at a time.
- img2img hands the illustrator a rough draft and says "redo this, changing it by this much".
- Inpainting masks out one region and says "only repaint this part".
- ControlNet gives them a tracing: edges, a depth map or a stick-figure pose to follow.
- LoRA is a short apprenticeship: a few dozen example images teach a new style, character or product.
Key idea Every control does one of three things: changes where sampling starts (seed, img2img, inpainting), changes what the denoiser is told at each step (prompt, negative prompt, guidance, ControlNet), or changes the denoiser's weights (LoRA, fine-tuning). Change one at a time, with a fixed seed.
How it works
Prompts that work
A text encoder turns the prompt into vectors, and cross-attention lets each part of the image draw on the relevant words (Latent Diffusion and Stable Diffusion). Practical consequences:
- Describe the image, not the request. Models were trained on captions, so "a watercolour of a lighthouse on a cliff at dusk, soft pink sky" works better than "can you make me a nice lighthouse picture".
- Cover the main dimensions: subject (who or what, doing what), setting, medium or style (photo, oil painting, 3-D render, flat vector icon), lighting (golden hour, studio softbox, neon), composition and camera (close-up, wide shot, from above, 85 mm lens, shallow depth of field), and mood or colour palette.
- Put the important things first and be specific. "A red 1960s convertible" beats "a car".
- Know your text encoder. Models using only CLIP (Stable Diffusion 1.5, partly SDXL) respond well to short, comma-separated keyword lists and have a 77-token limit. Models with a large language-model encoder such as T5 (SD3, FLUX, Imagen) understand full sentences, spatial relations ("a cat to the left of a dog") and quoted text to render ("a sign that says "OPEN"") much better.
- Weighting syntax such as
(lighthouse:1.3)is a convention of particular apps (Automatic1111, ComfyUI), not of the models themselves. Plaindiffusersignores it unless you add a helper library.
Negative prompts
Classifier-free guidance normally extrapolates away from an empty prompt. A negative prompt replaces that empty prompt with text describing what you don't want. The update becomes:
so each step moves towards the prompt and away from the negative. Typical uses are "blurry, low quality, watermark, text, extra fingers, deformed hands" for photos, or "photo, realistic" when you want an illustration. Keep negatives short and targeted. A long list of everything bad can flatten the image. Some distilled models (SDXL Turbo, FLUX.1 schnell and FLUX.1 dev in its default setup) don't use classifier-free guidance at all, so negative prompts have no effect there.
Guidance scale, steps, sampler, seed
- Guidance scale (, "CFG scale"). Higher values follow the prompt more literally and give less variety. Too high gives oversaturated, harsh, distorted images. The Latent Diffusion and Stable Diffusion chapter shows the effect on 2-D data. Typical starting points for these models: about 7 for SD 1.5, 5–7 for SDXL, around 3.5 for FLUX.1 dev (which uses a built-in "distilled guidance" value), and 0 for one-step Turbo models. Check each model card.
- Steps. More denoising steps give more detail, up to a point. 20–40 is typical for standard models with a good sampler, and 1–8 for distilled "turbo", "lightning" or "schnell" models. Doubling steps doubles generation time.
- Sampler or scheduler. The algorithm that takes the steps (Euler, DPM-Solver++, UniPC and others; see Diffusion Models). Differences are usually small. Keep the default unless you have a reason.
- Seed. Sets the initial noise. Generate a batch with different seeds to explore, then fix the best seed and refine the prompt. Results are reproducible only with the same model, settings, library version and, ideally, hardware.
- Resolution and aspect ratio. Generate at or near the model's native size (512² for SD 1.5, about 1024² in total pixels for SDXL, SD3 and FLUX). Much larger sizes cause duplicated subjects. For big images, generate at native size and then upscale, possibly with a light img2img pass ("hires fix").
img2img: start from an existing picture
img2img (image-to-image), based on the SDEdit method, starts sampling from a partly noised version of your picture instead of pure noise:
- Encode the input image to a latent with the VAE.
- Add noise up to an intermediate level set by the denoising strength , between 0 and 1.
- Run only the remaining denoising steps with your prompt.
With strength 0 the image comes back unchanged. With strength 1 the input is ignored, which is plain text-to-image. In between, the input fixes the overall layout and colours while the model redraws the details. For example, with num_inference_steps=30 and strength=0.6, diffusers runs only the last 18 steps. Practical ranges are about 0.2–0.4 for touch-ups and style tweaks, 0.5–0.7 for restyling a photo or turning a sketch into a render, and 0.8 or more for loose inspiration.
Inpainting and outpainting
Inpainting regenerates only a masked region: remove an object, change a shirt, fix a hand. At each step, the area outside the mask is reset to the (appropriately noised) original, so only the masked area is free to change, and the model blends it in. Dedicated inpainting checkpoints, trained with the mask and masked image as extra inputs, blend more cleanly than general models. Tips:
- Make the mask a little larger than the object, and describe what should be there, not what you are removing.
- Use a high strength (0.8–1.0) to replace something completely, and a lower one to adjust it.
- Outpainting is inpainting on an enlarged canvas whose new border is the "mask". It extends a picture beyond its frame.
ControlNet: follow a structure
Prompts are poor at exact layout. "Hand raised at shoulder height, head turned left" rarely comes out right. ControlNet (Zhang, Rao and Agrawala, 2023) adds a spatial condition: an edge map (Canny), a depth map, a human pose skeleton (OpenPose), line art, a segmentation map, and so on. Mechanically, it is a trainable copy of the denoiser's encoder half. It reads the control image and adds its features into the frozen main model through zero-initialised convolution layers, so at the start of training it changes nothing and can't damage the base model.
In practice:
- Make a control image from a reference, for example Canny edges of a product photo or the pose of a person.
- Generate with a prompt and the control image. The structure follows the map, and the prompt decides everything else.
- Tune the conditioning scale (about 0.5–1.0). Lower values let the model deviate from the map.
Related tools: IP-Adapter conditions on a reference image's look or subject instead of its structure, and T2I-Adapters are lighter ControlNet-like modules.
LoRA: teach a style, character or product
To make a model produce your product, character or house style, you fine-tune it. Full fine-tuning of billions of weights is expensive, and the result is a multi-gigabyte file. LoRA (low-rank adaptation, LoRA and Parameter-Efficient Fine-Tuning) instead freezes the model and learns small update matrices for selected layers, usually the attention projections. For a weight matrix the effective weight becomes , where and are thin matrices of rank (often 4–32). A LoRA file for SDXL is typically tens of megabytes instead of about 7 GB, and you can mix several and set each one's strength at load time.
Common recipes:
- Style LoRA: 20–100 images in a consistent style, with captions describing the content (so the style is what the LoRA learns).
- Subject or character LoRA, often combined with DreamBooth: 5–30 photos of one subject bound to a rare trigger word ("a photo of sks backpack on a beach"). DreamBooth's original method used 3–5 images and a "prior preservation" loss to stop the model forgetting what backpacks in general look like.
- Textual inversion learns only a new word embedding. It is tiny and weaker, but can capture a concept.
Training scripts for all three ship with diffusers. A style LoRA for SDXL can be trained in an hour or so on a single consumer GPU with 16–24 GB of memory, depending on settings.
In code
The pretrained pipelines below need downloads of several gigabytes and a GPU, so they are written carefully against the diffusers API (checked against version 0.43, late 2026) but not run here. First, text-to-image with all the main controls, then img2img and inpainting reusing the same loaded model:
import torch
from diffusers import AutoPipelineForText2Image, AutoPipelineForImage2Image, AutoPipelineForInpainting
from diffusers.utils import load_image
pipe = AutoPipelineForText2Image.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16, variant="fp16"
).to("cuda")
gen = torch.Generator("cuda").manual_seed(42) # fixed seed: reproducible
image = pipe(
prompt="product photo of a ceramic coffee mug on an oak table, morning window light, 85mm, shallow depth of field",
negative_prompt="blurry, low quality, text, watermark",
guidance_scale=6.0, num_inference_steps=30, width=1024, height=1024, generator=gen,
).images[0]
image.save("mug.png")
img2img = AutoPipelineForImage2Image.from_pipe(pipe) # same weights, no reload
restyled = img2img(prompt="the same mug, watercolour illustration", image=image,
strength=0.6, guidance_scale=6.0, generator=gen).images[0]
inpaint = AutoPipelineForInpainting.from_pipe(pipe)
mask = load_image("mug_mask.png") # white = repaint, black = keep
edited = inpaint(prompt="a blue ceramic mug with white polka dots", image=image,
mask_image=mask, strength=0.95, generator=gen).images[0]
ControlNet with a Canny edge map, plus a LoRA loaded from a local folder:
import cv2, numpy as np, torch
from PIL import Image
from diffusers import StableDiffusionXLControlNetPipeline, ControlNetModel
from diffusers.utils import load_image
edges = cv2.Canny(np.array(load_image("reference.jpg")), 100, 200) # structure to follow
control = Image.fromarray(np.stack([edges] * 3, axis=-1))
controlnet = ControlNetModel.from_pretrained("diffusers/controlnet-canny-sdxl-1.0", torch_dtype=torch.float16)
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
).to("cuda")
pipe.load_lora_weights("./my_style_lora", adapter_name="house_style") # your trained LoRA
pipe.set_adapters(["house_style"], adapter_weights=[0.8]) # LoRA strength
image = pipe("a cosy reading nook, house style illustration", image=control,
controlnet_conditioning_scale=0.6, num_inference_steps=30).images[0]
You can try img2img by hand without any download. Append this to the Normalizing Flows and Flow Matching chapter's code, after training. It produced the picture above:
import math
torch.manual_seed(7)
ang = torch.rand(400) * 2 * math.pi # the "input image": a ring
ring = torch.stack([1.2 * torch.cos(ang), 1.2 * torch.sin(ang)], 1) + 0.03 * torch.randn(400, 2)
def img2img(x_in, strength, steps=50):
t0 = 1 - strength # start part-way along the flow
x = t0 * x_in + (1 - t0) * torch.randn_like(x_in) # partly noised input
n = max(1, int(steps * strength)) # only the remaining steps
with torch.no_grad():
for k in range(n):
t = torch.full((len(x), 1), t0 + strength * k / n)
x = x + net(torch.cat([x, t], 1)) * strength / n
return x
for s in [0.05, 0.1, 0.25, 0.6]:
out = img2img(ring, s)
d = torch.cdist(out, X).min(1).values
print(f"strength {s}: on the moons {(d < 0.1).float().mean():.0%}, "
f"still ring-shaped (median |radius - 1.2|) {(out.norm(dim=1) - 1.2).abs().median():.2f}")
# strength 0.05: on the moons 26%, still ring-shaped (median |radius - 1.2|) 0.07
# strength 0.1: on the moons 47%, still ring-shaped (median |radius - 1.2|) 0.17
# strength 0.25: on the moons 87%, still ring-shaped (median |radius - 1.2|) 0.38
# strength 0.6: on the moons 93%, still ring-shaped (median |radius - 1.2|) 0.47
Common pitfalls
- Changing many things at once. Fix the seed and change one setting at a time, or you can't tell what helped.
- Guidance too high. Burnt colours and plastic-looking skin usually mean the scale is too high. Lower it before adding negatives.
- Wrong resolution. Duplicated heads or limbs usually come from generating far above the model's native size.
- Hands, text and counting. Older models in particular struggle with fingers, legible text and exact numbers of objects. Use a newer model with a strong text encoder, inpaint the problem area, or use ControlNet for pose.
- Overfitted LoRAs. Too many training steps or too few varied images produce a LoRA that copies its training pictures and ignores the prompt. Lower the LoRA strength or retrain with fewer steps and more varied captions.
- Mixing incompatible parts. A LoRA or ControlNet trained for SD 1.5 doesn't work with SDXL or FLUX. Match the base model family.
Watch out Settle rights and disclosure before you publish. As of late 2026:
- Licences. Open models come with licences that can restrict use. Stable Diffusion 1.5 and SDXL use OpenRAIL-style licences with use restrictions. FLUX.1 dev has a non-commercial licence, while FLUX.1 schnell is Apache 2.0. Stability's newer models use a community licence with a revenue threshold. Read the model card. Hosted services have their own terms.
- Copyright in outputs. In the US, the Copyright Office's position is that purely AI-generated material is not copyrightable, while human selection, arrangement and substantial modification can be protected. Other countries differ. Don't assume you own exclusive rights to a raw generation.
- Other people's rights. Prompting for a living artist's style, a trademarked character or a real person's likeness can infringe copyright, trademark, publicity or privacy rights, whatever tool you used. Lawsuits by artists and image libraries against model makers over training data were still being fought in several countries in 2026.
- Disclosure. Label realistic synthetic images, especially of real people, places or news events. Many platforms require it, and the EU AI Act requires deepfakes to be disclosed (its transparency rules apply from August 2026). Keep provenance metadata such as Content Credentials (C2PA) when your tools add it.
See Privacy, Data and Copyright, Deepfakes and Misinformation and Creating Images, Audio and Video with AI.
Where it leads
- Diffusion Transformers: the architecture behind SD3, FLUX and newer models, which follow long prompts and render text better.
- Video Generation: the same controls (prompt, image-to-video, ControlNet-style conditioning) for moving images.
- LoRA and Parameter-Efficient Fine-Tuning: the low-rank adaptation idea in detail, as used for LLMs.
- Fine-Tuning an Open Model in Practice: data preparation and evaluation habits that also apply to image LoRAs.
- Creating Images, Audio and Video with AI: creative workflows with hosted tools.
A bit of history
Text-to-image went from curiosity to everyday tool in about two years. DALL·E (OpenAI, January 2021) used an autoregressive Transformer over image tokens. The same month, CLIP made "steer an image towards a caption" possible, and within months hobbyists combined CLIP with VQGAN for the first wave of AI art. In 2022 came DALL·E 2 (April), Imagen (May), Midjourney's open beta (July) and Stable Diffusion (August). Stable Diffusion's open weights led to img2img and inpainting interfaces, DreamBooth fine-tuning (August 2022), community LoRA training (late 2022, adapting a 2021 language-model method) and ControlNet (February 2023).
SDXL (2023), DALL·E 3 (2023, trained on rewritten, highly descriptive captions) and then SD3 and FLUX.1 (2024) greatly improved prompt following and text rendering. Since 2024, image generation has also been built directly into multimodal assistants, which let people edit images by conversation. In parallel, the C2PA / Content Credentials standard for provenance metadata gained support from camera makers, Adobe, OpenAI, Google and others.
Try it
- With a fixed seed, generate the same prompt at guidance scales 2, 5, 8 and 12 (on any open model, or a hosted tool that exposes the setting). Describe what changes. Then run the 2-D guidance experiment in Latent Diffusion and Stable Diffusion and compare.
- Take a photo of your own and run img2img with strengths 0.3, 0.5 and 0.7 and a prompt for a different style. At which strength does the photo stop being recognisable?
- Write down, for one image you would like to publish, its model and licence, whether a real person or brand appears, and how you will disclose that it is AI-generated.
Hint for 2: recognisability usually drops sharply somewhere between 0.5 and 0.7, as in the ring-to-moons picture.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Diffusers documentation
The official guide to the diffusers library: pipelines for text-to-image, img2img, inpainting, ControlNet, LoRA loading, schedulers and training scripts.
Hugging Face Diffusion Models Course
Theory and hands-on notebooks for training and using diffusion models with the diffusers library.
Diffusion Explainer
An interactive visual walk through how Stable Diffusion turns a prompt into an image, including the effect of the guidance scale.
Adding Conditional Control to Text-to-Image Diffusion Models
ControlNet: steer a frozen diffusion model with edges, depth maps or poses through a trainable copy joined by zero-initialised layers.
LoRA: Low-Rank Adaptation of Large Language Models
Fine-tuning by learning small low-rank updates instead of all weights.
DreamBooth: Fine Tuning Text-to-Image Diffusion Models for Subject-Driven Generation
Teach a model a specific subject from 3 to 5 photos, bound to a rare token in the prompt.
Content Credentials
The open standard for labelling how an image, video or audio file was made, including by AI, with a free tool to inspect a file's credentials.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/generative/text-to-image.md