By the end of this lesson you will be able to:
- Explain how diffusion models create images by removing noise step by step.
- Write image prompts with subject, style, composition and lighting.
- Call an image generation API and choose its settings.
- Build image features safely: content rules, consent, copyright and labelling.
Why images matter for our study buddy
A picture of the water cycle, a labelled diagram of a plant cell, a cartoon of Newton's apple. Visuals make lessons stick. Our startup wants teachers to type a description and instantly get a classroom-ready illustration. That's an image generation application.
Popular image models include OpenAI's GPT Image and DALL·E models, Stable Diffusion (open weights), Google's Imagen and Midjourney. Most of them are built on the same core idea: diffusion.
How diffusion works: from noise to picture
During training, a diffusion model is shown millions of images with captions. Each image is gradually destroyed by adding random noise, and the model learns to predict and remove a little noise at each step. It learns this given the caption, so the text steers what the noise turns into.
To create a new image, the model starts from pure random noise and runs the process in reverse: dozens of small denoising steps, each guided by your prompt, until a clear picture appears. Try it in 3D:
A useful mental model, not the full maths. Real models denoise millions of pixels (often in a compressed "latent" space), and a text encoder turns your prompt into the guidance signal. But "start with noise, remove a bit at a time, steered by text" is exactly what happens.
Writing great image prompts
Image prompts work best as a list of visual details. Build them from these parts:
- Subject: what's in the picture. "A girl in school uniform watering a tulsi plant".
- Style or medium: "flat vector illustration", "watercolour", "3D render", "pencil sketch", "photo".
- Composition: "close-up", "wide shot", "top-down view", "centred on a white background".
- Lighting and colour: "soft morning light", "pastel colours", "high contrast".
- Purpose and constraints: "for a Class 6 textbook, simple shapes, no text".
Weak prompt
water cycle
Random style, cluttered, unusable labels.
Strong prompt
Flat vector illustration of the water cycle
for a Class 6 textbook: sea, sun, clouds,
rain over green hills, arrows showing
evaporation and rain. Bright friendly
colours, white background, no text.
Clear, on-style, ready for a worksheet.
Text inside images is still a weak spot for many models. Generate the picture without words and add labels yourself in a design tool, or with HTML on your site.
Calling an image API
On your machine, with an API key (same setup as Lesson 6):
result = client.images.generate(
model="gpt-image-1", # or another image model your account has
prompt="Flat vector illustration of the water cycle for a Class 6 textbook, white background, no text",
size="1024x1024",
n=1,
)
# Depending on the model you get a URL or base64 image data; save it to a file.
- size: square, landscape or portrait. Larger images cost more.
- quality: some models offer standard vs high quality.
- n: how many images to generate, so the teacher can pick the best.
Many models also support editing (change part of an image using a mask: "replace the sky with a sunset") and variations (similar images from an existing one).
A system message for images
Just like chat apps, image apps wrap the user's request in rules before it reaches the model. For a school product:
You turn teachers' requests into image prompts for school material.
- Always child-appropriate: no violence, gore, weapons or adult content.
- Never depict real, identifiable people or copy a living artist's style.
- Prefer simple, clear educational illustrations with no text.
- If a request breaks these rules, reply exactly: BLOCKED
The app first sends the teacher's request to a text model with these rules, then sends the improved, safe prompt to the image model.
Responsible image generation
- Deepfakes and consent: never generate realistic images of real people, especially students, without consent.
- Copyright and style: avoid prompts that copy a specific living artist or a trademarked character.
- Bias: "a scientist" or "a nurse" may come out as stereotypes. Ask for diversity explicitly.
- Transparency: label AI-generated images, and keep the content filters on.
Hands-on
Your task: finish build_image_prompt() so it joins the non-empty parts with ", " and also returns a negative prompt (things to avoid) made from the avoid list. Many tools, like Stable Diffusion, accept a separate negative prompt. Expected last line: Negative prompt: text, watermark, blurry, scary.
request = {
"subject": "a girl in school uniform watering a tulsi plant",
"style": "flat vector illustration",
"composition": "centred, white background",
"lighting": "soft morning light, pastel colours",
"purpose": "for a Class 4 environmental studies worksheet",
}
avoid = ["text", "watermark", "blurry", "scary"]
def build_image_prompt(parts, avoid):
order = ["style", "subject", "composition", "lighting", "purpose"]
# TODO: prompt = the values in this order (skip empty ones) joined with ", "
# TODO: negative = the avoid list joined with ", "
prompt = ""
negative = ""
return prompt, negative
prompt, negative = build_image_prompt(request, avoid)
print("Prompt:", prompt)
print("Negative prompt:", negative)
Show solution
prompt = ", ".join(parts[k] for k in order if parts.get(k))
negative = ", ".join(avoid)
Your task: this toy "image" is just 8 brightness values. It starts as random noise. Each step should move every pixel a fraction of the way towards the target. Complete the update line and watch the error fall to zero, just like the 3D demo. Expected last line: Final error: 0.00.
import random
random.seed(7)
target = [0.0, 0.2, 0.6, 1.0, 1.0, 0.6, 0.2, 0.0] # a simple "bright bar" picture
image = [random.random() for _ in target] # start: pure noise
def error(img):
return sum(abs(a - b) for a, b in zip(img, target)) / len(img)
def show(img):
shades = " .:-=+*#%@"
return "".join(shades[min(9, int(v * 9.99))] * 3 for v in img)
steps = 30
for step in range(1, steps + 1):
strength = step / steps # remove more noise as we go
# TODO: move each pixel towards its target: new = old + strength * (target - old)
image = image
if step in (1, 5, 10, 20, 30):
print(f"Step {step:2}: {show(image)} error {error(image):.2f}")
print(f"Final error: {error(image):.2f}")
Show solution
image = [old + strength * (t - old) for old, t in zip(image, target)]
Check your understanding
How does a diffusion model create a new image?
- It searches the internet for a matching photo
- It paints pixels left to right like a printer
- It starts from random noise and removes noise step by step, guided by the prompt
- It edits a stock image
Generation reverses the noising process. Each denoising step is steered by the text prompt.
A teacher needs a labelled diagram of a flower. What's the most reliable approach?
- Generate the picture without text, then add labels yourself
- Ask the model to spell every label perfectly
- Use a very high temperature
- Generate 100 images and hope
Text inside generated images is often wrong. Add labels with a design tool or HTML.
A user asks for a realistic photo of a classmate doing something embarrassing. Your app should…
- Generate it with a watermark
- Refuse: realistic images of real people need consent and can cause harm
- Generate it in cartoon style instead
- Ask for the classmate's photo first
Images of real, identifiable people (deepfakes) can seriously harm them. Block these requests.
Key takeaways
- Diffusion models start from noise and remove it step by step, guided by your prompt.
- Strong image prompts list subject, style, composition, lighting and purpose.
- Use a text model with rules to clean prompts before they reach the image model.
- Protect real people, respect creators, watch for bias and label AI images.
Next: build AI apps with little or no code, using low-code platforms.
Your progress is saved in this browser.
Adapted from Lesson 9 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source