翻篇收录说明
翻篇网页快照

How to Generate Images Using Stable Diffusion? - Analytics Vidhya

https://www.analyticsvidhya.com/blog/2023/05/how-to-generate-images-using-stable-diffusion/

最近抓取:2026-12-03 21:27:50(北京时间)

最近内容变化:2026-12-03 21:27:50(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Learn how to generate images using Stable Diffusion, a Hugging Face pipeline built on PyTorch for text-to-image & text-to-video conversion.

正文摘录

India's Most Futuristic AI Conference Is Back – Bigger, Sharper, Bolder d : h : m : s Get Details Interview PrepCareerGenAIPrompt EnggChatGPTLLMLangchainRAGAI AgentsMachine LearningDeep LearningGenAI ToolsLLMOpsPythonNLPSQLAIML Projects Reading list Introduction to Generative AIWhat is Generative AI? Introduction to Generative AI applicationsOverview of generative AI applications and their impact No-code Generative AI app developmentIntroduction to No-code AI Development Code-focused Generative AI App DevelopmentIntroduction to LangChain, ChatGPT and Gemini Pro Introduction to Responsible AIIntroduction to Responsible AI LLMSWhat are Large Language Models?GPT modelsMistralLlamaGeminiHow to build diffferent LLM AppIications? Prompt EngineeringIntroduction to Prompt EngineeringBest Practices and Guidelines for Prompt EngineeringN shot promptingChain of ThoughtTree of ThoughtsSkeleton of ThoughtsChain of Emotion Finetuning LLMsIntroduction to Finetuning LLMsParameter-Efficient Finetuning (PEFT)LORAQLORAusing Unslothusing Huggingface Training LLMs from ScratchWhat do you mean by Training LLMs from Scratch? LangchainIntro to the LangChain EcosystemCore Components of LangChainApplications of LCEL ChainsRAG using LangChainLangGraphLangSmith RAGIntroduction to RAG systemsEvaluation of RAG systems LlamaIndexGetting Started with LlamaIndexComponents of LlamaIndexAdvanced approaches for powerful RAG system Stable DiffusionIntroduction to Stable DiffusionGenerating image using Stable diffusionDiffusion modelsPrompt Engineering Concepts for Stable DiffusionMidJourneyUnderstanding Dalle 3 Guide to Image-to-Image Diffusion: A Hugging Face Pipeline Mobarak Inuwa Last Updated : 24 Oct, 2024 9 min read By applying specific modern state-of-the-art techniques, stable diffusion models make it possible to generate images and audio. Stable Diffusion works by modifying input data with the guide of text input and generating new creative output data. In this article, we will see how to generate new images from a given input image by employing depth-to-depth model diffusers on the PyTorch backend with a Hugging Face pipeline. We are using Hugging Face since they have made an easy-to-use image generation using stable diffusion pipeline available. Learn More: Hugging Face Transformers Pipeline Functions Learning Objectives Understand the concept of Stable Diffusion and its application in generating images and audio using modern state-of-the-art techniques. Gain knowledge of the key components and techniques involved in Stable Diffusion, such as latent diffusion models, denoising autoencoders, variational autoencoders, U-Net blocks, and text encoders. Explore common applications of diffusion models, including text-to-image, text-to-videos, and text-to-3D conversions. Learn how to set up the environment for Stable Diffusion, including utilizing GPU and installing necessary libraries and dependencies. Develop practical skills in applying Stable Diffusion by loading and diffusing images, creating text prompts to guide the output, adjusting diffusion levels, and understanding the limitations and challenges associated with image generation using stable diffusion models. This article was published as a part of the Data Science Blogathon. Table of contentsWhat is a Stable Diffusion?The Concepts of Stable DiffusionCommon Applications of DiffusionSetting Up EnvironmentImporting DependenciesInstantiating the Pre-trained DiffusersPreparing Image DataLoading ImageCreating Text PromptsCreating Negative PromptsAdjusting Diffusion LevelLimitations of Diffusion ModelsConclusionFrequently Asked Questions What is a Stable Diffusion? Stable Diffusion models function as latent diffusion models. It learns the latent structure of input by modeling how the data attributes diffuse through the latent space. They belong to the deep generative neural network. It is considered stable because we guide the results using original images, text, etc. On the other hand, an unstable diffusion will be unpredictable. The Concepts of Stable Diffusion Stable Diffusion uses the Diffusion or latent image generation using stable diffusion model (LDM), a probabilistic model. These models are trained like other deep learning models. Still, the objective here is removing the need for continuous applications of signal processing denoting a kind of noise in the signals in which the probability density function equals the normal distribution. We refer to this as the Gaussian noise applied to the training images. We achieve this through a sequence of denoising autoencoders (DAE). DAEs contribute by changing the reconstruction criterion. This is what alters the continuous application of signal processing. It is initialized to add a noise process to the standard autoencoder. In a more detailed explanation, Stable Diffusion consists of 3 essential parts: First is the variational autoencoder (VAE) which, in simple terms, is an artificial neural network that performs as probabilistic graphical models. Next is the U-Net block. This convolutional neural network (CNN) was developed for image segmentation. Lastly is the text encoder part. A trained CLIP ViT-L/14 text encoder deals with this. It handles the transformations of the text prompts into an embedding space. The VAE encoder compresses the image pixel space values into a smaller dimensional latent space to carry out image diffusion. This helps the image not to lose details. It is represented again in pixeled pictures. Common Applications of Diffusion Let us quickly look at three common areas where diffusion models can be applied: Text-to-Image: This approach does not use images but a piece of text “prompt” to generate related photos. Text-to-Videos: Diffusion models are used for generating videos out of text prompts. Current research uses this in media to do interesting feats like creating online ad videos, explaining concepts, and creating short animation videos, song videos, etc. Text-to-3D: This stable image generation using stable diffusion approach converts input text to 3D images. Applying diffusers can help generate free images that are plagiarism free. This provides content for your projects, materials, and even marketing brands. Instead of hiring a painter or photographer, you can generate your images. Instead of a voice-over artist, you can create your unique audio. Now let’s look at Image-to-image Generation. Also Read: Bring Doodles to Life: Meta Open-Sources AI Model Setting Up Environment This task requires GPU and a good development environment like processing images and graphics. You are expected to ensure you have GPU available if you want to follow along with this project. We can use Google Colab since it provides a suitable environment and GPU, and you can search for it online. Follow the steps below to engage the available GPU: Go to the Runtime tab towards the top right. After selecting Runtime, click the Change Runtime Type option. Then select GPU as a hardware accelerator from the drop-down option. You can find all the code on GitHub. Importing Dependencies There are several dependencies in using the pipeline from Huggingface. We will first start by importing them into our project environment. Installing Libraries Some libraries are not preinstalled in Colab. We need to start by installing them before importing from them. # Installing required libraries %pip install --quiet --upgrade diffusers transformers scipy ftfy # Installing required libraries %pip install --quiet --upgrade accelerate Let us explain the installations we have done above. Firstly are the diffusers, transformers, scipy, and ftfy. SciPy and ftfy are standard Python libraries we employ for everyday Python tasks. We will explain the new major libraries below. Diffusers: Diffusers is a library made available by Hugging Face for getting well-trained image to image stable diffusion models for generating images. We are going to use it for accessing our pipeline and other packages. Transformers: Transformers contain tools and APIs that help us cut training costs from scratch. # Backend import torch # Internet access import requests # Regular Python library for Image processing from PIL import Image # Hugging face pipeline from diffusers import StableDiffusionDepth2ImgPipeline StableDiffusionDepth2ImgPipeline is the library that reduces our code. All we need to do is pass an image and a prompt describing our expectations. Instantiating the Pre-trained Diffusers Next, we just make an instance of the pre-trained diffuser we imported above and assign it to our GPU. Here this is Cuda. # Creating a variable instance of the pipeline pipe = StableDiffusionDepth2ImgPipeline.from_pretrained( "stabilityai/stable-diffusion-2-depth", torch_dtype=torch.float16, ) # Assigning to GPU pipe.to("cuda") Preparing Image Data Let’s define a function to help us check images from URLs. You can skip this step to try an image you have locally. Mount the drive in Colab. # Accesssing images from the web import urllib.parse as parse import os import requests # Verify URL def check_url(string): try: result = parse.urlparse(string) return all([result.scheme, result.netloc, result.path]) except: return False We can define another function to use the check_url function for loading an image. # Load an image def load_image(image_path): if check_url(image_path): return Image.open(requests.get(image_path, stream=True).raw) elif os.path.exists(image_path): return Image.open(image_path) Loading Image Now, we need an image to diffuse into another image. You can use your photo. In this example, we are using an online image for convenience. Feel free to use your URL or images. # Loading an image URL img = load_image("https://img.freepik.com/free-photo/stacked-tomatoes_1353-262.jpg?w=740&t=st=1683821147~exp=1683821747~hmac=708f16371d1e158d76c8ea5e8b9790fb68dc75009750b8328e17c21f16d36468") # Displaying the Image img Creating Text Prompts Now we have a usable image. Let’s now show some image to imag