Spaces:
Running
on
Zero
Running
on
Zero
Upload 4 files
Browse files- README.md +111 -5
- app.py +430 -22
- briarmbg.py +176 -0
- requirements.txt +12 -8
README.md
CHANGED
@@ -1,12 +1,118 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
colorFrom: blue
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
app_file: app.py
|
9 |
pinned: false
|
|
|
10 |
---
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
+
title: IC-Light Background Conditional Relighting Demo
|
3 |
+
emoji: ✨
|
4 |
colorFrom: blue
|
5 |
+
colorTo: purple
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 3.41.2
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
license: apache-2.0
|
11 |
---
|
12 |
|
13 |
+
# IC-Light Background Conditional Relighting Demo
|
14 |
+
|
15 |
+
这是一个基于IC-Light的背景条件重新打光演示应用,适用于Hugging Face Spaces。
|
16 |
+
|
17 |
+
## 功能特性
|
18 |
+
|
19 |
+
- **背景条件重新打光**: 使用前景图像和背景图像进行智能重新打光
|
20 |
+
- **多种光照模式**: 支持上传背景图像或选择预设光照方向(左、右、上、下、环境光)
|
21 |
+
- **自动背景移除**: 自动移除前景图像的背景
|
22 |
+
- **高分辨率支持**: 支持高分辨率图像生成和细化
|
23 |
+
- **实时预览**: 快速生成预览结果
|
24 |
+
|
25 |
+
## 使用方法
|
26 |
+
|
27 |
+
### 基本使用
|
28 |
+
|
29 |
+
1. **上传前景图像**: 上传包含人物或物体的图像
|
30 |
+
2. **选择背景源**:
|
31 |
+
- `Use Background Image`: 上传自定义背景图像
|
32 |
+
- `Left Light/Right Light/Top Light/Bottom Light`: 使用预设的方向性光照
|
33 |
+
- `Ambient`: 使用环境光照
|
34 |
+
3. **输入提示词**: 描述期望的光照效果,如 "beautiful woman, cinematic lighting"
|
35 |
+
4. **点击"✨ Relight Image"**: 生成重新打光的结果
|
36 |
+
|
37 |
+
### 高级设置
|
38 |
+
|
39 |
+
- **图像尺寸**: 调整输出图像的宽度和高度
|
40 |
+
- **生成步数**: 控制生成质量(更多步数 = 更高质量,但更慢)
|
41 |
+
- **CFG Scale**: 控制提示词的影响强度
|
42 |
+
- **高分辨率缩放**: 启用高分辨率细化
|
43 |
+
- **种子值**: 控制随机性,相同种子产生相同结果
|
44 |
+
|
45 |
+
## 技术实现
|
46 |
+
|
47 |
+
### 模型架构
|
48 |
+
|
49 |
+
- **基础模型**: Stable Diffusion 1.5 (realistic-vision-v51)
|
50 |
+
- **IC-Light权重**: iclight_sd15_fbc.safetensors (背景条件模型)
|
51 |
+
- **背景移除**: RMBG-1.4 或简化的边缘检测算法
|
52 |
+
|
53 |
+
### 核心功能
|
54 |
+
|
55 |
+
1. **UNet修改**: 将输入通道从4扩展到12,以支持前景和背景条件
|
56 |
+
2. **条件编码**: 将前景和背景图像编码为潜在空间条件
|
57 |
+
3. **提示词编码**: 支持长提示词的分块编码
|
58 |
+
4. **多阶段生成**: 支持低分辨率生成 + 高分辨率细化
|
59 |
+
|
60 |
+
## 依赖项
|
61 |
+
|
62 |
+
```
|
63 |
+
diffusers==0.27.2
|
64 |
+
transformers==4.36.2
|
65 |
+
torch
|
66 |
+
gradio==3.41.2
|
67 |
+
pillow==10.2.0
|
68 |
+
safetensors
|
69 |
+
numpy
|
70 |
+
scipy
|
71 |
+
```
|
72 |
+
|
73 |
+
## 部署到Hugging Face Spaces
|
74 |
+
|
75 |
+
1. 创建新的Gradio Space
|
76 |
+
2. 上传所有文件到Space
|
77 |
+
3. 确保requirements.txt包含所有依赖
|
78 |
+
4. Space会自动构建和部署
|
79 |
+
|
80 |
+
## 示例用法
|
81 |
+
|
82 |
+
### 人像重新打光
|
83 |
+
```
|
84 |
+
前景: 人像照片
|
85 |
+
背景: 选择"Left Light"
|
86 |
+
提示词: "beautiful woman, cinematic lighting"
|
87 |
+
```
|
88 |
+
|
89 |
+
### 产品摄影
|
90 |
+
```
|
91 |
+
前景: 产品图片
|
92 |
+
背景: 上传工作室背景
|
93 |
+
提示词: "product photography, professional lighting"
|
94 |
+
```
|
95 |
+
|
96 |
+
### 艺术创作
|
97 |
+
```
|
98 |
+
前景: 任意物体
|
99 |
+
背景: 选择"Top Light"
|
100 |
+
提示词: "dramatic lighting, artistic photography"
|
101 |
+
```
|
102 |
+
|
103 |
+
## 注意事项
|
104 |
+
|
105 |
+
- 首次运行会下载IC-Light模型文件(约2GB)
|
106 |
+
- GPU环境下运行效果最佳
|
107 |
+
- 背景移除功能可能需要手动调整
|
108 |
+
- 生成时间取决于图像尺寸和步数设置
|
109 |
+
|
110 |
+
## 许可证
|
111 |
+
|
112 |
+
本项目基于IC-Light官方实现,遵循相应的开源许可证。
|
113 |
+
|
114 |
+
## 相关链接
|
115 |
+
|
116 |
+
- [IC-Light官方仓库](https://github.com/lllyasviel/IC-Light)
|
117 |
+
- [IC-Light论文](https://openreview.net/forum?id=u1cQYxRI1H)
|
118 |
+
- [Hugging Face Spaces](https://huggingface.co/spaces)
|
app.py
CHANGED
@@ -1,28 +1,436 @@
|
|
1 |
-
|
|
|
2 |
import gradio as gr
|
3 |
-
|
4 |
import torch
|
5 |
-
|
6 |
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
)
|
26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
27 |
if __name__ == "__main__":
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import math
|
3 |
import gradio as gr
|
4 |
+
import numpy as np
|
5 |
import torch
|
6 |
+
import safetensors.torch as sf
|
7 |
|
8 |
+
from PIL import Image
|
9 |
+
from diffusers import StableDiffusionPipeline, StableDiffusionImg2ImgPipeline
|
10 |
+
from diffusers import AutoencoderKL, UNet2DConditionModel, DDIMScheduler, EulerAncestralDiscreteScheduler, DPMSolverMultistepScheduler
|
11 |
+
from diffusers.models.attention_processor import AttnProcessor2_0
|
12 |
+
from transformers import CLIPTextModel, CLIPTokenizer
|
13 |
+
from enum import Enum
|
14 |
+
from torch.hub import download_url_to_file
|
15 |
+
import torch.nn as nn
|
16 |
+
import torch.nn.functional as F
|
17 |
+
from huggingface_hub import PyTorchModelHubMixin
|
18 |
+
|
19 |
+
# Try to import RMBG, fallback to local implementation
|
20 |
+
try:
|
21 |
+
from transformers import pipeline
|
22 |
+
rmbg_pipeline = pipeline("image-segmentation", model="briaai/RMBG-1.4")
|
23 |
+
USE_RMBG_PIPELINE = True
|
24 |
+
except Exception as e:
|
25 |
+
print(f"Failed to load RMBG pipeline: {e}")
|
26 |
+
USE_RMBG_PIPELINE = False
|
27 |
+
try:
|
28 |
+
from briarmbg import BriaRMBG, simple_background_removal
|
29 |
+
except:
|
30 |
+
# Inline simple background removal
|
31 |
+
def simple_background_removal(image):
|
32 |
+
if isinstance(image, np.ndarray):
|
33 |
+
img = image
|
34 |
+
else:
|
35 |
+
img = np.array(image)
|
36 |
+
|
37 |
+
# Simple fallback - return full mask
|
38 |
+
gray = np.mean(img, axis=2)
|
39 |
+
mask = np.ones_like(gray)
|
40 |
+
return mask
|
41 |
+
|
42 |
+
# Model setup
|
43 |
+
sd15_name = 'stablediffusionapi/realistic-vision-v51'
|
44 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
45 |
+
|
46 |
+
print(f"Using device: {device}")
|
47 |
+
print("Loading models...")
|
48 |
+
|
49 |
+
# Initialize models
|
50 |
+
tokenizer = CLIPTokenizer.from_pretrained(sd15_name, subfolder="tokenizer")
|
51 |
+
text_encoder = CLIPTextModel.from_pretrained(sd15_name, subfolder="text_encoder")
|
52 |
+
vae = AutoencoderKL.from_pretrained(sd15_name, subfolder="vae")
|
53 |
+
unet = UNet2DConditionModel.from_pretrained(sd15_name, subfolder="unet")
|
54 |
+
|
55 |
+
# Modify UNet for IC-Light
|
56 |
+
with torch.no_grad():
|
57 |
+
new_conv_in = torch.nn.Conv2d(12, unet.conv_in.out_channels, unet.conv_in.kernel_size, unet.conv_in.stride, unet.conv_in.padding)
|
58 |
+
new_conv_in.weight.zero_()
|
59 |
+
new_conv_in.weight[:, :4, :, :].copy_(unet.conv_in.weight)
|
60 |
+
new_conv_in.bias = unet.conv_in.bias
|
61 |
+
unet.conv_in = new_conv_in
|
62 |
+
|
63 |
+
unet_original_forward = unet.forward
|
64 |
+
|
65 |
+
def hooked_unet_forward(sample, timestep, encoder_hidden_states, **kwargs):
|
66 |
+
c_concat = kwargs['cross_attention_kwargs']['concat_conds'].to(sample)
|
67 |
+
c_concat = torch.cat([c_concat] * (sample.shape[0] // c_concat.shape[0]), dim=0)
|
68 |
+
new_sample = torch.cat([sample, c_concat], dim=1)
|
69 |
+
kwargs['cross_attention_kwargs'] = {}
|
70 |
+
return unet_original_forward(new_sample, timestep, encoder_hidden_states, **kwargs)
|
71 |
+
|
72 |
+
unet.forward = hooked_unet_forward
|
73 |
+
|
74 |
+
# Load IC-Light weights
|
75 |
+
model_path = './iclight_sd15_fbc.safetensors'
|
76 |
+
if not os.path.exists(model_path):
|
77 |
+
print("Downloading IC-Light model...")
|
78 |
+
download_url_to_file(url='https://huggingface.co/lllyasviel/ic-light/resolve/main/iclight_sd15_fbc.safetensors', dst=model_path)
|
79 |
+
|
80 |
+
sd_offset = sf.load_file(model_path)
|
81 |
+
sd_origin = unet.state_dict()
|
82 |
+
sd_merged = {k: sd_origin[k] + sd_offset[k] for k in sd_origin.keys()}
|
83 |
+
unet.load_state_dict(sd_merged, strict=True)
|
84 |
+
del sd_offset, sd_origin, sd_merged
|
85 |
+
|
86 |
+
# Move models to device
|
87 |
+
text_encoder = text_encoder.to(device=device, dtype=torch.float16)
|
88 |
+
vae = vae.to(device=device, dtype=torch.bfloat16)
|
89 |
+
unet = unet.to(device=device, dtype=torch.float16)
|
90 |
+
|
91 |
+
# Set attention processors
|
92 |
+
unet.set_attn_processor(AttnProcessor2_0())
|
93 |
+
vae.set_attn_processor(AttnProcessor2_0())
|
94 |
+
|
95 |
+
# Scheduler
|
96 |
+
scheduler = DPMSolverMultistepScheduler(
|
97 |
+
num_train_timesteps=1000,
|
98 |
+
beta_start=0.00085,
|
99 |
+
beta_end=0.012,
|
100 |
+
algorithm_type="sde-dpmsolver++",
|
101 |
+
use_karras_sigmas=True,
|
102 |
+
steps_offset=1
|
103 |
+
)
|
104 |
+
|
105 |
+
# Pipelines
|
106 |
+
t2i_pipe = StableDiffusionPipeline(
|
107 |
+
vae=vae,
|
108 |
+
text_encoder=text_encoder,
|
109 |
+
tokenizer=tokenizer,
|
110 |
+
unet=unet,
|
111 |
+
scheduler=scheduler,
|
112 |
+
safety_checker=None,
|
113 |
+
requires_safety_checker=False,
|
114 |
+
feature_extractor=None,
|
115 |
+
image_encoder=None
|
116 |
+
)
|
117 |
+
|
118 |
+
i2i_pipe = StableDiffusionImg2ImgPipeline(
|
119 |
+
vae=vae,
|
120 |
+
text_encoder=text_encoder,
|
121 |
+
tokenizer=tokenizer,
|
122 |
+
unet=unet,
|
123 |
+
scheduler=scheduler,
|
124 |
+
safety_checker=None,
|
125 |
+
requires_safety_checker=False,
|
126 |
+
feature_extractor=None,
|
127 |
+
image_encoder=None
|
128 |
)
|
129 |
|
130 |
+
print("Models loaded successfully!")
|
131 |
+
|
132 |
+
@torch.inference_mode()
|
133 |
+
def encode_prompt_inner(txt: str):
|
134 |
+
max_length = tokenizer.model_max_length
|
135 |
+
chunk_length = tokenizer.model_max_length - 2
|
136 |
+
id_start = tokenizer.bos_token_id
|
137 |
+
id_end = tokenizer.eos_token_id
|
138 |
+
id_pad = id_end
|
139 |
+
|
140 |
+
def pad(x, p, i):
|
141 |
+
return x[:i] if len(x) >= i else x + [p] * (i - len(x))
|
142 |
+
|
143 |
+
tokens = tokenizer(txt, truncation=False, add_special_tokens=False)["input_ids"]
|
144 |
+
chunks = [[id_start] + tokens[i: i + chunk_length] + [id_end] for i in range(0, len(tokens), chunk_length)]
|
145 |
+
chunks = [pad(ck, id_pad, max_length) for ck in chunks]
|
146 |
+
|
147 |
+
token_ids = torch.tensor(chunks).to(device=device, dtype=torch.int64)
|
148 |
+
conds = text_encoder(token_ids).last_hidden_state
|
149 |
+
|
150 |
+
return conds
|
151 |
+
|
152 |
+
@torch.inference_mode()
|
153 |
+
def encode_prompt_pair(positive_prompt, negative_prompt):
|
154 |
+
c = encode_prompt_inner(positive_prompt)
|
155 |
+
uc = encode_prompt_inner(negative_prompt)
|
156 |
+
|
157 |
+
c_len = float(len(c))
|
158 |
+
uc_len = float(len(uc))
|
159 |
+
max_count = max(c_len, uc_len)
|
160 |
+
c_repeat = int(math.ceil(max_count / c_len))
|
161 |
+
uc_repeat = int(math.ceil(max_count / uc_len))
|
162 |
+
max_chunk = max(len(c), len(uc))
|
163 |
+
|
164 |
+
c = torch.cat([c] * c_repeat, dim=0)[:max_chunk]
|
165 |
+
uc = torch.cat([uc] * uc_repeat, dim=0)[:max_chunk]
|
166 |
+
|
167 |
+
c = torch.cat([p[None, ...] for p in c], dim=1)
|
168 |
+
uc = torch.cat([p[None, ...] for p in uc], dim=1)
|
169 |
+
|
170 |
+
return c, uc
|
171 |
+
|
172 |
+
@torch.inference_mode()
|
173 |
+
def pytorch2numpy(imgs, quant=True):
|
174 |
+
results = []
|
175 |
+
for x in imgs:
|
176 |
+
y = x.movedim(0, -1)
|
177 |
+
if quant:
|
178 |
+
y = y * 127.5 + 127.5
|
179 |
+
y = y.detach().float().cpu().numpy().clip(0, 255).astype(np.uint8)
|
180 |
+
else:
|
181 |
+
y = y * 0.5 + 0.5
|
182 |
+
y = y.detach().float().cpu().numpy().clip(0, 1).astype(np.float32)
|
183 |
+
results.append(y)
|
184 |
+
return results
|
185 |
+
|
186 |
+
@torch.inference_mode()
|
187 |
+
def numpy2pytorch(imgs):
|
188 |
+
h = torch.from_numpy(np.stack(imgs, axis=0)).float() / 127.0 - 1.0
|
189 |
+
h = h.movedim(-1, 1)
|
190 |
+
return h
|
191 |
+
|
192 |
+
def resize_and_center_crop(image, target_width, target_height):
|
193 |
+
pil_image = Image.fromarray(image)
|
194 |
+
original_width, original_height = pil_image.size
|
195 |
+
scale_factor = max(target_width / original_width, target_height / original_height)
|
196 |
+
new_width = int(original_width * scale_factor)
|
197 |
+
new_height = int(original_height * scale_factor)
|
198 |
+
pil_image = pil_image.resize((new_width, new_height), Image.LANCZOS)
|
199 |
+
left = (new_width - target_width) / 2
|
200 |
+
top = (new_height - target_height) / 2
|
201 |
+
right = (new_width + target_width) / 2
|
202 |
+
bottom = (new_height + target_height) / 2
|
203 |
+
pil_image = pil_image.crop((left, top, right, bottom))
|
204 |
+
return np.array(pil_image)
|
205 |
+
|
206 |
+
def resize_without_crop(image, target_width, target_height):
|
207 |
+
pil_image = Image.fromarray(image)
|
208 |
+
pil_image = pil_image.resize((target_width, target_height), Image.LANCZOS)
|
209 |
+
return np.array(pil_image)
|
210 |
+
|
211 |
+
@torch.inference_mode()
|
212 |
+
def run_rmbg(img, sigma=0.0):
|
213 |
+
# Simplified background removal
|
214 |
+
if USE_RMBG_PIPELINE:
|
215 |
+
# Using transformers pipeline
|
216 |
+
try:
|
217 |
+
result = rmbg_pipeline(Image.fromarray(img))
|
218 |
+
mask = np.array(result['mask'])
|
219 |
+
if len(mask.shape) == 3:
|
220 |
+
mask = mask[:, :, 0]
|
221 |
+
mask = mask.astype(np.float32) / 255.0
|
222 |
+
except Exception as e:
|
223 |
+
print(f"RMBG pipeline failed: {e}, using fallback")
|
224 |
+
mask = simple_background_removal(img)
|
225 |
+
else:
|
226 |
+
# Using simple background removal
|
227 |
+
mask = simple_background_removal(img)
|
228 |
+
|
229 |
+
# Apply sigma smoothing
|
230 |
+
if sigma > 0:
|
231 |
+
try:
|
232 |
+
from scipy import ndimage
|
233 |
+
mask = ndimage.gaussian_filter(mask, sigma=sigma)
|
234 |
+
except ImportError:
|
235 |
+
# Fallback if scipy is not available
|
236 |
+
pass
|
237 |
+
|
238 |
+
# Create RGBA output
|
239 |
+
result = np.dstack((img, (mask * 255).astype(np.uint8)))
|
240 |
+
return img, mask
|
241 |
+
|
242 |
+
class BGSource(Enum):
|
243 |
+
UPLOAD = "Use Background Image"
|
244 |
+
UPLOAD_FLIP = "Use Flipped Background Image"
|
245 |
+
LEFT = "Left Light"
|
246 |
+
RIGHT = "Right Light"
|
247 |
+
TOP = "Top Light"
|
248 |
+
BOTTOM = "Bottom Light"
|
249 |
+
GREY = "Ambient"
|
250 |
+
|
251 |
+
@torch.inference_mode()
|
252 |
+
def process(input_fg, input_bg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, bg_source):
|
253 |
+
bg_source = BGSource(bg_source)
|
254 |
+
|
255 |
+
if bg_source == BGSource.UPLOAD:
|
256 |
+
pass
|
257 |
+
elif bg_source == BGSource.UPLOAD_FLIP:
|
258 |
+
input_bg = np.fliplr(input_bg)
|
259 |
+
elif bg_source == BGSource.GREY:
|
260 |
+
input_bg = np.zeros(shape=(image_height, image_width, 3), dtype=np.uint8) + 64
|
261 |
+
elif bg_source == BGSource.LEFT:
|
262 |
+
gradient = np.linspace(224, 32, image_width)
|
263 |
+
image = np.tile(gradient, (image_height, 1))
|
264 |
+
input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8)
|
265 |
+
elif bg_source == BGSource.RIGHT:
|
266 |
+
gradient = np.linspace(32, 224, image_width)
|
267 |
+
image = np.tile(gradient, (image_height, 1))
|
268 |
+
input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8)
|
269 |
+
elif bg_source == BGSource.TOP:
|
270 |
+
gradient = np.linspace(224, 32, image_height)[:, None]
|
271 |
+
image = np.tile(gradient, (1, image_width))
|
272 |
+
input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8)
|
273 |
+
elif bg_source == BGSource.BOTTOM:
|
274 |
+
gradient = np.linspace(32, 224, image_height)[:, None]
|
275 |
+
image = np.tile(gradient, (1, image_width))
|
276 |
+
input_bg = np.stack((image,) * 3, axis=-1).astype(np.uint8)
|
277 |
+
else:
|
278 |
+
raise ValueError('Wrong background source!')
|
279 |
+
|
280 |
+
rng = torch.Generator(device=device).manual_seed(seed)
|
281 |
+
|
282 |
+
fg = resize_and_center_crop(input_fg, image_width, image_height)
|
283 |
+
bg = resize_and_center_crop(input_bg, image_width, image_height)
|
284 |
+
concat_conds = numpy2pytorch([fg, bg]).to(device=vae.device, dtype=vae.dtype)
|
285 |
+
concat_conds = vae.encode(concat_conds).latent_dist.mode() * vae.config.scaling_factor
|
286 |
+
concat_conds = torch.cat([c[None, ...] for c in concat_conds], dim=1)
|
287 |
+
|
288 |
+
conds, unconds = encode_prompt_pair(positive_prompt=prompt + ', ' + a_prompt, negative_prompt=n_prompt)
|
289 |
+
|
290 |
+
latents = t2i_pipe(
|
291 |
+
prompt_embeds=conds,
|
292 |
+
negative_prompt_embeds=unconds,
|
293 |
+
width=image_width,
|
294 |
+
height=image_height,
|
295 |
+
num_inference_steps=steps,
|
296 |
+
num_images_per_prompt=num_samples,
|
297 |
+
generator=rng,
|
298 |
+
output_type='latent',
|
299 |
+
guidance_scale=cfg,
|
300 |
+
cross_attention_kwargs={'concat_conds': concat_conds},
|
301 |
+
).images.to(vae.dtype) / vae.config.scaling_factor
|
302 |
+
|
303 |
+
pixels = vae.decode(latents).sample
|
304 |
+
pixels = pytorch2numpy(pixels)
|
305 |
+
|
306 |
+
if highres_scale > 1.0:
|
307 |
+
pixels = [resize_without_crop(
|
308 |
+
image=p,
|
309 |
+
target_width=int(round(image_width * highres_scale / 64.0) * 64),
|
310 |
+
target_height=int(round(image_height * highres_scale / 64.0) * 64))
|
311 |
+
for p in pixels]
|
312 |
+
|
313 |
+
pixels = numpy2pytorch(pixels).to(device=vae.device, dtype=vae.dtype)
|
314 |
+
latents = vae.encode(pixels).latent_dist.mode() * vae.config.scaling_factor
|
315 |
+
latents = latents.to(device=unet.device, dtype=unet.dtype)
|
316 |
+
|
317 |
+
image_height, image_width = latents.shape[2] * 8, latents.shape[3] * 8
|
318 |
+
fg = resize_and_center_crop(input_fg, image_width, image_height)
|
319 |
+
bg = resize_and_center_crop(input_bg, image_width, image_height)
|
320 |
+
concat_conds = numpy2pytorch([fg, bg]).to(device=vae.device, dtype=vae.dtype)
|
321 |
+
concat_conds = vae.encode(concat_conds).latent_dist.mode() * vae.config.scaling_factor
|
322 |
+
concat_conds = torch.cat([c[None, ...] for c in concat_conds], dim=1)
|
323 |
+
|
324 |
+
latents = i2i_pipe(
|
325 |
+
image=latents,
|
326 |
+
strength=highres_denoise,
|
327 |
+
prompt_embeds=conds,
|
328 |
+
negative_prompt_embeds=unconds,
|
329 |
+
width=image_width,
|
330 |
+
height=image_height,
|
331 |
+
num_inference_steps=int(round(steps / highres_denoise)),
|
332 |
+
num_images_per_prompt=num_samples,
|
333 |
+
generator=rng,
|
334 |
+
output_type='latent',
|
335 |
+
guidance_scale=cfg,
|
336 |
+
cross_attention_kwargs={'concat_conds': concat_conds},
|
337 |
+
).images.to(vae.dtype) / vae.config.scaling_factor
|
338 |
+
|
339 |
+
pixels = vae.decode(latents).sample
|
340 |
+
pixels = pytorch2numpy(pixels, quant=False)
|
341 |
+
|
342 |
+
return pixels, [fg, bg]
|
343 |
+
|
344 |
+
@torch.inference_mode()
|
345 |
+
def process_relight(input_fg, input_bg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, bg_source):
|
346 |
+
input_fg, matting = run_rmbg(input_fg)
|
347 |
+
results, extra_images = process(input_fg, input_bg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, bg_source)
|
348 |
+
results = [(x * 255.0).clip(0, 255).astype(np.uint8) for x in results]
|
349 |
+
return results + extra_images
|
350 |
+
|
351 |
+
# Quick prompts for easy testing
|
352 |
+
quick_prompts = [
|
353 |
+
'beautiful woman, cinematic lighting',
|
354 |
+
'handsome man, cinematic lighting',
|
355 |
+
'beautiful woman, natural lighting',
|
356 |
+
'handsome man, natural lighting',
|
357 |
+
'beautiful woman, neo punk lighting, cyberpunk',
|
358 |
+
'handsome man, neo punk lighting, cyberpunk',
|
359 |
+
]
|
360 |
+
quick_prompts = [[x] for x in quick_prompts]
|
361 |
+
|
362 |
+
# Gradio Interface
|
363 |
+
def create_demo():
|
364 |
+
with gr.Blocks(title="IC-Light Background Conditional Relighting") as demo:
|
365 |
+
gr.Markdown("## IC-Light: Relighting with Foreground and Background Condition")
|
366 |
+
gr.Markdown("Upload a foreground image and background image (or choose lighting direction) to perform relighting.")
|
367 |
+
|
368 |
+
with gr.Row():
|
369 |
+
with gr.Column():
|
370 |
+
with gr.Row():
|
371 |
+
input_fg = gr.Image(source='upload', type="numpy", label="Foreground Image", height=400)
|
372 |
+
input_bg = gr.Image(source='upload', type="numpy", label="Background Image", height=400)
|
373 |
+
|
374 |
+
prompt = gr.Textbox(label="Prompt", value="beautiful woman, cinematic lighting")
|
375 |
+
bg_source = gr.Radio(
|
376 |
+
choices=[e.value for e in BGSource],
|
377 |
+
value=BGSource.UPLOAD.value,
|
378 |
+
label="Background Source"
|
379 |
+
)
|
380 |
+
|
381 |
+
example_prompts = gr.Dataset(
|
382 |
+
samples=quick_prompts,
|
383 |
+
label='Quick Prompts',
|
384 |
+
components=[prompt]
|
385 |
+
)
|
386 |
+
|
387 |
+
relight_button = gr.Button(value="✨ Relight Image", variant="primary")
|
388 |
+
|
389 |
+
with gr.Accordion("Advanced Settings", open=False):
|
390 |
+
with gr.Row():
|
391 |
+
num_samples = gr.Slider(label="Number of Images", minimum=1, maximum=4, value=1, step=1)
|
392 |
+
seed = gr.Number(label="Seed", value=12345, precision=0)
|
393 |
+
with gr.Row():
|
394 |
+
image_width = gr.Slider(label="Width", minimum=256, maximum=1024, value=512, step=64)
|
395 |
+
image_height = gr.Slider(label="Height", minimum=256, maximum=1024, value=640, step=64)
|
396 |
+
with gr.Row():
|
397 |
+
steps = gr.Slider(label="Steps", minimum=1, maximum=50, value=20, step=1)
|
398 |
+
cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=20.0, value=7.0, step=0.1)
|
399 |
+
with gr.Row():
|
400 |
+
highres_scale = gr.Slider(label="Highres Scale", minimum=1.0, maximum=2.0, value=1.5, step=0.1)
|
401 |
+
highres_denoise = gr.Slider(label="Highres Denoise", minimum=0.1, maximum=0.9, value=0.5, step=0.1)
|
402 |
+
|
403 |
+
a_prompt = gr.Textbox(label="Additional Prompt", value='best quality')
|
404 |
+
n_prompt = gr.Textbox(label="Negative Prompt", value='lowres, bad anatomy, bad hands, cropped, worst quality')
|
405 |
+
|
406 |
+
with gr.Column():
|
407 |
+
result_gallery = gr.Gallery(label='Results', height=600, object_fit='contain')
|
408 |
+
|
409 |
+
# Event handlers
|
410 |
+
inputs = [input_fg, input_bg, prompt, image_width, image_height, num_samples, seed, steps, a_prompt, n_prompt, cfg, highres_scale, highres_denoise, bg_source]
|
411 |
+
relight_button.click(fn=process_relight, inputs=inputs, outputs=[result_gallery])
|
412 |
+
example_prompts.click(lambda x: x[0], inputs=example_prompts, outputs=prompt, show_progress=False, queue=False)
|
413 |
+
|
414 |
+
# Examples
|
415 |
+
gr.Examples(
|
416 |
+
examples=[
|
417 |
+
["examples/person1.jpg", "examples/bg1.jpg", "beautiful woman, cinematic lighting", "Use Background Image"],
|
418 |
+
["examples/person2.jpg", None, "handsome man, dramatic lighting", "Left Light"],
|
419 |
+
],
|
420 |
+
inputs=[input_fg, input_bg, prompt, bg_source],
|
421 |
+
outputs=[result_gallery],
|
422 |
+
fn=process_relight,
|
423 |
+
cache_examples=False,
|
424 |
+
)
|
425 |
+
|
426 |
+
return demo
|
427 |
+
|
428 |
if __name__ == "__main__":
|
429 |
+
demo = create_demo()
|
430 |
+
demo.queue(max_size=20)
|
431 |
+
demo.launch(
|
432 |
+
server_name='0.0.0.0',
|
433 |
+
server_port=7860,
|
434 |
+
show_error=True,
|
435 |
+
share=False
|
436 |
+
)
|
briarmbg.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
import torch.nn.functional as F
|
4 |
+
from huggingface_hub import PyTorchModelHubMixin
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
class REBNCONV(nn.Module):
|
9 |
+
def __init__(self, in_ch=3, out_ch=3, dirate=1, stride=1):
|
10 |
+
super(REBNCONV, self).__init__()
|
11 |
+
self.conv_s1 = nn.Conv2d(
|
12 |
+
in_ch, out_ch, 3, padding=1 * dirate, dilation=1 * dirate, stride=stride
|
13 |
+
)
|
14 |
+
self.bn_s1 = nn.BatchNorm2d(out_ch)
|
15 |
+
self.relu_s1 = nn.ReLU(inplace=True)
|
16 |
+
|
17 |
+
def forward(self, x):
|
18 |
+
hx = x
|
19 |
+
xout = self.relu_s1(self.bn_s1(self.conv_s1(hx)))
|
20 |
+
return xout
|
21 |
+
|
22 |
+
def _upsample_like(src, tar):
|
23 |
+
src = F.interpolate(src, size=tar.shape[2:], mode="bilinear")
|
24 |
+
return src
|
25 |
+
|
26 |
+
class RSU7(nn.Module):
|
27 |
+
def __init__(self, in_ch=3, mid_ch=12, out_ch=3, img_size=512):
|
28 |
+
super(RSU7, self).__init__()
|
29 |
+
self.in_ch = in_ch
|
30 |
+
self.mid_ch = mid_ch
|
31 |
+
self.out_ch = out_ch
|
32 |
+
|
33 |
+
self.rebnconvin = REBNCONV(in_ch, out_ch, dirate=1)
|
34 |
+
self.rebnconv1 = REBNCONV(out_ch, mid_ch, dirate=1)
|
35 |
+
self.pool1 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
|
36 |
+
self.rebnconv2 = REBNCONV(mid_ch, mid_ch, dirate=1)
|
37 |
+
self.pool2 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
|
38 |
+
self.rebnconv3 = REBNCONV(mid_ch, mid_ch, dirate=1)
|
39 |
+
self.pool3 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
|
40 |
+
self.rebnconv4 = REBNCONV(mid_ch, mid_ch, dirate=1)
|
41 |
+
self.pool4 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
|
42 |
+
self.rebnconv5 = REBNCONV(mid_ch, mid_ch, dirate=1)
|
43 |
+
self.pool5 = nn.MaxPool2d(2, stride=2, ceil_mode=True)
|
44 |
+
self.rebnconv6 = REBNCONV(mid_ch, mid_ch, dirate=1)
|
45 |
+
self.rebnconv7 = REBNCONV(mid_ch, mid_ch, dirate=2)
|
46 |
+
self.rebnconv6d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
|
47 |
+
self.rebnconv5d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
|
48 |
+
self.rebnconv4d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
|
49 |
+
self.rebnconv3d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
|
50 |
+
self.rebnconv2d = REBNCONV(mid_ch * 2, mid_ch, dirate=1)
|
51 |
+
self.rebnconv1d = REBNCONV(mid_ch * 2, out_ch, dirate=1)
|
52 |
+
|
53 |
+
def forward(self, x):
|
54 |
+
hx = x
|
55 |
+
hxin = self.rebnconvin(hx)
|
56 |
+
hx1 = self.rebnconv1(hxin)
|
57 |
+
hx = self.pool1(hx1)
|
58 |
+
hx2 = self.rebnconv2(hx)
|
59 |
+
hx = self.pool2(hx2)
|
60 |
+
hx3 = self.rebnconv3(hx)
|
61 |
+
hx = self.pool3(hx3)
|
62 |
+
hx4 = self.rebnconv4(hx)
|
63 |
+
hx = self.pool4(hx4)
|
64 |
+
hx5 = self.rebnconv5(hx)
|
65 |
+
hx = self.pool5(hx5)
|
66 |
+
hx6 = self.rebnconv6(hx)
|
67 |
+
hx7 = self.rebnconv7(hx6)
|
68 |
+
hx6d = self.rebnconv6d(torch.cat((hx7, hx6), 1))
|
69 |
+
hx6dup = _upsample_like(hx6d, hx5)
|
70 |
+
hx5d = self.rebnconv5d(torch.cat((hx6dup, hx5), 1))
|
71 |
+
hx5dup = _upsample_like(hx5d, hx4)
|
72 |
+
hx4d = self.rebnconv4d(torch.cat((hx5dup, hx4), 1))
|
73 |
+
hx4dup = _upsample_like(hx4d, hx3)
|
74 |
+
hx3d = self.rebnconv3d(torch.cat((hx4dup, hx3), 1))
|
75 |
+
hx3dup = _upsample_like(hx3d, hx2)
|
76 |
+
hx2d = self.rebnconv2d(torch.cat((hx3dup, hx2), 1))
|
77 |
+
hx2dup = _upsample_like(hx2d, hx1)
|
78 |
+
hx1d = self.rebnconv1d(torch.cat((hx2dup, hx1), 1))
|
79 |
+
return hx1d + hxin
|
80 |
+
|
81 |
+
class BriaRMBG(nn.Module, PyTorchModelHubMixin):
|
82 |
+
def __init__(self, config: dict = {"in_ch": 3, "out_ch": 1}):
|
83 |
+
super(BriaRMBG, self).__init__()
|
84 |
+
self.config = config
|
85 |
+
# Simplified architecture for fallback
|
86 |
+
self.stage1 = RSU7(3, 32, 64)
|
87 |
+
self.stage2 = RSU7(64, 32, 128)
|
88 |
+
self.stage3 = RSU7(128, 64, 256)
|
89 |
+
self.stage4 = RSU7(256, 128, 512)
|
90 |
+
|
91 |
+
# Decoder
|
92 |
+
self.stage4d = RSU7(1024, 128, 256)
|
93 |
+
self.stage3d = RSU7(512, 64, 128)
|
94 |
+
self.stage2d = RSU7(256, 32, 64)
|
95 |
+
self.stage1d = RSU7(128, 16, 64)
|
96 |
+
|
97 |
+
self.side1 = nn.Conv2d(64, 1, 3, padding=1)
|
98 |
+
self.side2 = nn.Conv2d(64, 1, 3, padding=1)
|
99 |
+
self.side3 = nn.Conv2d(128, 1, 3, padding=1)
|
100 |
+
self.side4 = nn.Conv2d(256, 1, 3, padding=1)
|
101 |
+
self.side5 = nn.Conv2d(512, 1, 3, padding=1)
|
102 |
+
self.side6 = nn.Conv2d(256, 1, 3, padding=1)
|
103 |
+
|
104 |
+
self.outconv = nn.Conv2d(6, 1, 1)
|
105 |
+
|
106 |
+
def forward(self, x):
|
107 |
+
hx = x
|
108 |
+
|
109 |
+
# Encoder
|
110 |
+
hx1 = self.stage1(hx)
|
111 |
+
hx = F.max_pool2d(hx1, 2, stride=2, ceil_mode=True)
|
112 |
+
|
113 |
+
hx2 = self.stage2(hx)
|
114 |
+
hx = F.max_pool2d(hx2, 2, stride=2, ceil_mode=True)
|
115 |
+
|
116 |
+
hx3 = self.stage3(hx)
|
117 |
+
hx = F.max_pool2d(hx3, 2, stride=2, ceil_mode=True)
|
118 |
+
|
119 |
+
hx4 = self.stage4(hx)
|
120 |
+
hx = F.max_pool2d(hx4, 2, stride=2, ceil_mode=True)
|
121 |
+
|
122 |
+
# Decoder
|
123 |
+
hx4d = self.stage4d(torch.cat((hx, hx4), 1))
|
124 |
+
hx4dup = _upsample_like(hx4d, hx3)
|
125 |
+
|
126 |
+
hx3d = self.stage3d(torch.cat((hx4dup, hx3), 1))
|
127 |
+
hx3dup = _upsample_like(hx3d, hx2)
|
128 |
+
|
129 |
+
hx2d = self.stage2d(torch.cat((hx3dup, hx2), 1))
|
130 |
+
hx2dup = _upsample_like(hx2d, hx1)
|
131 |
+
|
132 |
+
hx1d = self.stage1d(torch.cat((hx2dup, hx1), 1))
|
133 |
+
|
134 |
+
# Side outputs
|
135 |
+
side1 = self.side1(hx1d)
|
136 |
+
side2 = _upsample_like(self.side2(hx2d), side1)
|
137 |
+
side3 = _upsample_like(self.side3(hx3d), side1)
|
138 |
+
side4 = _upsample_like(self.side4(hx4d), side1)
|
139 |
+
side5 = _upsample_like(self.side5(hx), side1)
|
140 |
+
side6 = _upsample_like(self.side6(hx4d), side1)
|
141 |
+
|
142 |
+
# Fusion
|
143 |
+
out = self.outconv(torch.cat((side1, side2, side3, side4, side5, side6), 1))
|
144 |
+
|
145 |
+
return torch.sigmoid(out)
|
146 |
+
|
147 |
+
def simple_background_removal(image):
|
148 |
+
"""
|
149 |
+
Simple fallback background removal using edge detection and thresholding
|
150 |
+
"""
|
151 |
+
if isinstance(image, np.ndarray):
|
152 |
+
img = image
|
153 |
+
else:
|
154 |
+
img = np.array(image)
|
155 |
+
|
156 |
+
# Convert to grayscale
|
157 |
+
gray = np.mean(img, axis=2)
|
158 |
+
|
159 |
+
# Simple edge detection
|
160 |
+
from scipy import ndimage
|
161 |
+
edges = ndimage.sobel(gray)
|
162 |
+
|
163 |
+
# Create a simple mask based on intensity
|
164 |
+
mask = np.ones_like(gray)
|
165 |
+
|
166 |
+
# Simple thresholding - assume foreground is in center and has more edges
|
167 |
+
h, w = gray.shape
|
168 |
+
center_mask = np.zeros_like(gray)
|
169 |
+
center_mask[h//4:3*h//4, w//4:3*w//4] = 1
|
170 |
+
|
171 |
+
# Combine edge information with center bias
|
172 |
+
mask = (edges > np.percentile(edges, 70)) * center_mask
|
173 |
+
mask = ndimage.binary_fill_holes(mask)
|
174 |
+
mask = ndimage.gaussian_filter(mask.astype(float), sigma=2)
|
175 |
+
|
176 |
+
return mask
|
requirements.txt
CHANGED
@@ -1,12 +1,16 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
torch
|
4 |
-
Pillow
|
5 |
-
opencv-python
|
6 |
-
einops
|
7 |
-
transformers==4.36.2
|
8 |
diffusers==0.27.2
|
|
|
|
|
|
|
9 |
safetensors
|
|
|
|
|
10 |
peft
|
|
|
11 |
protobuf==3.20
|
12 |
-
|
|
|
|
|
|
|
|
1 |
+
torch>=2.0.0
|
2 |
+
torchvision
|
|
|
|
|
|
|
|
|
|
|
3 |
diffusers==0.27.2
|
4 |
+
transformers==4.36.2
|
5 |
+
accelerate
|
6 |
+
opencv-python-headless
|
7 |
safetensors
|
8 |
+
pillow==10.2.0
|
9 |
+
einops
|
10 |
peft
|
11 |
+
gradio==3.41.2
|
12 |
protobuf==3.20
|
13 |
+
numpy
|
14 |
+
scipy
|
15 |
+
huggingface_hub
|
16 |
+
xformers
|