Generating an image from text with Diffusers

MediumDiffusion models and image generationImage generation

Goal: Loading a diffusion pipeline and generating an image.

Python — example.py
import torch
from diffusers import DiffusionPipeline

pipe = DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base", torch_dtype=torch.float16)
pipe = pipe.to("cuda")
image = pipe("a watercolor painting of a robot reading a book", num_inference_steps=25).images[0]
image.save("robot.png")

Code explanation

DiffusionPipeline.from_pretrained loads all the model's components (the text encoder, the U-Net, the scheduler and the decoder). It needs a GPU with enough memory and a download of several gigabytes, and some models require accepting their license on Hugging Face. Not run in the test environment.

Requirements

Shell
pip install diffusers transformers accelerate torch

How to run

Save the code in a file example.py then run it:

Shell
python example.py

This example was not run in the test environment: needs a GPU and a download of the model weights. Check it against the library documentation before relying on it.

Libraries used

Related examples