### Start Gradio Web Interface for Image Decomposition
Source: https://github.com/qwenlm/qwen-image-layered/blob/main/README.md
This bash script initiates a Gradio-based web interface for the Qwen-Image-Layered model. This interface allows users to upload an image, decompose it into RGBA layers, and export these layers into a PPTX file for further editing.
```bash
python src/app.py
```
--------------------------------
### Launch Gradio for RGBA Image Editing
Source: https://github.com/qwenlm/qwen-image-layered/blob/main/README.md
This bash script launches a Gradio-based web interface specifically designed for editing images with transparency using Qwen-Image-Edit. This tool is intended for post-decomposition editing of the RGBA layers generated by Qwen-Image-Layered.
```bash
python src/tool/edit_rgba_image.py
```
--------------------------------
### Initialize Qwen-Image-Layered Pipeline with Gradio
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
Initializes the Qwen-Image-Layered pipeline, moves it to the CUDA device with bfloat16 precision, and sets up a Gradio interface for image decomposition. The interface includes image input, advanced settings for generation parameters, and outputs for layered images and export files.
```python
import gradio as gr
from diffusers import QwenImageLayeredPipeline
import torch
# Initialize pipeline
pipeline = QwenImageLayeredPipeline.from_pretrained("Qwen/Qwen-Image-Layered")
pipeline = pipeline.to("cuda", torch.bfloat16)
with gr.Blocks() as demo:
with gr.Column():
gr.HTML('
')
with gr.Row():
with gr.Column(scale=1):
input_image = gr.Image(label="Input Image", image_mode="RGBA")
with gr.Accordion("Advanced Settings", open=False):
prompt = gr.Textbox(label="Prompt (Optional)", lines=3)
neg_prompt = gr.Textbox(label="Negative Prompt", value=" ", lines=3)
seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, value=0)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
true_guidance_scale = gr.Slider(label="Guidance scale", minimum=1.0, maximum=10.0, value=4.0)
num_inference_steps = gr.Slider(label="Inference steps", minimum=1, maximum=50, value=50)
layer = gr.Slider(label="Layers", minimum=2, maximum=10, value=4)
cfg_norm = gr.Checkbox(label="CFG normalization", value=True)
use_en_prompt = gr.Checkbox(label="Use English caption", value=True)
run_button = gr.Button("Decompose!", variant="primary")
with gr.Column(scale=2):
gallery = gr.Gallery(label="Layers", columns=4, rows=1, format="png")
with gr.Row():
export_file = gr.File(label="Download PPTX")
export_zip_file = gr.File(label="Download ZIP")
run_button.click(
fn=infer,
inputs=[input_image, seed, randomize_seed, prompt, neg_prompt,
true_guidance_scale, num_inference_steps, layer, cfg_norm, use_en_prompt],
outputs=[gallery, export_file, export_zip_file]
)
# Launch application
demo.launch(server_name="0.0.0.0", server_port=7869)
```
--------------------------------
### Initialize Qwen-Image-Edit Pipeline with Gradio
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
Initializes the Qwen-Image-Edit pipeline, moves it to the CUDA device with bfloat16 precision, and sets up a Gradio interface for editing RGBA layers. The interface allows users to upload an image, provide a text prompt for editing, and adjust advanced generation settings.
```python
import gradio as gr
from diffusers import QwenImageEditPlusPipeline
import torch
# Initialize pipeline
pipe = QwenImageEditPlusPipeline.from_pretrained("Qwen/Qwen-Image-Edit-2509", torch_dtype=torch.bfloat16).to("cuda")
with gr.Blocks() as demo:
with gr.Column():
gr.HTML('
')
gr.Markdown("Edit layers with transparent background using Qwen-Image-Edit")
with gr.Row():
with gr.Column():
input_image = gr.Image(label="Input Image", type="pil", image_mode="RGBA")
result = gr.Image(label="Result", type="pil")
with gr.Row():
prompt = gr.Text(label="Prompt", placeholder="describe the edit instruction")
run_button = gr.Button("Edit!", variant="primary")
with gr.Accordion("Advanced Settings", open=False):
seed = gr.Slider(label="Seed", minimum=0, maximum=2147483647, value=0)
randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
true_guidance_scale = gr.Slider(label="Guidance scale", minimum=1.0, maximum=10.0, value=4.0)
num_inference_steps = gr.Slider(label="Inference steps", minimum=1, maximum=50, value=50)
gr.on(
triggers=[run_button.click, prompt.submit],
fn=infer,
inputs=[input_image, prompt, seed, randomize_seed, true_guidance_scale, num_inference_steps],
outputs=[result, seed]
)
demo.launch()
```
--------------------------------
### Image Layer Decomposition with Diffusers
Source: https://github.com/qwenlm/qwen-image-layered/blob/main/README.md
This Python script demonstrates how to use the QwenImageLayeredPipeline from the diffusers library to decompose an input RGBA image into multiple layers. It requires the diffusers library and PyTorch. The script takes an image path, sets various inference parameters such as the number of layers, resolution, and CFG scale, and then saves the resulting decomposed layers as PNG files.
```python
from diffusers import QwenImageLayeredPipeline
import torch
from PIL import Image
pipeline = QwenImageLayeredPipeline.from_pretrained("Qwen/Qwen-Image-Layered")
pipeline = pipeline.to("cuda", torch.bfloat16)
pipeline.set_progress_bar_config(disable=None)
image = Image.open("asserts/test_images/1.png").convert("RGBA")
inputs = {
"image": image,
"generator": torch.Generator(device='cuda').manual_seed(777),
"true_cfg_scale": 4.0,
"negative_prompt": " ",
"num_inference_steps": 50,
"num_images_per_prompt": 1,
"layers": 4,
"resolution": 640, # Using different bucket (640, 1024) to determine the resolution. For this version, 640 is recommended
"cfg_normalize": True, # Whether enable cfg normalization.
"use_en_prompt": True, # Automatic caption language if user does not provide caption
}
with torch.inference_mode():
output = pipeline(**inputs)
output_image = output.images[0]
for i, image in enumerate(output_image):
image.save(f"{i}.png")
```
--------------------------------
### Decompose Image to Layers with QwenImageLayeredPipeline (Python)
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
This snippet demonstrates how to use the QwenImageLayeredPipeline from the Hugging Face diffusers library to decompose an input image into multiple RGBA layers. It loads the pipeline, configures decomposition parameters such as the number of layers and inference steps, and then saves each generated layer as a PNG file. Dependencies include `diffusers`, `torch`, and `PIL`.
```python
from diffusers import QwenImageLayeredPipeline
import torch
from PIL import Image
# Load the model pipeline
pipeline = QwenImageLayeredPipeline.from_pretrained("Qwen/Qwen-Image-Layered")
pipeline = pipeline.to("cuda", torch.bfloat16)
pipeline.set_progress_bar_config(disable=None)
# Load input image
image = Image.open("input.png").convert("RGBA")
# Configure decomposition parameters
inputs = {
"image": image,
"generator": torch.Generator(device='cuda').manual_seed(777),
"true_cfg_scale": 4.0,
"negative_prompt": " ",
"num_inference_steps": 50,
"num_images_per_prompt": 1,
"layers": 4,
"resolution": 640, # 640 or 1024, 640 recommended
"cfg_normalize": True,
"use_en_prompt": True,
}
# Generate layers
with torch.inference_mode():
output = pipeline(**inputs)
output_images = output.images[0]
# Save individual layers
for i, layer_image in enumerate(output_images):
layer_image.save(f"layer_{i}.png")
```
--------------------------------
### Convert Image List to PowerPoint (Python)
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
Converts a list of image files into a PowerPoint presentation. Each image is added as an overlaying shape on a slide, maintaining original dimensions. Dependencies include 'python-pptx' and 'Pillow'. It takes a list of image file paths as input and returns the path to the generated .pptx file.
```python
from pptx import Presentation
from PIL import Image
import tempfile
def imagelist_to_pptx(img_files):
# Get dimensions from first image
with Image.open(img_files[0]) as img:
img_width_px, img_height_px = img.size
# Convert pixels to EMU (English Metric Units) for PowerPoint
def px_to_emu(px, dpi=96):
inch = px / dpi
emu = inch * 914400
return int(emu)
# Create presentation with image dimensions
prs = Presentation()
prs.slide_width = px_to_emu(img_width_px)
prs.slide_height = px_to_emu(img_height_px)
# Add blank slide
slide = prs.slides.add_slide(prs.slide_layouts[6])
# Add each layer as a picture shape
left = top = 0
for img_path in img_files:
slide.shapes.add_picture(
img_path,
left,
top,
width=px_to_emu(img_width_px),
height=px_to_emu(img_height_px)
)
# Save to temporary file
with tempfile.NamedTemporaryFile(suffix=".pptx", delete=False) as tmp:
prs.save(tmp.name)
return tmp.name
# Example usage
layer_files = ["layer_0.png", "layer_1.png", "layer_2.png", "layer_3.png"]
pptx_path = imagelist_to_pptx(layer_files)
print(f"PowerPoint file saved to: {pptx_path}")
```
--------------------------------
### Edit RGBA Layers with Text Prompts (Python)
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
A pipeline for editing individual RGBA image layers using text prompts. It integrates background removal for transparent image editing, allowing precise layer modifications. Dependencies include 'diffusers', 'transformers', 'torchvision', and 'Pillow'. Inputs are an RGBA image and a text prompt; outputs are edited RGBA images.
```python
from diffusers import QwenImageEditPlusPipeline
from transformers import AutoModelForImageSegmentation
from torchvision import transforms
import torch
from PIL import Image
# Load models
dtype = torch.bfloat16
device = "cuda"
pipe = QwenImageEditPlusPipeline.from_pretrained(
"Qwen/Qwen-Image-Edit-2509",
torch_dtype=dtype
).to(device)
rmbg_model = AutoModelForImageSegmentation.from_pretrained(
'briaai/RMBG-2.0',
trust_remote_code=True
).eval().to(device)
rmbg_transforms = transforms.Compose([
transforms.Resize((1024, 1024)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# Load RGBA layer to edit
layer_image = Image.open("layer_1.png").convert("RGBA")
# Blend with green background for better editing
bg = Image.new("RGB", layer_image.size, (30, 215, 96)).convert("RGBA")
input_rgba = layer_image.convert("RGBA")
blended = Image.alpha_composite(bg, input_rgba).convert("RGB")
# Edit the layer
generator = torch.Generator(device=device).manual_seed(42)
edited_image = pipe(
blended,
prompt="change the color to red",
negative_prompt=" ",
num_inference_steps=50,
generator=generator,
true_cfg_scale=4.0,
num_images_per_prompt=1
).images[0]
# Remove background and restore transparency
input_images = rmbg_transforms(edited_image).unsqueeze(0).to(device)
with torch.no_grad():
preds = rmbg_model(input_images)[-1].sigmoid().cpu()
pred = preds[0].squeeze()
pred_pil = transforms.ToPILImage()(pred)
mask = pred_pil.resize(edited_image.size)
edited_image.putalpha(mask)
# Save edited layer
edited_image.save("layer_1_edited.png")
```
--------------------------------
### Inference Function for Gradio Web Interface (Python)
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
This Python function, `infer()`, serves as the core inference logic for the Gradio web interface of Qwen-Image-Layered. It handles image decomposition, parameter configuration (including seed randomization, prompts, guidance scale, and number of layers), and generates layered images. It also supports exporting results to PowerPoint (PPTX) and ZIP archive formats. Dependencies include `PIL`, `torch`, `numpy`, `random`, `tempfile`, and `zipfile`.
```python
from PIL import Image
import torch
import numpy as np
import random
import tempfile
import zipfile
MAX_SEED = np.iinfo(np.int32).max
def infer(input_image,
seed=777,
randomize_seed=False,
prompt=None,
neg_prompt=" ",
true_guidance_scale=4.0,
num_inference_steps=50,
layer=4,
cfg_norm=True,
use_en_prompt=True):
# Handle random seed
if randomize_seed:
seed = random.randint(0, MAX_SEED)
# Process input image (handles file path, PIL Image, or numpy array)
if isinstance(input_image, str):
pil_image = Image.open(input_image).convert("RGB").convert("RGBA")
elif isinstance(input_image, Image.Image):
pil_image = input_image.convert("RGB").convert("RGBA")
elif isinstance(input_image, np.ndarray):
pil_image = Image.fromarray(input_image).convert("RGB").convert("RGBA")
# Configure pipeline inputs
inputs = {
"image": pil_image,
"generator": torch.Generator(device='cuda').manual_seed(seed),
"true_cfg_scale": true_guidance_scale,
"prompt": prompt,
"negative_prompt": neg_prompt,
"num_inference_steps": num_inference_steps,
"num_images_per_prompt": 1,
"layers": layer,
"resolution": 640,
"cfg_normalize": cfg_norm,
"use_en_prompt": use_en_prompt,
}
# Generate layers
with torch.inference_mode():
output = pipeline(**inputs)
output_images = output.images[0]
# Save layers to temporary files
temp_files = []
for i, image in enumerate(output_images):
tmp = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
image.save(tmp.name)
temp_files.append(tmp.name)
# Generate PPTX export
pptx_path = imagelist_to_pptx(temp_files)
# Generate ZIP export
with tempfile.NamedTemporaryFile(suffix=".zip", delete=False) as tmp:
with zipfile.ZipFile(tmp.name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for i, img_path in enumerate(temp_files):
zipf.write(img_path, f"layer_{i+1}.png")
zip_path = tmp.name
return output_images, pptx_path, zip_path
```
--------------------------------
### Gradio Web Application for Layer Decomposition (Python)
Source: https://context7.com/qwenlm/qwen-image-layered/llms.txt
A complete web application interface for decomposing images into layers. It utilizes Gradio for a user-friendly experience, providing real-time previews and export functionality. This application integrates controls for various model parameters, enabling flexible image layer manipulation. Dependencies include 'gradio' and 'diffusers'.
```python
import gradio as gr
from diffusers import QwenImageLayeredPipeline
import torch
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.