lzyhha commited on
Commit
319886d
·
1 Parent(s): 25274d4
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. .gitignore +14 -0
  3. INSTALL.md +29 -0
  4. app.py +491 -0
  5. data/__init__.py +1 -0
  6. data/prefix_instruction.py +1086 -0
  7. degradation_toolkit/__init__.py +0 -0
  8. degradation_toolkit/add_degradation_various.py +401 -0
  9. degradation_toolkit/frost/frost1.png +3 -0
  10. degradation_toolkit/frost/frost2.png +3 -0
  11. degradation_toolkit/frost/frost3.png +3 -0
  12. degradation_toolkit/frost/frost4.jpg +3 -0
  13. degradation_toolkit/frost/frost5.jpg +3 -0
  14. degradation_toolkit/frost/frost6.jpg +3 -0
  15. degradation_toolkit/image_operators.py +420 -0
  16. degradation_toolkit/x_distortion/__init__.py +120 -0
  17. degradation_toolkit/x_distortion/blur.py +155 -0
  18. degradation_toolkit/x_distortion/brightness.py +150 -0
  19. degradation_toolkit/x_distortion/compression.py +78 -0
  20. degradation_toolkit/x_distortion/contrast.py +74 -0
  21. degradation_toolkit/x_distortion/helper.py +171 -0
  22. degradation_toolkit/x_distortion/noise.py +117 -0
  23. degradation_toolkit/x_distortion/oversharpen.py +31 -0
  24. degradation_toolkit/x_distortion/pixelate.py +21 -0
  25. degradation_toolkit/x_distortion/quantization.py +68 -0
  26. degradation_toolkit/x_distortion/saturate.py +75 -0
  27. degradation_toolkit/x_distortion/spatter.py +74 -0
  28. degradation_utils.py +232 -0
  29. demo_tasks/__init__.py +13 -0
  30. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9.jpg +3 -0
  31. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_ben2-background-removal.jpg +3 -0
  32. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_canny_100_200_512.jpg +3 -0
  33. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_depth-anything-v2_Large.jpg +3 -0
  34. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_dsine_normal_map.jpg +3 -0
  35. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_hed_512.jpg +3 -0
  36. demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_sam2_mask.jpg +3 -0
  37. demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3.jpg +3 -0
  38. demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0.jpg +3 -0
  39. demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0_style.jpg +3 -0
  40. demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_qwen2_5_mask.jpg +3 -0
  41. demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462.jpg +3 -0
  42. demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0.jpg +3 -0
  43. demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0_style.jpg +3 -0
  44. demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_qwen2_5_mask.jpg +3 -0
  45. demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3.jpg +3 -0
  46. demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_canny_100_200_512.jpg +3 -0
  47. demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_depth-anything-v2_Large.jpg +3 -0
  48. demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_dsine_normal_map.jpg +3 -0
  49. demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_hed_512.jpg +3 -0
  50. demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_openpose_fullres_nohand.jpg +3 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.jpg filter=lfs diff=lfs merge=lfs -text
37
+ *.png filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ batch*
2
+ phoe*
3
+ *gt*
4
+ *__pycache__*
5
+ *ocr*
6
+ *.pyc
7
+ *.pyo
8
+ *.pyd
9
+ *.txt
10
+ *.json
11
+ .gradio
12
+ output
13
+ gradio_cache
14
+ __pycache__
INSTALL.md ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Installation
2
+
3
+ Downloading VisualCloze repo from github:
4
+
5
+ ```bash
6
+ git clone xxx
7
+ ```
8
+
9
+ ### 1. Create a conda environment and install PyTorch
10
+
11
+ Note: You may want to adjust the CUDA version [according to your driver version](https://docs.nvidia.com/deploy/cuda-compatibility/#default-to-minor-version).
12
+
13
+ ```bash
14
+ conda create -n visualcloze -y
15
+ conda activate visualcloze
16
+ conda install python=3.11 pytorch==2.1.0 torchvision==0.16.0 torchaudio==2.1.0 pytorch-cuda=12.1 -c pytorch -c nvidia -y
17
+ ```
18
+
19
+ ### 2. Install dependencies
20
+
21
+ ```bash
22
+ pip install -r requirements.txt
23
+ ```
24
+
25
+ ### 3. Install flash-attn
26
+
27
+ ```bash
28
+ pip install flash-attn --no-build-isolation
29
+ ```
app.py ADDED
@@ -0,0 +1,491 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gradio as gr
3
+ import demo_tasks
4
+ from functools import partial
5
+ from data.prefix_instruction import get_layout_instruction
6
+ from visualcloze import VisualClozeModel
7
+
8
+
9
+ max_grid_h = 5
10
+ max_grid_w = 5
11
+ default_grid_h = 2
12
+ default_grid_w = 3
13
+ default_upsampling_noise = 0.4
14
+ default_steps = 30
15
+
16
+ GUIDANCE = """
17
+
18
+ ## 📋 Quick Start Guide:
19
+ 1. Adjust **Number of In-context Examples**, 0 disables in-context learning.
20
+ 2. Set **Task Columns**, the number of images involved in a task.
21
+ 3. Upload Images. For in-context examples, upload all images. For the current query, upload images exclude the target.
22
+ 4. Click **Generate** to create the images.
23
+ 5. Parameters can be fine-tuned under **Advanced Options**.
24
+
25
+ <div style='font-size: 24px; font-weight: bold; color: #FF9999;'>Click the task button in the right bottom to acquire examples of various tasks.</div>
26
+
27
+ """
28
+
29
+ CITATION = r"""
30
+ If you find VisualCloze is helpful, please consider to star ⭐ the <a href='https://github.com/lzyhha/VisualCloze' target='_blank'>Github Repo</a>. Thanks!
31
+ ---
32
+ 📝 **Citation**
33
+ <br>
34
+ If our work is useful for your research, please consider citing:
35
+ ```bibtex
36
+ @article{li2025visualcloze,
37
+ title={VisualCloze : A Universal Image Generation Framework via Visual In-Context Learning},
38
+ author={Li, Zhong-Yu and Du, ruoyi and Yan, Juncheng and Zhuo, Le and Li, Zhen and Gao, Peng and Ma, Zhanyu and Cheng, Ming-Ming},
39
+ booktitle={arXiv preprint arxiv:},
40
+ year={2025}
41
+ }
42
+ ```
43
+ 📋 **License**
44
+ <br>
45
+ This project is licensed under xxx.
46
+ """
47
+
48
+ INTRODUCTION = """
49
+ ## 📋 Introduction:
50
+ VisualCloze utilizes in-context examples as visual demonstrations to clarify the desired task.
51
+
52
+ Through in-context learning, VisualCloze can:
53
+ 1. support various in-domain tasks,
54
+ 2. generalize to **unseen tasks** through in-context learning,
55
+ 3. unify multiple tasks into one step and generate not only the target image but also the intermediate results,
56
+ 4. support reverse generation, i.e., reverse-engineering a set of conditions from a target.
57
+
58
+ """
59
+
60
+ def create_demo(model):
61
+ with gr.Blocks(title="VisualCloze Demo") as demo:
62
+ gr.Markdown("# VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning")
63
+
64
+ gr.HTML("""
65
+ <div style="display:flex;column-gap:4px;">
66
+ <a href="xxx">
67
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue'>
68
+ </a>
69
+ <a href="xxx">
70
+ <img src='https://img.shields.io/badge/ArXiv-Paper-red'>
71
+ </a>
72
+ <a href="xxx">
73
+ <img src='https://img.shields.io/badge/VisualCloze%20checkpoint-HF%20Model-green?logoColor=violet&label=%F0%9F%A4%97%20Checkpoint'>
74
+ </a>
75
+ <a href="xxx">
76
+ <img src='https://img.shields.io/badge/VisualCloze%20datasets-HF%20Dataset-6B88E3?logoColor=violet&label=%F0%9F%A4%97%20Graph200k%20Dataset'>
77
+ </a>
78
+ </div>
79
+ """)
80
+
81
+ with gr.Row():
82
+ with gr.Column(scale=2):
83
+ gr.Markdown(INTRODUCTION)
84
+ with gr.Column(scale=2):
85
+ gr.Markdown(GUIDANCE)
86
+
87
+ # gr.Markdown("<div style='font-size: 24px; font-weight: bold; color: #FF9999;'>" +
88
+ # "Note: Click the task button in the right bottom to acquire examples of tasks." +
89
+ # "</div>", )
90
+
91
+ # Pre-create all possible image components
92
+ all_image_inputs = []
93
+ rows = []
94
+ row_texts = []
95
+ with gr.Row():
96
+
97
+ # 左侧列:图像网格和提示输入
98
+ with gr.Column(scale=2):
99
+ # 图像网格部分
100
+ for i in range(max_grid_h):
101
+ # Add row label before each row
102
+ row_texts.append(gr.Markdown(
103
+ "<div style='font-size: 24px; font-weight: bold;'>" +
104
+ ("query" if i == default_grid_h - 1 else f"In-context Example {i + 1}") +
105
+ "</div>",
106
+ elem_id=f"row_text_{i}",
107
+ visible=i < default_grid_h
108
+ ))
109
+ with gr.Row(visible=i < default_grid_h, elem_id=f"row_{i}") as row:
110
+ rows.append(row)
111
+ for j in range(max_grid_w):
112
+ img_input = gr.Image(
113
+ label=f"In-context Example {i + 1}/{j + 1}" if i != default_grid_h - 1 else f"Query {j + 1}",
114
+ type="pil",
115
+ visible= i < default_grid_h and j < default_grid_w,
116
+ interactive=True,
117
+ elem_id=f"img_{i}_{j}"
118
+ )
119
+ all_image_inputs.append(img_input)
120
+
121
+ # 提示输入部分
122
+ layout_prompt = gr.Textbox(
123
+ label="Layout Description (Auto-filled, Read-only)",
124
+ placeholder="Layout description will be automatically filled based on grid size...",
125
+ value=get_layout_instruction(default_grid_w, default_grid_h),
126
+ elem_id="layout_prompt",
127
+ interactive=False
128
+ )
129
+
130
+ task_prompt = gr.Textbox(
131
+ label="Task Description (Can be modified by referring to examples to perform custom tasks, but may lead to unstable results)",
132
+ placeholder="Describe what task should be performed...",
133
+ value="",
134
+ elem_id="task_prompt"
135
+ )
136
+
137
+ content_prompt = gr.Textbox(
138
+ label="Content Description (Image caption, Editing instructions, etc.)",
139
+ placeholder="Describe the content requirements...",
140
+ value="",
141
+ elem_id="content_prompt"
142
+ )
143
+
144
+ generate_btn = gr.Button("Generate", elem_id="generate_btn")
145
+
146
+ grid_h = gr.Slider(minimum=0, maximum=max_grid_h-1, value=default_grid_h-1, step=1, label="Number of In-context Examples", elem_id="grid_h")
147
+ grid_w = gr.Slider(minimum=1, maximum=max_grid_w, value=default_grid_w, step=1, label="Task Columns", elem_id="grid_w")
148
+
149
+ with gr.Accordion("Advanced options", open=False):
150
+ seed = gr.Number(label="Seed (0 for random)", value=0, precision=0)
151
+ steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=default_steps, step=1)
152
+ cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=50.0, value=30, step=1)
153
+ upsampling_steps = gr.Slider(label="Upsampling steps (SDEdit)", minimum=1, maximum=100.0, value=10, step=1)
154
+ upsampling_noise = gr.Slider(label="Upsampling noise (SDEdit)", minimum=0, maximum=1.0, value=default_upsampling_noise, step=0.01)
155
+
156
+ gr.Markdown(CITATION)
157
+
158
+ # 右侧列:输出图像
159
+ with gr.Column(scale=2):
160
+ output_gallery = gr.Gallery(
161
+ label="Generated Results",
162
+ show_label=True,
163
+ elem_id="output_gallery",
164
+ columns=None, # 设为None以允许自动调整
165
+ rows=None, # 设为None以允许自动调整
166
+ height="auto",
167
+ allow_preview=True,
168
+ object_fit="contain" # 确保图片完整显示
169
+ )
170
+
171
+ gr.Markdown("# Task Examples")
172
+ text_dense_prediction_tasks = gr.Textbox(label="Task", visible=False)
173
+ dense_prediction_tasks = gr.Dataset(
174
+ samples=demo_tasks.dense_prediction_text,
175
+ label='Dense Prediction',
176
+ samples_per_page=1000,
177
+ components=[text_dense_prediction_tasks])
178
+
179
+ text_conditional_generation_tasks = gr.Textbox(label="Task", visible=False)
180
+ conditional_generation_tasks = gr.Dataset(
181
+ samples=demo_tasks.conditional_generation_text,
182
+ label='Conditional Generation',
183
+ samples_per_page=1000,
184
+ components=[text_conditional_generation_tasks])
185
+
186
+ text_image_restoration_tasks = gr.Textbox(label="Task", visible=False)
187
+ image_restoration_tasks = gr.Dataset(
188
+ samples=demo_tasks.image_restoration_text,
189
+ label='Image Restoration',
190
+ samples_per_page=1000,
191
+ components=[text_image_restoration_tasks])
192
+
193
+ text_style_transfer_tasks = gr.Textbox(label="Task", visible=False)
194
+ style_transfer_tasks = gr.Dataset(
195
+ samples=demo_tasks.style_transfer_text,
196
+ label='Style Transfer',
197
+ samples_per_page=1000,
198
+ components=[text_style_transfer_tasks])
199
+
200
+ text_style_condition_fusion_tasks = gr.Textbox(label="Task", visible=False)
201
+ style_condition_fusion_tasks = gr.Dataset(
202
+ samples=demo_tasks.style_condition_fusion_text,
203
+ label='Style Condition Fusion',
204
+ samples_per_page=1000,
205
+ components=[text_style_condition_fusion_tasks])
206
+
207
+ text_tryon_tasks = gr.Textbox(label="Task", visible=False)
208
+ tryon_tasks = gr.Dataset(
209
+ samples=demo_tasks.tryon_text,
210
+ label='Virtual Try-On',
211
+ samples_per_page=1000,
212
+ components=[text_tryon_tasks])
213
+
214
+ text_relighting_tasks = gr.Textbox(label="Task", visible=False)
215
+ relighting_tasks = gr.Dataset(
216
+ samples=demo_tasks.relighting_text,
217
+ label='Relighting',
218
+ samples_per_page=1000,
219
+ components=[text_relighting_tasks])
220
+
221
+ text_photodoodle_tasks = gr.Textbox(label="Task", visible=False)
222
+ photodoodle_tasks = gr.Dataset(
223
+ samples=demo_tasks.photodoodle_text,
224
+ label='Photodoodle',
225
+ samples_per_page=1000,
226
+ components=[text_photodoodle_tasks])
227
+
228
+ text_editing_tasks = gr.Textbox(label="Task", visible=False)
229
+ editing_tasks = gr.Dataset(
230
+ samples=demo_tasks.editing_text,
231
+ label='Editing',
232
+ samples_per_page=1000,
233
+ components=[text_editing_tasks])
234
+
235
+ text_unseen_tasks = gr.Textbox(label="Task", visible=False)
236
+ unseen_tasks = gr.Dataset(
237
+ samples=demo_tasks.unseen_tasks_text,
238
+ label='Unseen Tasks (May produce unstable effects)',
239
+ samples_per_page=1000,
240
+ components=[text_unseen_tasks])
241
+
242
+ gr.Markdown("# Subject-driven Tasks Examples")
243
+ text_subject_driven_tasks = gr.Textbox(label="Task", visible=False)
244
+ subject_driven_tasks = gr.Dataset(
245
+ samples=demo_tasks.subject_driven_text,
246
+ label='Subject-driven Generation',
247
+ samples_per_page=1000,
248
+ components=[text_subject_driven_tasks])
249
+
250
+ text_condition_subject_fusion_tasks = gr.Textbox(label="Task", visible=False)
251
+ condition_subject_fusion_tasks = gr.Dataset(
252
+ samples=demo_tasks.condition_subject_fusion_text,
253
+ label='Condition+Subject Fusion',
254
+ samples_per_page=1000,
255
+ components=[text_condition_subject_fusion_tasks])
256
+
257
+ text_style_transfer_with_subject_tasks = gr.Textbox(label="Task", visible=False)
258
+ style_transfer_with_subject_tasks = gr.Dataset(
259
+ samples=demo_tasks.style_transfer_with_subject_text,
260
+ label='Style Transfer with Subject',
261
+ samples_per_page=1000,
262
+ components=[text_style_transfer_with_subject_tasks])
263
+
264
+ text_condition_subject_style_fusion_tasks = gr.Textbox(label="Task", visible=False)
265
+ condition_subject_style_fusion_tasks = gr.Dataset(
266
+ samples=demo_tasks.condition_subject_style_fusion_text,
267
+ label='Condition+Subject+Style Fusion',
268
+ samples_per_page=1000,
269
+ components=[text_condition_subject_style_fusion_tasks])
270
+
271
+ text_editing_with_subject_tasks = gr.Textbox(label="Task", visible=False)
272
+ editing_with_subject_tasks = gr.Dataset(
273
+ samples=demo_tasks.editing_with_subject_text,
274
+ label='Editing with Subject',
275
+ samples_per_page=1000,
276
+ components=[text_editing_with_subject_tasks])
277
+
278
+ text_image_restoration_with_subject_tasks = gr.Textbox(label="Task", visible=False)
279
+ image_restoration_with_subject_tasks = gr.Dataset(
280
+ samples=demo_tasks.image_restoration_with_subject_text,
281
+ label='Image Restoration with Subject',
282
+ samples_per_page=1000,
283
+ components=[text_image_restoration_with_subject_tasks])
284
+
285
+ def update_grid(h, w):
286
+ actual_h = h + 1
287
+ model.set_grid_size(actual_h, w)
288
+
289
+ updates = []
290
+
291
+ # Update image component visibility
292
+ for i in range(max_grid_h * max_grid_w):
293
+ curr_row = i // max_grid_w
294
+ curr_col = i % max_grid_w
295
+ updates.append(
296
+ gr.update(
297
+ label=f"In-context Example {curr_row + 1}/{curr_col + 1}" if curr_row != actual_h - 1 else f"Query {curr_col + 1}",
298
+ elem_id=f"img_{curr_row}_{curr_col}",
299
+ visible=(curr_row < actual_h and curr_col < w)))
300
+
301
+ # Update row visibility and labels
302
+ updates_row = []
303
+ updates_row_text = []
304
+ for i in range(max_grid_h):
305
+ updates_row.append(gr.update(f"row_{i}", visible=(i < actual_h)))
306
+ updates_row_text.append(
307
+ gr.update(
308
+ elem_id=f"row_text_{i}",
309
+ visible=i < actual_h,
310
+ value="<div style='font-size: 24px; font-weight: bold;'>" +
311
+ ("Query" if i == actual_h - 1 else f"In-context Example {i + 1}") +
312
+ "</div>",
313
+ )
314
+ )
315
+
316
+ updates.extend(updates_row)
317
+ updates.extend(updates_row_text)
318
+ updates.append(gr.update(elem_id="layout_prompt", value=get_layout_instruction(w, actual_h)))
319
+ return updates
320
+
321
+ def generate_image(*inputs):
322
+ images = []
323
+ for i in range(model.grid_h):
324
+ images.append([])
325
+ for j in range(model.grid_w):
326
+ images[i].append(inputs[i * max_grid_w + j])
327
+ seed, cfg, steps, upsampling_steps, upsampling_noise, layout_text, task_text, content_text = inputs[-8:]
328
+
329
+ results = model.process_images(
330
+ images,
331
+ [layout_text, task_text, content_text],
332
+ seed=seed, cfg=cfg, steps=steps,
333
+ upsampling_steps=upsampling_steps, upsampling_noise=upsampling_noise
334
+ )
335
+
336
+ output = gr.update(
337
+ elem_id='output_gallery',
338
+ value=results,
339
+ columns=min(len(results), 2),
340
+ rows=int(len(results) / 2 + 0.5))
341
+
342
+ return output
343
+
344
+ def process_tasks(task, func):
345
+ outputs = func(task)
346
+ mask = outputs[0]
347
+ state = outputs[1:8]
348
+ if state[5] is None:
349
+ state[5] = default_upsampling_noise
350
+ if state[6] is None:
351
+ state[6] = default_steps
352
+ images = outputs[8:-len(mask)]
353
+ output = outputs[-len(mask):]
354
+ for i in range(len(mask)):
355
+ if mask[i] == 1:
356
+ images.append(None)
357
+ else:
358
+ images.append(output[-len(mask) + i])
359
+
360
+ state[0] = state[0] - 1
361
+ cur_hrid_h = state[0]
362
+ cur_hrid_w = state[1]
363
+
364
+ current_example = [None] * 25
365
+ for i, image in enumerate(images):
366
+ pos = (i // cur_hrid_w) * 5 + (i % cur_hrid_w)
367
+ if image is not None:
368
+ current_example[pos] = image
369
+ update_grid(cur_hrid_h, cur_hrid_w)
370
+ output = gr.update(
371
+ elem_id='output_gallery',
372
+ value=output,
373
+ columns=min(len(output), 2),
374
+ rows=int(len(output) / 2 + 0.5))
375
+ return [output] + current_example + state
376
+
377
+ dense_prediction_tasks.click(
378
+ partial(process_tasks, func=demo_tasks.process_dense_prediction_tasks),
379
+ inputs=[dense_prediction_tasks],
380
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
381
+
382
+ conditional_generation_tasks.click(
383
+ partial(process_tasks, func=demo_tasks.process_conditional_generation_tasks),
384
+ inputs=[conditional_generation_tasks],
385
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
386
+
387
+ image_restoration_tasks.click(
388
+ partial(process_tasks, func=demo_tasks.process_image_restoration_tasks),
389
+ inputs=[image_restoration_tasks],
390
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
391
+
392
+ style_transfer_tasks.click(
393
+ partial(process_tasks, func=demo_tasks.process_style_transfer_tasks),
394
+ inputs=[style_transfer_tasks],
395
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
396
+
397
+ style_condition_fusion_tasks.click(
398
+ partial(process_tasks, func=demo_tasks.process_style_condition_fusion_tasks),
399
+ inputs=[style_condition_fusion_tasks],
400
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
401
+
402
+ relighting_tasks.click(
403
+ partial(process_tasks, func=demo_tasks.process_relighting_tasks),
404
+ inputs=[relighting_tasks],
405
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
406
+
407
+ tryon_tasks.click(
408
+ partial(process_tasks, func=demo_tasks.process_tryon_tasks),
409
+ inputs=[tryon_tasks],
410
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
411
+
412
+ photodoodle_tasks.click(
413
+ partial(process_tasks, func=demo_tasks.process_photodoodle_tasks),
414
+ inputs=[photodoodle_tasks],
415
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
416
+
417
+ editing_tasks.click(
418
+ partial(process_tasks, func=demo_tasks.process_editing_tasks),
419
+ inputs=[editing_tasks],
420
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
421
+
422
+ unseen_tasks.click(
423
+ partial(process_tasks, func=demo_tasks.process_unseen_tasks),
424
+ inputs=[unseen_tasks],
425
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
426
+
427
+ subject_driven_tasks.click(
428
+ partial(process_tasks, func=demo_tasks.process_subject_driven_tasks),
429
+ inputs=[subject_driven_tasks],
430
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
431
+
432
+ style_transfer_with_subject_tasks.click(
433
+ partial(process_tasks, func=demo_tasks.process_style_transfer_with_subject_tasks),
434
+ inputs=[style_transfer_with_subject_tasks],
435
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
436
+
437
+ condition_subject_fusion_tasks.click(
438
+ partial(process_tasks, func=demo_tasks.process_condition_subject_fusion_tasks),
439
+ inputs=[condition_subject_fusion_tasks],
440
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
441
+
442
+ condition_subject_style_fusion_tasks.click(
443
+ partial(process_tasks, func=demo_tasks.process_condition_subject_style_fusion_tasks),
444
+ inputs=[condition_subject_style_fusion_tasks],
445
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
446
+
447
+ editing_with_subject_tasks.click(
448
+ partial(process_tasks, func=demo_tasks.process_editing_with_subject_tasks),
449
+ inputs=[editing_with_subject_tasks],
450
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
451
+
452
+ image_restoration_with_subject_tasks.click(
453
+ partial(process_tasks, func=demo_tasks.process_image_restoration_with_subject_tasks),
454
+ inputs=[image_restoration_with_subject_tasks],
455
+ outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps], show_progress=False, queue=False)
456
+ # Initialize grid
457
+ model.set_grid_size(default_grid_h, default_grid_w)
458
+
459
+ # Connect event processing function to all components that need updating
460
+ output_components = all_image_inputs + rows + row_texts + [layout_prompt]
461
+
462
+ grid_h.change(fn=update_grid, inputs=[grid_h, grid_w], outputs=output_components)
463
+ grid_w.change(fn=update_grid, inputs=[grid_h, grid_w], outputs=output_components)
464
+
465
+ # Modify generate button click event
466
+ generate_btn.click(
467
+ fn=generate_image,
468
+ inputs=all_image_inputs + [seed, cfg, steps, upsampling_steps, upsampling_noise] + [layout_prompt, task_prompt, content_prompt],
469
+ outputs=output_gallery
470
+ )
471
+
472
+ return demo
473
+
474
+ def parse_args():
475
+ parser = argparse.ArgumentParser()
476
+ parser.add_argument("--model_path", type=str, default=None)
477
+ parser.add_argument("--precision", type=str, choices=["fp32", "bf16", "fp16"], default="bf16")
478
+ parser.add_argument("--resolution", type=int, default=384)
479
+ return parser.parse_args()
480
+
481
+ if __name__ == "__main__":
482
+ args = parse_args()
483
+
484
+ # Initialize model
485
+ model = VisualClozeModel(resolution=args.resolution, model_path=args.model_path, precision=args.precision)
486
+
487
+ # Create Gradio demo
488
+ demo = create_demo(model)
489
+
490
+ # Start Gradio server
491
+ demo.launch(share=False, server_port=10050, server_name="0.0.0.0")
data/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .prefix_instruction import *
data/prefix_instruction.py ADDED
@@ -0,0 +1,1086 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+
3
+ condition_list = ["canny", "depth", "hed", "normal", "mlsd", "openpose", "sam2_mask", "mask", "foreground", "background", "uniformer"]
4
+ style_list = ["InstantStyle", "ReduxStyle"]
5
+ editing_list = ["DepthEdit", "FillEdit"]
6
+ degradation_list = [
7
+ # blur
8
+ "blur",
9
+ "compression",
10
+ "SRx2",
11
+ "SRx4",
12
+ "pixelate",
13
+ "Defocus",
14
+ "GaussianBlur",
15
+ # sharpen
16
+ "oversharpen",
17
+ # nosie
18
+ "GaussianNoise",
19
+ "PoissonNoise",
20
+ "SPNoise",
21
+ # mosaic
22
+ "mosaic",
23
+ # contrast
24
+ "contrast_strengthen",
25
+ "contrast_weaken",
26
+ # quantization
27
+ "quantization",
28
+ "JPEG",
29
+ # light
30
+ "brighten",
31
+ "darken",
32
+ "LowLight",
33
+ # color
34
+ "saturate_strengthen",
35
+ "saturate_weaken",
36
+ "gray",
37
+ "ColorDistortion",
38
+ # infilling
39
+ "Inpainting",
40
+ # rotate
41
+ "rotate90",
42
+ "rotate180",
43
+ "rotate270",
44
+ # other
45
+ "Barrel",
46
+ "Pincushion",
47
+ "Elastic",
48
+ # spacial effect
49
+ "Rain",
50
+ "Frost",
51
+ ]
52
+
53
+
54
+ def get_image_prompt(image_type):
55
+ image_prompts = {
56
+ "target": [
57
+ "a high-quality image",
58
+ "an aesthetically pleasing photograph",
59
+ "a high-resolution image",
60
+ "an image with vivid details",
61
+ "a visually striking and clear picture",
62
+ "a high-definition image",
63
+ "an image with artistic appeal",
64
+ "a sharp and beautifully composed photograph",
65
+ "a high-aesthetic image",
66
+ "an image with flawless clarity",
67
+ "a vibrant and professionally captured photo",
68
+ "a crystal-clear image",
69
+ "an image with artistic quality"
70
+ "a high-quality image with exceptional detail",
71
+ "a photo realistic image",
72
+ ],
73
+ "reference": [
74
+ "a reference image",
75
+ "an image featuring the primary object"
76
+ "a reference for the main object",
77
+ "a reference image highlighting the central object",
78
+ "an image containing the key object",
79
+ "a reference image with the main subject included",
80
+ "an image providing the main object",
81
+ "a reference image showcasing the dominant object",
82
+ "an image that includes the main object",
83
+ "a reference image capturing the primary subject",
84
+ "an image containing the main subject",
85
+ ],
86
+ # condition
87
+ "canny": [
88
+ "canny edge map with sharp black-and-white contours",
89
+ "black-and-white edge map highlighting crisp boundaries",
90
+ "canny result showing stark white edges on black",
91
+ "edge map with clean white lines on a dark background",
92
+ "canny output featuring precise white object outlines",
93
+ "black background with white edge-detected contours",
94
+ "canny edge map displaying clear white structural edges",
95
+ "white edge lines on black from canny detection",
96
+ "canny map with sharp white edges and dark voids",
97
+ "edge map revealing white outlines of object shapes",
98
+ ],
99
+ "depth": [
100
+ "depth map showing gray-scale object contours",
101
+ "gray-toned depth map with layered outlines",
102
+ "depth map featuring gradient-gray surfaces",
103
+ "gray-shaded depth map with distinct edges",
104
+ "depth map displaying soft gray gradients",
105
+ "gray-scale depth map with clear object boundaries",
106
+ "depth map highlighting gray-level depth variations",
107
+ "gray-textured depth map with smooth transitions",
108
+ "depth map revealing gray-toned spatial layers",
109
+ "gray-based depth map with detailed object contours",
110
+ ],
111
+ "hed": [
112
+ "hed edge map with smooth flowing contours",
113
+ "soft-edged map from hed detection",
114
+ "hed result showing refined continuous edges",
115
+ "edge map with natural well-connected outlines",
116
+ "hed output featuring smooth detailed boundaries",
117
+ "elegant edge map with seamless transitions",
118
+ "hed edge map displaying clean holistic contours",
119
+ "refined edge lines from hed detection",
120
+ "hed map with flowing natural object outlines",
121
+ "edge map revealing smooth interconnected shapes",
122
+ ],
123
+ "normal": [
124
+ "normal map showing surface orientation details",
125
+ "rgb-coded normal map for 3D lighting",
126
+ "normal map with encoded surface normals",
127
+ "detailed normal map for texture shading",
128
+ "normal map highlighting surface curvature",
129
+ "rgb normal map for bump mapping effects",
130
+ "normal map capturing fine geometric details",
131
+ "surface normal visualization in rgb colors",
132
+ "normal map for realistic lighting interaction",
133
+ "normal map displaying directional surface data",
134
+ ],
135
+ "mlsd": [
136
+ "mlsd detected straight line segments",
137
+ "line segments extracted using mlsd",
138
+ "mlsd output showing precise straight lines",
139
+ "straight edges detected by mlsd algorithm",
140
+ "mlsd result with clean line segment boundaries",
141
+ "line segment map generated by mlsd",
142
+ "mlsd-detected straight structural lines",
143
+ "straight line visualization from mlsd",
144
+ "mlsd-based line segment detection output",
145
+ "line segments highlighted by mlsd method",
146
+ ],
147
+ "openpose": [
148
+ "openpose skeleton with colorful connecting lines",
149
+ "body keypoints linked by bright colored lines",
150
+ "openpose output showing joints and vibrant skeleton",
151
+ "human pose with colored lines for bone structure",
152
+ "openpose-detected keypoints and colorful limbs",
153
+ "skeletal lines in vivid colors from openpose",
154
+ "body joints connected by multicolored straight lines",
155
+ "openpose visualization with colorful skeletal links",
156
+ "keypoints and bright lines forming body skeleton",
157
+ "human pose mapped with colored lines by openpose",
158
+ ],
159
+ "sam2_mask": [
160
+ "sam 2 generated colorful segmentation masks",
161
+ "color-coded masks from sam 2 segmentation",
162
+ "sam 2 output with vibrant object masks",
163
+ "segmentation masks in bright colors by sam 2",
164
+ "colorful object masks from sam 2 detection",
165
+ "sam 2 result showing multicolored regions",
166
+ "masks with distinct colors from sam 2",
167
+ "sam 2 segmentation with vivid mask overlays",
168
+ "colorful masks highlighting objects via sam 2",
169
+ "sam 2-generated masks with rich color coding",
170
+ ],
171
+ "uniformer": [
172
+ "color-coded objects in uniformer segmentation",
173
+ "uniformer map with colored object blocks",
174
+ "objects as distinct color patches by uniformer",
175
+ "color blocks representing objects in uniformer",
176
+ "uniformer output with colored object regions",
177
+ "objects highlighted as color zones in uniformer",
178
+ "uniformer segmentation showing color-divided objects",
179
+ "color patches for objects in uniformer result",
180
+ "uniformer map with objects as solid color areas",
181
+ "objects segmented as colored blocks by uniformer",
182
+ "uniformer map with objects as solid color areas",
183
+ ],
184
+ "mask": [
185
+ "Color-coded objects in open-world segmentation",
186
+ "Distinct colors marking different objects",
187
+ "Objects highlighted as unique color patches",
188
+ "Color blocks representing diverse objects",
189
+ "Segmented image with varied color zones",
190
+ "Objects visualized as solid color regions",
191
+ "Colorful map of open-world object segmentation",
192
+ "Objects divided by vibrant color boundaries",
193
+ "Color-coded segmentation of diverse items",
194
+ "Objects mapped as distinct colored areas",
195
+ ],
196
+ "foreground": [
197
+ "Foreground on solid color canvas",
198
+ "Image with foreground on plain backdrop",
199
+ "Foreground placed on monochrome background",
200
+ "Objects on solid color base",
201
+ "Foreground isolated on uniform color",
202
+ "Segmented subject on plain color field",
203
+ "Foreground displayed on solid color",
204
+ "Image with foreground on solid backdrop",
205
+ "Foreground on a clean color canvas",
206
+ "Objects on a solid color background",
207
+ ],
208
+ "background": [
209
+ "Background-only image with foreground masked",
210
+ "Photo showing background after masking foreground",
211
+ "Image with foreground removed leaving background",
212
+ "Background revealed by masking the foreground",
213
+ "Foreground masked to expose background",
214
+ "Picture with background visible after masking",
215
+ "Image displaying background without foreground",
216
+ "Foreground erased leaving only background",
217
+ "Background isolated by masking the foreground",
218
+ "Photo with foreground hidden showing background",
219
+ ],
220
+ # Style
221
+ "style_source": [
222
+ "Image in a distinct artistic style",
223
+ "Artistically styled picture with unique flair",
224
+ "Photo showcasing a specific art style",
225
+ "Image with a clear artistic aesthetic",
226
+ "Art-style influenced visual composition",
227
+ "Picture reflecting a particular art movement",
228
+ "Image with bold artistic characteristics",
229
+ "Artistically rendered visual content",
230
+ "Photo with a strong artistic theme",
231
+ "Image embodying a defined art style",
232
+ ],
233
+ "style_target": [
234
+ "High-quality image with striking artistic style",
235
+ "Crisp photo showcasing bold artistic flair",
236
+ "Visually stunning image with artistic influence",
237
+ "High-definition picture in a unique art style",
238
+ "Artistically styled image with exceptional clarity",
239
+ "High-quality visual with distinct artistic touch",
240
+ "Sharp photo reflecting a clear artistic theme",
241
+ "Artistically crafted image with high resolution",
242
+ "Vibrant picture blending quality and art style",
243
+ "High-aesthetic image with artistic precision",
244
+ ],
245
+ # Editing
246
+ "DepthEdit": [
247
+ "a high-quality image",
248
+ "an aesthetically pleasing photograph",
249
+ "a high-resolution image",
250
+ "an image with vivid details",
251
+ "a visually striking and clear picture",
252
+ "a high-definition image",
253
+ "an image with artistic appeal",
254
+ "a sharp and beautifully composed photograph",
255
+ "a high-aesthetic image",
256
+ "an image with flawless clarity",
257
+ "a vibrant and professionally captured photo",
258
+ "a crystal-clear image",
259
+ "an image with artistic quality",
260
+ "a high-quality image with exceptional detail",
261
+ "a photo realistic image",
262
+ ],
263
+ "FillEdit": [
264
+ "a high-quality image",
265
+ "an aesthetically pleasing photograph",
266
+ "a high-resolution image",
267
+ "an image with vivid details",
268
+ "a visually striking and clear picture",
269
+ "a high-definition image",
270
+ "an image with artistic appeal",
271
+ "a sharp and beautifully composed photograph",
272
+ "a high-aesthetic image",
273
+ "an image with flawless clarity",
274
+ "a vibrant and professionally captured photo",
275
+ "a crystal-clear image",
276
+ "an image with artistic quality",
277
+ "a high-quality image with exceptional detail",
278
+ "a photo realistic image",
279
+ ],
280
+ # degradation
281
+ # Blur
282
+ "blur": [
283
+ "a softly blurred image with smooth transitions",
284
+ "a photograph with a gentle motion blur effect",
285
+ "an image exhibiting subtle Gaussian blur",
286
+ "a picture with a light and even blurring",
287
+ "a softly defocused photograph with reduced sharpness",
288
+ "an image featuring a mild blur for artistic effect",
289
+ "a photograph with a gentle out-of-focus appearance",
290
+ "a softly smeared image with smooth edges",
291
+ "a picture with a light blur enhancing the mood",
292
+ "an image with a delicate blur creating a dreamy effect",
293
+ ],
294
+ "compression": [
295
+ "a highly compressed image with noticeable artifacts",
296
+ "a photograph showing compression-induced quality loss",
297
+ "an image with visible compression artifacts and reduced clarity",
298
+ "a picture exhibiting blocky artifacts from compression",
299
+ "a compressed photo with color banding and loss of detail",
300
+ "an image displaying noticeable compression noise",
301
+ "a photograph with degraded quality due to high compression",
302
+ "a picture showing pixelation from aggressive compression",
303
+ "an image with artifacts and reduced resolution from compression",
304
+ "a compressed image featuring loss of sharpness and detail",
305
+ ],
306
+ "SRx2": [
307
+ "an image downsampled by a factor of 2 with enhanced details",
308
+ "a photograph resized to half its original resolution",
309
+ "an downscaled image (2x) maintaining image quality",
310
+ "a picture downsized by 2x with preserved sharpness",
311
+ "an image scaled half its size with clear details",
312
+ "a low-resolution version of the original image (2x)",
313
+ "a half-resolution photograph with maintained clarity",
314
+ "an image decreased in size by 2x with minimal quality loss",
315
+ "a 2x downscaled picture retaining original details",
316
+ "an image resized to half its original dimensions with enhanced quality",
317
+ ],
318
+ "SRx4": [
319
+ "an image downsampled by a factor of 4 with enhanced details",
320
+ "a photograph resized to quarter its original resolution",
321
+ "an downscaled image (4x) maintaining image quality",
322
+ "a picture downsized by 4x with preserved sharpness",
323
+ "an image scaled four times its size with clear details",
324
+ "a low-resolution version of the original image (4x)",
325
+ "a quadruple-resolution photograph with maintained clarity",
326
+ "an image decreased in size by 4x with minimal quality loss",
327
+ "a 4x downscaled picture retaining original details",
328
+ "an image resized to quarter its original dimensions with enhanced quality",
329
+ ],
330
+ "pixelate": [
331
+ "a heavily pixelated image with large blocks",
332
+ "a picture showing strong pixelation effects",
333
+ "an image with noticeable pixel blocks obscuring details",
334
+ "a pixelated photograph with reduced image clarity",
335
+ "an image exhibiting coarse pixelation for a stylized look",
336
+ "a picture with large pixel squares creating a mosaic effect",
337
+ "a highly pixelated photo obscuring fine details",
338
+ "an image featuring prominent pixelation and blockiness",
339
+ "a pixelated image with distinct square blocks",
340
+ "a photograph with exaggerated pixelation for artistic effect",
341
+ ],
342
+ "Defocus": [
343
+ "a defocused image with soft and blurry regions",
344
+ "a photograph with intentional defocus creating a shallow depth of field",
345
+ "an image exhibiting a defocused background with a clear subject",
346
+ "a picture with selective defocus enhancing the main object",
347
+ "a defocused photo with smooth out-of-focus areas",
348
+ "an image showing a defocused effect for artistic blurring",
349
+ "a photograph with a softly defocused foreground",
350
+ "a picture with partial defocus creating a dreamy appearance",
351
+ "an image featuring defocus to highlight specific areas",
352
+ "a defocused photograph with gentle blurring around the subject",
353
+ ],
354
+ "GaussianBlur": [
355
+ "an image with Gaussian blurring creating a soft focus effect",
356
+ "a photograph with a Gaussian blur enhancing the subject",
357
+ "a picture with Gaussian blurring to highlight the main object",
358
+ "an image featuring Gaussian blur to soften the background",
359
+ "a Gaussian-blurred photograph with a soft focus",
360
+ "a Gaussian-blurred image with a gentle focus on the subject",
361
+ "a picture with Gaussian blurring to emphasize the main subject",
362
+ "an image with Gaussian blurring to create a dreamy effect",
363
+ "a Gaussian-blurred photograph with a soft focus on the main object",
364
+ ],
365
+ # Sharpen
366
+ "oversharpen": [
367
+ "an image with excessive sharpening creating halos around edges",
368
+ "a photograph overly sharpened with exaggerated edge contrast",
369
+ "an oversharpened picture showing unnatural edge highlights",
370
+ "a highly sharpened image with pronounced texture details",
371
+ "a picture exhibiting over-sharpening with visible artifacts",
372
+ "an image with extreme sharpening enhancing all details sharply",
373
+ "a photograph with oversharpened edges and increased contrast",
374
+ "an overly sharpened image causing unnatural texture emphasis",
375
+ "a picture with excessive sharpening effects on all elements",
376
+ "an image displaying over-sharpened features with enhanced edges",
377
+ ],
378
+ # Noise
379
+ "GaussianNoise": [
380
+ "an image with subtle Gaussian noise adding grain",
381
+ "a photograph exhibiting Gaussian noise for a textured look",
382
+ "a picture with light Gaussian noise enhancing realism",
383
+ "an image featuring Gaussian noise with smooth distribution",
384
+ "a photo with added Gaussian noise creating a grainy effect",
385
+ "an image showing gentle Gaussian noise for artistic texture",
386
+ "a photograph with mild Gaussian noise increasing depth",
387
+ "a picture with soft Gaussian noise enhancing the image",
388
+ "an image displaying Gaussian noise for a vintage feel",
389
+ "a photo with Gaussian noise subtly integrated into the image",
390
+ ],
391
+ "PoissonNoise": [
392
+ "an image with Poisson noise creating photon distribution effects",
393
+ "a photograph exhibiting Poisson noise for realistic grain",
394
+ "a picture with added Poisson noise enhancing texture",
395
+ "an image featuring Poisson noise with natural variance",
396
+ "a photo with Poisson noise simulating low-light conditions",
397
+ "an image showing Poisson noise for authentic grain patterns",
398
+ "a photograph with mild Poisson noise increasing image depth",
399
+ "a picture with Poisson noise adding subtle texture",
400
+ "an image displaying Poisson noise for a realistic appearance",
401
+ "a photo with Poisson noise integrated for enhanced realism",
402
+ ],
403
+ "SPNoise": [
404
+ "an image with salt and pepper noise introducing random pixels",
405
+ "a photograph exhibiting SP noise with black and white speckles",
406
+ "a picture with added salt and pepper noise creating scattered dots",
407
+ "an image featuring SP noise with random pixel disruptions",
408
+ "a photo with SP noise simulating transmission errors",
409
+ "an image showing salt and pepper noise for a gritty effect",
410
+ "a photograph with mild SP noise adding texture variation",
411
+ "a picture with SP noise introducing random black and white pixels",
412
+ "an image displaying salt and pepper noise for a distressed look",
413
+ "a photo with SP noise integrated for a speckled appearance",
414
+ ],
415
+ # Mosaic
416
+ "mosaic": [
417
+ "an image with a strong mosaic effect obscuring details",
418
+ "a photograph exhibiting mosaic patterns with large tiles",
419
+ "a picture with applied mosaic effect creating a tiled appearance",
420
+ "an image featuring mosaic blocks for privacy masking",
421
+ "a photo with mosaic segmentation highlighting regions",
422
+ "an image showing a mosaic overlay for abstract effect",
423
+ "a photograph with mosaic patterns simplifying the image",
424
+ "a picture with a mosaic filter creating geometric tiles",
425
+ "an image displaying a mosaic effect for stylistic purposes",
426
+ "a photo with mosaic segmentation emphasizing specific areas",
427
+ ],
428
+ # Contrast
429
+ "contrast_strengthen": [
430
+ "an image with enhanced contrast making colors pop",
431
+ "a photograph exhibiting strengthened contrast for vividness",
432
+ "a picture with increased contrast highlighting details",
433
+ "an image featuring heightened contrast for dramatic effect",
434
+ "a photo with boosted contrast enhancing visual depth",
435
+ "an image showing strengthened contrast with pronounced shadows and highlights",
436
+ "a photograph with amplified contrast for greater clarity",
437
+ "a picture with enhanced contrast making elements stand out",
438
+ "an image displaying increased contrast for a striking appearance",
439
+ "a photo with reinforced contrast improving overall image impact",
440
+ ],
441
+ "contrast_weaken": [
442
+ "an image with reduced contrast creating a softer look",
443
+ "a photograph exhibiting weakened contrast for a muted effect",
444
+ "a picture with decreased contrast making colors more subtle",
445
+ "an image featuring lowered contrast for a gentle appearance",
446
+ "a photo with diminished contrast softening the overall image",
447
+ "an image showing weakened contrast with less pronounced shadows and highlights",
448
+ "a photograph with reduced contrast for a flatter visual tone",
449
+ "a picture with softened contrast creating a delicate atmosphere",
450
+ "an image displaying decreased contrast for a subdued look",
451
+ "a photo with lowered contrast enhancing a calm and serene feel",
452
+ ],
453
+ # Quantization
454
+ "quantization": [
455
+ "an image with quantization artifacts reducing color depth",
456
+ "a photograph exhibiting quantization leading to banding effects",
457
+ "a picture with applied quantization simplifying color gradients",
458
+ "an image featuring quantized color levels creating discrete steps",
459
+ "a photo with quantization reducing the number of distinct colors",
460
+ "an image showing quantization leading to posterization effects",
461
+ "a photograph with quantized color palette for a stylized look",
462
+ "a picture with quantization introducing color banding and loss of detail",
463
+ "an image displaying quantization effects on smooth color transitions",
464
+ "a photo with quantization artifacts simplifying the overall color scheme",
465
+ ],
466
+ "JPEG": [
467
+ "a JPEG-compressed image with noticeable compression artifacts",
468
+ "a photograph saved in JPEG format showing quality loss",
469
+ "an image exhibiting JPEG artifacts like blockiness and blurring",
470
+ "a picture with JPEG compression leading to reduced clarity",
471
+ "an image featuring JPEG-induced artifacts affecting image quality",
472
+ "a photo with visible JPEG compression effects on details",
473
+ "an image showing JPEG artifacts such as color banding and pixelation",
474
+ "a photograph with degraded quality due to JPEG compression",
475
+ "a picture with JPEG compression artifacts impacting the overall appearance",
476
+ "an image displaying JPEG-induced quality loss with blurred edges",
477
+ ],
478
+ # Light
479
+ "brighten": [
480
+ "a brightly lit image with enhanced luminosity",
481
+ "a photograph exhibiting increased brightness for a vibrant look",
482
+ "a picture with boosted brightness making the scene more radiant",
483
+ "an image featuring heightened brightness illuminating all areas",
484
+ "a photo with amplified brightness creating a sunny appearance",
485
+ "an image showing increased brightness enhancing visibility",
486
+ "a photograph with enhanced brightness making colors more vivid",
487
+ "a picture with boosted luminosity brightening the overall image",
488
+ "an image displaying heightened brightness for a luminous effect",
489
+ "a photo with increased brightness adding warmth and clarity",
490
+ ],
491
+ "darken": [
492
+ "a darkened image with reduced luminosity creating a moody atmosphere",
493
+ "a photograph exhibiting decreased brightness for a subdued look",
494
+ "a picture with lowered brightness making the scene more somber",
495
+ "an image featuring diminished brightness enhancing shadows",
496
+ "a photo with reduced brightness creating a twilight appearance",
497
+ "an image showing decreased brightness adding depth and contrast",
498
+ "a photograph with darkened tones making colors more muted",
499
+ "a picture with lowered luminosity creating a dramatic effect",
500
+ "an image displaying reduced brightness for a darker aesthetic",
501
+ "a photo with decreased brightness enhancing the mysterious mood",
502
+ ],
503
+ "LowLight": [
504
+ "an image with low light conditions creating a dim and shadowy appearance",
505
+ "a photograph exhibiting low light to simulate night-time conditions",
506
+ "a picture with reduced illumination to create a night-time ambiance",
507
+ "an image featuring low light to emphasize the subject in darkness",
508
+ "a photo with low light conditions creating a mysterious mood",
509
+ "an image showing low light to enhance the dramatic lighting of the scene",
510
+ "a photograph with dim lighting to create a soft and dreamy effect",
511
+ "a picture with low light to emphasize the texture and details of the image",
512
+ "an image displaying low light conditions for a serene and peaceful feel",
513
+ ],
514
+ # Color
515
+ "saturate_strengthen": [
516
+ "an image with enhanced saturation making colors more vivid",
517
+ "a photograph exhibiting strengthened saturation for vibrant hues",
518
+ "a picture with boosted color saturation enhancing visual appeal",
519
+ "an image featuring heightened saturation creating rich color tones",
520
+ "a photo with amplified saturation making colors pop",
521
+ "an image showing increased saturation for a lively appearance",
522
+ "a photograph with saturated colors enhancing the overall image",
523
+ "a picture with strengthened color saturation adding vibrancy",
524
+ "an image displaying enhanced saturation for a dynamic look",
525
+ "a photo with boosted color intensity making the scene more colorful",
526
+ ],
527
+ "saturate_weaken": [
528
+ "an image with reduced saturation creating a muted color palette",
529
+ "a photograph exhibiting weakened saturation for subdued tones",
530
+ "a picture with lowered color saturation making colors more subtle",
531
+ "an image featuring diminished saturation creating a pastel look",
532
+ "a photo with decreased saturation softening the overall colors",
533
+ "an image showing reduced saturation for a faded appearance",
534
+ "a photograph with desaturated colors enhancing a minimalist aesthetic",
535
+ "a picture with weakened color saturation adding a calm feel",
536
+ "an image displaying lowered saturation for a gentle color scheme",
537
+ "a photo with diminished color intensity creating a subdued look",
538
+ ],
539
+ "gray": [
540
+ "a grayscale image with varying shades of gray",
541
+ "a black and white photograph emphasizing contrast and texture",
542
+ "a gray-toned picture highlighting light and shadow",
543
+ "an image converted to grayscale showcasing structural details",
544
+ "a monochromatic photo with rich gray gradients",
545
+ "a grayscale image emphasizing form and composition",
546
+ "a black and white picture with balanced gray tones",
547
+ "an image in gray scale enhancing depth and dimension",
548
+ "a monochrome photograph focusing on texture and contrast",
549
+ "a gray-toned image presenting a classic black and white aesthetic",
550
+ ],
551
+ "ColorDistortion": [
552
+ "an image with distorted and surreal colors",
553
+ "a picture featuring unnatural color tones",
554
+ "a visually striking image with altered hues",
555
+ "a photo showcasing disrupted color balance",
556
+ "an image with vibrant and unexpected colors",
557
+ "a picture displaying shifted color spectrums",
558
+ "an artwork-like image with perturbed colors",
559
+ "a photo with dreamlike and distorted hues",
560
+ "an image with unconventional color variations",
561
+ "a visually unique picture with color shifts",
562
+ ],
563
+ # Infilling
564
+ "Inpainting": [
565
+ "an inpainted image seamlessly filling missing areas",
566
+ "a photograph with inpainting repairing damaged regions",
567
+ "a picture featuring inpainting to restore obscured parts",
568
+ "an image using inpainting to complete incomplete areas",
569
+ "a photo with inpainting blending filled regions naturally",
570
+ "an image showing inpainting techniques removing unwanted objects",
571
+ "a photograph with inpainting reconstructing missing details",
572
+ "a picture utilizing inpainting to enhance image continuity",
573
+ "an image with inpainting seamlessly integrating filled sections",
574
+ "a photo using inpainting to mend and complete the visual content",
575
+ ],
576
+ # Rotate
577
+ "rotate90": [
578
+ "an image rotated 90 degrees clockwise for a new perspective",
579
+ "a photograph turned 90 degrees to the right altering the orientation",
580
+ "a picture rotated a quarter turn clockwise enhancing composition",
581
+ "an image featuring a 90-degree rotation adjusting the viewpoint",
582
+ "a photo with a 90-degree clockwise rotation changing the layout",
583
+ "an image showing a rotated view at 90 degrees for a fresh angle",
584
+ "a photograph rotated right by 90 degrees for dynamic framing",
585
+ "a picture with a 90-degree turn clockwise modifying the scene",
586
+ "an image displaying a 90-degree rotated orientation for visual interest",
587
+ "a photo rotated ninety degrees to enhance the composition",
588
+ ],
589
+ "rotate180": [
590
+ "an image rotated 180 degrees flipping it upside down",
591
+ "a photograph turned completely around with a 180-degree rotation",
592
+ "a picture rotated halfway, creating an inverted perspective",
593
+ "an image featuring a 180-degree turn altering the original orientation",
594
+ "a photo with an upside-down view due to 180-degree rotation",
595
+ "an image showing a flipped perspective with a 180-degree rotation",
596
+ "a photograph rotated twice around, changing the viewpoint",
597
+ "a picture with a half-turn rotation modifying the scene layout",
598
+ "an image displaying a 180-degree rotated orientation for a unique angle",
599
+ "a photo rotated one full half-circle to invert the composition",
600
+ ],
601
+ "rotate270": [
602
+ "an image rotated 270 degrees clockwise for a new angle",
603
+ "a photograph turned 270 degrees to the right altering the orientation",
604
+ "a picture rotated three quarters turn clockwise enhancing composition",
605
+ "an image featuring a 270-degree rotation adjusting the viewpoint",
606
+ "a photo with a 270-degree clockwise rotation changing the layout",
607
+ "an image showing a rotated view at 270 degrees for a fresh angle",
608
+ "a photograph rotated right by 270 degrees for dynamic framing",
609
+ "a picture with a 270-degree turn clockwise modifying the scene",
610
+ "an image displaying a 270-degree rotated orientation for visual interest",
611
+ "a photo rotated two and a half turns clockwise to enhance the composition",
612
+ ],
613
+ # Other
614
+ "Barrel": [
615
+ "an image with barrel distortion bending the edges outward",
616
+ "a photograph exhibiting barrel distortion creating a convex effect",
617
+ "a picture with barrel distortion warping the image edges",
618
+ "an image featuring barrel distortion causing peripheral stretching",
619
+ "a photo with barrel distortion curving the sides outward",
620
+ "an image showing barrel distortion for a fisheye lens effect",
621
+ "a photograph with warped edges due to barrel distortion",
622
+ "a picture with barrel distortion altering the straight lines",
623
+ "an image displaying barrel distortion creating a rounded appearance",
624
+ "a photo with barrel distortion enhancing the central focus",
625
+ ],
626
+ "Pincushion": [
627
+ "an image with pincushion distortion bending the edges inward",
628
+ "a photograph exhibiting pincushion distortion creating a concave effect",
629
+ "a picture with pincushion distortion warping the image edges inward",
630
+ "an image featuring pincushion distortion causing peripheral compression",
631
+ "a photo with pincushion distortion curving the sides inward",
632
+ "an image showing pincushion distortion for a telephoto lens effect",
633
+ "a photograph with warped edges due to pincushion distortion",
634
+ "a picture with pincushion distortion altering the straight lines inward",
635
+ "an image displaying pincushion distortion creating a pinched appearance",
636
+ "a photo with pincushion distortion enhancing the central focus inward",
637
+ ],
638
+ "Elastic": [
639
+ "an image with elastic deformation creating fluid distortions",
640
+ "a photograph exhibiting elastic transformations warping the structure",
641
+ "a picture with elastic effects bending and stretching elements",
642
+ "an image featuring elastic distortions for a dynamic appearance",
643
+ "a photo with elastic transformations altering the image geometry",
644
+ "an image showing elastic deformation for a fluid, wavy effect",
645
+ "a photograph with elastic warping adding motion-like distortions",
646
+ "a picture with elastic effects creating flexible and dynamic shapes",
647
+ "an image displaying elastic transformations enhancing creative distortion",
648
+ "a photo with elastic deformation modifying the original image structure",
649
+ ],
650
+ # Spatial Effect
651
+ "Rain": [
652
+ "an image with realistic rain effects adding dynamic streaks",
653
+ "a photograph exhibiting rain overlays creating a wet atmosphere",
654
+ "a picture with rain effects enhancing the scene with falling droplets",
655
+ "an image featuring rain streaks adding motion and mood",
656
+ "a photo with simulated rain creating a rainy day ambiance",
657
+ "an image showing rain effects with dynamic water droplets",
658
+ "a photograph with rain overlays adding a sense of movement",
659
+ "a picture with rain effects enhancing the visual texture",
660
+ "an image displaying rain streaks for a dramatic weather effect",
661
+ "a photo with realistic rain adding depth and atmosphere",
662
+ ],
663
+ "Frost": [
664
+ "an image with frost overlays creating icy textures",
665
+ "a photograph exhibiting frost effects adding a chilly ambiance",
666
+ "a picture with frost patterns enhancing the scene with icy details",
667
+ "an image featuring frost overlays creating a frozen appearance",
668
+ "a photo with simulated frost adding a wintry atmosphere",
669
+ "an image showing frost effects with delicate ice patterns",
670
+ "a photograph with frost overlays adding a sense of coldness",
671
+ "a picture with frost effects enhancing the visual texture with ice",
672
+ "an image displaying frost patterns for a frosty weather effect",
673
+ "a photo with realistic frost adding depth and a chilly mood",
674
+ ],
675
+ }
676
+ if image_type in style_list:
677
+ return [random.choice(image_prompts["style_source"]), random.choice(image_prompts["style_target"])]
678
+ elif image_type == 'clothing':
679
+ return [random.choice(image_prompts["clothing"]), random.choice(image_prompts["fullbody"])]
680
+ else:
681
+ return [random.choice(image_prompts[image_type])]
682
+
683
+
684
+ def get_layout_instruction(cols, rows):
685
+ layout_instruction = [
686
+ f"A grid layout with {rows} rows and {cols} columns, displaying {cols*rows} images arranged side by side.",
687
+ f"{cols*rows} images are organized into a grid of {rows} rows and {cols} columns, evenly spaced.",
688
+ f"A {rows}x{cols} grid containing {cols*rows} images, aligned in a clean and structured layout.",
689
+ f"{cols*rows} images are placed in a grid format with {rows} horizontal rows and {cols} vertical columns.",
690
+ f"A visual grid composed of {rows} rows and {cols} columns, showcasing {cols*rows} images in a balanced arrangement.",
691
+ f"{cols*rows} images form a structured grid, with {rows} rows and {cols} columns, neatly aligned.",
692
+ f"A {rows}x{cols} grid layout featuring {cols*rows} images, arranged side by side in a precise pattern.",
693
+ f"{cols*rows} images are displayed in a grid of {rows} rows and {cols} columns, creating a uniform visual structure.",
694
+ f"A grid with {rows} rows and {cols} columns, containing {cols*rows} images arranged in a symmetrical layout.",
695
+ f"{cols*rows} images are organized into a {rows}x{cols} grid, forming a cohesive and orderly display.",
696
+ ]
697
+ return random.choice(layout_instruction)
698
+
699
+
700
+ def get_task_instruction(condition_prompt, target_prompt):
701
+ task_instruction = [
702
+ f"Each row outlines a logical process, starting from {condition_prompt}, to achieve {target_prompt}.",
703
+ f"In each row, a method is described to use {condition_prompt} for generating {target_prompt}.",
704
+ f"Each row presents a task that leverages {condition_prompt} to produce {target_prompt}.",
705
+ f"Every row demonstrates how to transform {condition_prompt} into {target_prompt} through a logical approach.",
706
+ f"Each row details a strategy to derive {target_prompt} based on the provided {condition_prompt}.",
707
+ f"In each row, a technique is explained to convert {condition_prompt} into {target_prompt}.",
708
+ f"Each row illustrates a pathway from {condition_prompt} to {target_prompt} using a clear logical task.",
709
+ f"Every row provides a step-by-step guide to evolve {condition_prompt} into {target_prompt}.",
710
+ f"Each row describes a process that begins with {condition_prompt} and results in {target_prompt}.",
711
+ f"In each row, a logical task is demonstrated to achieve {target_prompt} based on {condition_prompt}.",
712
+ ]
713
+ return random.choice(task_instruction)
714
+
715
+
716
+ def get_content_instruction():
717
+ content_instruction = [
718
+ "The content of the last image in the final row is: ",
719
+ "The last image of the last row depicts: ",
720
+ "In the final row, the last image shows: ",
721
+ "The last image in the bottom row illustrates: ",
722
+ "The content of the bottom-right image is: ",
723
+ "The final image in the last row portrays: ",
724
+ "The last image of the final row displays: ",
725
+ "In the last row, the final image captures: ",
726
+ "The bottom-right corner image presents: ",
727
+ "The content of the last image in the concluding row is: ",
728
+ ]
729
+ return random.choice(content_instruction)
730
+
731
+
732
+ graph200k_task_dicts = [
733
+ {
734
+ "task_name": "conditional generation",
735
+ "sample_weight": 1,
736
+ "image_list": [
737
+ ["canny", "target"],
738
+ ["depth", "target"],
739
+ ["hed", "target"],
740
+ ["normal", "target"],
741
+ ["mlsd", "target"],
742
+ ["openpose", "target"],
743
+ ["sam2_mask", "target"],
744
+ ["uniformer", "target"],
745
+ ["mask", "target"],
746
+ ["foreground", "target"],
747
+ ["background", "target"],
748
+ ],
749
+ },
750
+ {
751
+ "task_name": "conditional generation with reference",
752
+ "sample_weight": 1,
753
+ "image_list": [
754
+ ["reference", "canny", "target"],
755
+ ["reference", "depth", "target"],
756
+ ["reference", "hed", "target"],
757
+ ["reference", "normal", "target"],
758
+ ["reference", "mlsd", "target"],
759
+ ["reference", "openpose", "target"],
760
+ ["reference", "sam2_mask", "target"],
761
+ ["reference", "uniformer", "target"],
762
+ ["reference", "mask", "target"],
763
+ ["reference", "background", "target"],
764
+ ],
765
+ },
766
+ {
767
+ "task_name": "conditional generation with style",
768
+ "sample_weight": 1,
769
+ "image_list": [
770
+ # instant style
771
+ ["canny", "InstantStyle"],
772
+ ["depth", "InstantStyle"],
773
+ ["hed", "InstantStyle"],
774
+ ["normal", "InstantStyle"],
775
+ ["mlsd", "InstantStyle"],
776
+ ["openpose", "InstantStyle"],
777
+ ["sam2_mask", "InstantStyle"],
778
+ ["uniformer", "InstantStyle"],
779
+ ["mask", "InstantStyle"],
780
+ # redux style
781
+ ["canny", "ReduxStyle"],
782
+ ["depth", "ReduxStyle"],
783
+ ["hed", "ReduxStyle"],
784
+ ["normal", "ReduxStyle"],
785
+ ["mlsd", "ReduxStyle"],
786
+ ["openpose", "ReduxStyle"],
787
+ ["sam2_mask", "ReduxStyle"],
788
+ ["uniformer", "ReduxStyle"],
789
+ ["mask", "ReduxStyle"],
790
+ ],
791
+ },
792
+ {
793
+ "task_name": "image generation with reference",
794
+ "sample_weight": 1,
795
+ "image_list": [
796
+ ["reference", "target"],
797
+ ],
798
+ },
799
+ {
800
+ "task_name": "subject extraction",
801
+ "sample_weight": 1,
802
+ "image_list": [
803
+ ["target", "reference"],
804
+ ],
805
+ },
806
+ {
807
+ "task_name": "style transfer",
808
+ "sample_weight": 1,
809
+ "image_list": [
810
+ ["target", "InstantStyle"],
811
+ ["target", "ReduxStyle"],
812
+ ["reference", "InstantStyle"],
813
+ ],
814
+ },
815
+ {
816
+ "task_name": "style transfer with condition",
817
+ "sample_weight": 1,
818
+ "image_list": [
819
+ ["reference", "canny", "InstantStyle"],
820
+ ["reference", "depth", "InstantStyle"],
821
+ ["reference", "hed", "InstantStyle"],
822
+ ["reference", "normal", "InstantStyle"],
823
+ ["reference", "mlsd", "InstantStyle"],
824
+ ["reference", "openpose", "InstantStyle"],
825
+ ["reference", "sam2_mask", "InstantStyle"],
826
+ ["reference", "uniformer", "InstantStyle"],
827
+ ["reference", "mask", "InstantStyle"],
828
+ ],
829
+ },
830
+ {
831
+ "task_name": "image editing",
832
+ "sample_weight": 1,
833
+ "image_list": [
834
+ ["DepthEdit", "target"],
835
+ ["FillEdit", "target"],
836
+ ],
837
+ },
838
+ {
839
+ "task_name": "image editing with reference",
840
+ "sample_weight": 1,
841
+ "image_list": [
842
+ ["reference", "DepthEdit", "target"],
843
+ ["reference", "FillEdit", "target"],
844
+ ],
845
+ },
846
+ {
847
+ "task_name": "dense prediction",
848
+ "sample_weight": 1,
849
+ "image_list": [
850
+ ["target", "canny"],
851
+ ["target", "depth"],
852
+ ["target", "hed"],
853
+ ["target", "normal"],
854
+ ["target", "mlsd"],
855
+ ["target", "openpose"],
856
+ ["target", "sam2_mask"],
857
+ ["target", "uniformer"],
858
+ ],
859
+ },
860
+ {
861
+ "task_name": "restoration",
862
+ "sample_weight": 1,
863
+ "image_list": [
864
+ # blur related
865
+ ["blur", "target"],
866
+ ["compression", "target"],
867
+ ["SRx2", "target"],
868
+ ["SRx4", "target"],
869
+ ["pixelate", "target"],
870
+ ["Defocus", "target"],
871
+ ["GaussianBlur", "target"],
872
+
873
+ # sharpen related
874
+ ["oversharpen", "target"],
875
+
876
+ # noise related
877
+ ["GaussianNoise", "target"],
878
+ ["PoissonNoise", "target"],
879
+ ["SPNoise", "target"],
880
+
881
+ # mosaic
882
+ ["mosaic", "target"],
883
+
884
+ # contrast related
885
+ ["contrast_strengthen", "target"],
886
+ ["contrast_weaken", "target"],
887
+
888
+ # quantization related
889
+ ["quantization", "target"],
890
+ ["JPEG", "target"],
891
+
892
+ # light related
893
+ ["brighten", "target"],
894
+ ["darken", "target"],
895
+ ["LowLight", "target"],
896
+
897
+ # color related
898
+ ["saturate_strengthen", "target"],
899
+ ["saturate_weaken", "target"],
900
+ ["gray", "target"],
901
+ ["ColorDistortion", "target"],
902
+
903
+ # infilling
904
+ ["Inpainting", "target"],
905
+
906
+ # rotation related
907
+ ["rotate90", "target"],
908
+ ["rotate180", "target"],
909
+ ["rotate270", "target"],
910
+
911
+ # distortion related
912
+ ["Barrel", "target"],
913
+ ["Pincushion", "target"],
914
+ ["Elastic", "target"],
915
+
916
+ # special effects
917
+ ["Rain", "target"],
918
+ ["Frost", "target"]
919
+ ],
920
+ },
921
+ {
922
+ "task_name": "restoration with reference",
923
+ "sample_weight": 1,
924
+ "image_list": [
925
+ # blur related
926
+ ["reference", "blur", "target"],
927
+ ["reference", "compression", "target"],
928
+ ["reference", "SRx2", "target"],
929
+ ["reference", "SRx4", "target"],
930
+ ["reference", "pixelate", "target"],
931
+ ["reference", "Defocus", "target"],
932
+ ["reference", "GaussianBlur", "target"], # new
933
+ # sharpen related
934
+ ["reference", "oversharpen", "target"],
935
+ # noise related
936
+ ["reference", "GaussianNoise", "target"],
937
+ ["reference", "PoissonNoise", "target"],
938
+ ["reference", "SPNoise", "target"],
939
+ # mosaic
940
+ ["reference", "mosaic", "target"],
941
+ # contrast related
942
+ ["reference", "contrast_strengthen", "target"],
943
+ ["reference", "contrast_weaken", "target"],
944
+ # quantization related
945
+ ["reference", "quantization", "target"],
946
+ ["reference", "JPEG", "target"],
947
+ # light related
948
+ ["reference", "brighten", "target"],
949
+ ["reference", "darken", "target"],
950
+ ["reference", "LowLight", "target"], # new
951
+ # color related
952
+ ["reference", "saturate_strengthen", "target"],
953
+ ["reference", "saturate_weaken", "target"],
954
+ ["reference", "gray", "target"],
955
+ ["reference", "ColorDistortion", "target"],
956
+ # infilling
957
+ ["reference", "Inpainting", "target"],
958
+ # rotation related
959
+ ["reference", "rotate90", "target"],
960
+ ["reference", "rotate180", "target"],
961
+ ["reference", "rotate270", "target"],
962
+ # distortion related
963
+ ["reference", "Barrel", "target"],
964
+ ["reference", "Pincushion", "target"],
965
+ ["reference", "Elastic", "target"],
966
+ # special effects
967
+ ["reference", "Rain", "target"],
968
+ ["reference", "Frost", "target"]
969
+ ],
970
+ }
971
+ ]
972
+
973
+
974
+ test_task_dicts = [
975
+ {
976
+ "task_name": "conditional generation",
977
+ "sample_weight": 1,
978
+ "image_list": [
979
+ ["canny", "target"],
980
+ ["depth", "target"],
981
+ ["hed", "target"],
982
+ ["normal", "target"],
983
+ ["mlsd", "target"],
984
+ ["openpose", "target"],
985
+ ["sam2_mask", "target"],
986
+ ["uniformer", "target"],
987
+ ["mask", "target"],
988
+ ["foreground", "target"],
989
+ ["background", "target"],
990
+ ],
991
+ },
992
+ {
993
+ "task_name": "image generation with reference",
994
+ "sample_weight": 1,
995
+ "image_list": [
996
+ ["reference", "target"],
997
+ ],
998
+ },
999
+ {
1000
+ "task_name": "conditional generation with reference",
1001
+ "sample_weight": 1,
1002
+ "image_list": [
1003
+ ["reference", "depth", "target"],
1004
+ ["reference", "openpose", "target"],
1005
+ ],
1006
+ },
1007
+ {
1008
+ "task_name": "subject extraction",
1009
+ "sample_weight": 0.2,
1010
+ "image_list": [
1011
+ ["target", "reference"],
1012
+ ],
1013
+ },
1014
+ {
1015
+ "task_name": "dense prediction",
1016
+ "sample_weight": 1,
1017
+ "image_list": [
1018
+ ["target", "depth"],
1019
+ ["target", "openpose"],
1020
+ ],
1021
+ },
1022
+ {
1023
+ "task_name": "restoration",
1024
+ "sample_weight": 1,
1025
+ "image_list": [
1026
+ # blur related
1027
+ ["GaussianBlur", "target"],
1028
+
1029
+ # infilling
1030
+ ["Inpainting", "target"],
1031
+
1032
+ # rotation related
1033
+ ["rotate90", "target"],
1034
+
1035
+ # distortion related
1036
+ ["Elastic", "target"],
1037
+ ],
1038
+ },
1039
+ {
1040
+ "task_name": "restoration with reference",
1041
+ "sample_weight": 1,
1042
+ "image_list": [
1043
+ # infilling
1044
+ ["reference", "Inpainting", "target"],
1045
+ ],
1046
+ },
1047
+ {
1048
+ "task_name": "image editing with reference",
1049
+ "sample_weight": 1,
1050
+ "image_list": [
1051
+ ["reference", "DepthEdit", "target"],
1052
+ ["reference", "FillEdit", "target"],
1053
+ ],
1054
+ },
1055
+ {
1056
+ "task_name": "style transfer",
1057
+ "sample_weight": 1,
1058
+ "image_list": [
1059
+ ["target", "InstantStyle"],
1060
+ ["target", "ReduxStyle"],
1061
+ ["reference", "InstantStyle"],
1062
+ ],
1063
+ },
1064
+ {
1065
+ "task_name": "style transfer with condition",
1066
+ "sample_weight": 1,
1067
+ "image_list": [
1068
+ ["reference", "canny", "InstantStyle"],
1069
+ ["reference", "depth", "InstantStyle"],
1070
+ ["reference", "hed", "InstantStyle"],
1071
+ ["reference", "normal", "InstantStyle"],
1072
+ ["reference", "mlsd", "InstantStyle"],
1073
+ ["reference", "openpose", "InstantStyle"],
1074
+ ["reference", "sam2_mask", "InstantStyle"],
1075
+ ["reference", "uniformer", "InstantStyle"],
1076
+ ["reference", "mask", "InstantStyle"],
1077
+ ],
1078
+ },
1079
+ {
1080
+ "task_name": "subject extraction",
1081
+ "sample_weight": 1,
1082
+ "image_list": [
1083
+ ["target", "reference"],
1084
+ ],
1085
+ },
1086
+ ]
degradation_toolkit/__init__.py ADDED
File without changes
degradation_toolkit/add_degradation_various.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import random
4
+ import cv2
5
+ import math
6
+ from scipy import special
7
+ from skimage import restoration
8
+
9
+ import torch
10
+ from torch.nn import functional as F
11
+ from torchvision.utils import make_grid
12
+
13
+
14
+ def uint2single(img):
15
+ return np.float32(img/255.)
16
+
17
+
18
+ def single2uint(img):
19
+ return np.uint8((img.clip(0, 1)*255.).round())
20
+
21
+
22
+ def img2tensor(imgs, bgr2rgb=True, float32=True):
23
+ """Numpy array to tensor.
24
+ Args:
25
+ imgs (list[ndarray] | ndarray): Input images.
26
+ bgr2rgb (bool): Whether to change bgr to rgb.
27
+ float32 (bool): Whether to change to float32.
28
+ Returns:
29
+ list[tensor] | tensor: Tensor images. If returned results only have
30
+ one element, just return tensor.
31
+ """
32
+
33
+ def _totensor(img, bgr2rgb, float32):
34
+ if img.shape[2] == 3 and bgr2rgb:
35
+ if img.dtype == 'float64':
36
+ img = img.astype('float32')
37
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
38
+ img = torch.from_numpy(img.transpose(2, 0, 1))
39
+ if float32:
40
+ img = img.float()
41
+ return img
42
+
43
+ if isinstance(imgs, list):
44
+ return [_totensor(img, bgr2rgb, float32) for img in imgs]
45
+ else:
46
+ return _totensor(imgs, bgr2rgb, float32)
47
+
48
+
49
+ def tensor2img(tensor, rgb2bgr=True, out_type=np.uint8, min_max=(0, 1)):
50
+ """Convert torch Tensors into image numpy arrays.
51
+ After clamping to [min, max], values will be normalized to [0, 1].
52
+ Args:
53
+ tensor (Tensor or list[Tensor]): Accept shapes:
54
+ 1) 4D mini-batch Tensor of shape (B x 3/1 x H x W);
55
+ 2) 3D Tensor of shape (3/1 x H x W);
56
+ 3) 2D Tensor of shape (H x W).
57
+ Tensor channel should be in RGB order.
58
+ rgb2bgr (bool): Whether to change rgb to bgr.
59
+ out_type (numpy type): output types. If ``np.uint8``, transform outputs
60
+ to uint8 type with range [0, 255]; otherwise, float type with
61
+ range [0, 1]. Default: ``np.uint8``.
62
+ min_max (tuple[int]): min and max values for clamp.
63
+ Returns:
64
+ (Tensor or list): 3D ndarray of shape (H x W x C) OR 2D ndarray of
65
+ shape (H x W). The channel order is BGR.
66
+ """
67
+ if not (torch.is_tensor(tensor) or (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
68
+ raise TypeError(f'tensor or list of tensors expected, got {type(tensor)}')
69
+
70
+ if torch.is_tensor(tensor):
71
+ tensor = [tensor]
72
+ result = []
73
+ for _tensor in tensor:
74
+ _tensor = _tensor.squeeze(0).float().detach().cpu().clamp_(*min_max)
75
+ _tensor = (_tensor - min_max[0]) / (min_max[1] - min_max[0])
76
+
77
+ n_dim = _tensor.dim()
78
+ if n_dim == 4:
79
+ img_np = make_grid(_tensor, nrow=int(math.sqrt(_tensor.size(0))), normalize=False).numpy()
80
+ img_np = img_np.transpose(1, 2, 0)
81
+ if rgb2bgr:
82
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
83
+ elif n_dim == 3:
84
+ img_np = _tensor.numpy()
85
+ img_np = img_np.transpose(1, 2, 0)
86
+ if img_np.shape[2] == 1: # gray image
87
+ img_np = np.squeeze(img_np, axis=2)
88
+ else:
89
+ if rgb2bgr:
90
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
91
+ elif n_dim == 2:
92
+ img_np = _tensor.numpy()
93
+ else:
94
+ raise TypeError(f'Only support 4D, 3D or 2D tensor. But received with dimension: {n_dim}')
95
+ if out_type == np.uint8:
96
+ # Unlike MATLAB, numpy.unit8() WILL NOT round by default.
97
+ img_np = (img_np * 255.0).round()
98
+ img_np = img_np.astype(out_type)
99
+ result.append(img_np)
100
+ if len(result) == 1:
101
+ result = result[0]
102
+ return result
103
+
104
+
105
+ def get_noise(img, value=10):
106
+
107
+ noise = np.random.uniform(0, 256, img.shape[0:2])
108
+
109
+ v = value * 0.01
110
+ noise[np.where(noise < (256 - v))] = 0
111
+
112
+ k = np.array([[0, 0.1, 0],
113
+ [0.1, 8, 0.1],
114
+ [0, 0.1, 0]])
115
+
116
+ noise = cv2.filter2D(noise, -1, k)
117
+
118
+ '''cv2.imshow('img',noise)
119
+ cv2.waitKey()
120
+ cv2.destroyWindow('img')'''
121
+ return noise
122
+
123
+
124
+ def rain_blur(noise, length=10, angle=0, w=1):
125
+
126
+ trans = cv2.getRotationMatrix2D((length / 2, length / 2), angle - 45, 1 - length / 100.0)
127
+ dig = np.diag(np.ones(length))
128
+ k = cv2.warpAffine(dig, trans, (length, length))
129
+ k = cv2.GaussianBlur(k, (w, w), 0)
130
+
131
+ blurred = cv2.filter2D(noise, -1, k)
132
+
133
+ cv2.normalize(blurred, blurred, 0, 255, cv2.NORM_MINMAX)
134
+ blurred = np.array(blurred, dtype=np.uint8)
135
+
136
+ rain = np.expand_dims(blurred, 2)
137
+ blurred = np.repeat(rain, 3, 2)
138
+
139
+ return blurred
140
+
141
+
142
+ def add_rain(img,value):
143
+ if np.max(img) > 1:
144
+ pass
145
+ else:
146
+ img = img*255
147
+
148
+
149
+ w, h, c = img.shape
150
+ h = h - (h % 4)
151
+ w = w - (w % 4)
152
+ img = img[0:w, 0:h, :]
153
+
154
+
155
+ w = np.random.choice([3, 5, 7, 9, 11], p=[0.2, 0.2, 0.2, 0.2, 0.2])
156
+ length = np.random.randint(30, 41)
157
+ angle = np.random.randint(-45, 45)
158
+
159
+ noise = get_noise(img, value=value)
160
+ rain = rain_blur(noise, length=length, angle=angle, w=w)
161
+
162
+ img = img.astype('float32') + rain
163
+ np.clip(img, 0, 255, out=img)
164
+ img = img/255.0
165
+ return img
166
+
167
+
168
+ def add_rain_range(img, value_min, value_max):
169
+ value = np.random.randint(value_min, value_max)
170
+ if np.max(img) > 1:
171
+ pass
172
+ else:
173
+ img = img*255
174
+
175
+
176
+ w, h, c = img.shape
177
+ h = h - (h % 4)
178
+ w = w - (w % 4)
179
+ img = img[0:w, 0:h, :]
180
+
181
+
182
+ w = np.random.choice([3, 5, 7, 9, 11], p=[0.2, 0.2, 0.2, 0.2, 0.2])
183
+ length = np.random.randint(30, 41)
184
+ angle = np.random.randint(-45, 45)
185
+
186
+ noise = get_noise(img, value=value)
187
+ rain = rain_blur(noise, length=length, angle=angle, w=w)
188
+
189
+ img = img.astype('float32') + rain
190
+ np.clip(img, 0, 255, out=img)
191
+ img = img/255.0
192
+ return img
193
+
194
+
195
+ def add_Poisson_noise(img, level=2):
196
+ # input range[0, 1]
197
+ vals = 10**(level)
198
+ img = np.random.poisson(img * vals).astype(np.float32) / vals
199
+ img = np.clip(img, 0.0, 1.0)
200
+ return img
201
+
202
+
203
+ def add_Gaussian_noise(img, level=20):
204
+ # input range[0, 1]
205
+ noise_level = level / 255.0
206
+ noise_map = np.random.normal(loc=0.0, scale=1.0, size=img.shape)*noise_level
207
+ img += noise_map
208
+ img = np.clip(img, 0.0, 1.0)
209
+ return img
210
+
211
+
212
+ def add_Gaussian_noise_range(img, min_level=10, max_level=50):
213
+ # input range[0, 1]
214
+ level = random.uniform(min_level, max_level)
215
+ noise_level = level / 255.0
216
+ noise_map = np.random.normal(loc=0.0, scale=1.0, size=img.shape)*noise_level
217
+ img += noise_map
218
+ img = np.clip(img, 0.0, 1.0)
219
+ return img
220
+
221
+
222
+ def add_sp_noise(img, snr=0.95, salt_pro=0.5):
223
+ # input range[0, 1]
224
+ output = np.copy(img)
225
+ for i in range(img.shape[0]):
226
+ for j in range(img.shape[1]):
227
+ rdn = random.random()
228
+ if rdn < snr:
229
+ output[i][j] = img[i][j]
230
+ else:
231
+ rdn = random.random()
232
+ if rdn < salt_pro:
233
+ output[i][j] = 1
234
+ else:
235
+ output[i][j] = 0
236
+
237
+ return output
238
+
239
+
240
+ def add_JPEG_noise(img, level):
241
+
242
+ quality_factor = level
243
+ img = single2uint(img)
244
+ _, encimg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor])
245
+ img = cv2.imdecode(encimg, 1)
246
+ img = uint2single(img)
247
+
248
+ return img
249
+
250
+
251
+ def add_JPEG_noise_range(img, level_min, level_max):
252
+
253
+ quality_factor = random.randint(level_min, level_max)
254
+ img = single2uint(img)
255
+ _, encimg = cv2.imencode('.jpg', img, [int(cv2.IMWRITE_JPEG_QUALITY), quality_factor])
256
+ img = cv2.imdecode(encimg, 1)
257
+ img = uint2single(img)
258
+
259
+ return img
260
+
261
+
262
+ def circular_lowpass_kernel(cutoff, kernel_size, pad_to=0):
263
+ """2D sinc filter, ref: https://dsp.stackexchange.com/questions/58301/2-d-circularly-symmetric-low-pass-filter
264
+
265
+ Args:
266
+ cutoff (float): cutoff frequency in radians (pi is max)
267
+ kernel_size (int): horizontal and vertical size, must be odd.
268
+ pad_to (int): pad kernel size to desired size, must be odd or zero.
269
+ """
270
+ assert kernel_size % 2 == 1, 'Kernel size must be an odd number.'
271
+ kernel = np.fromfunction(
272
+ lambda x, y: cutoff * special.j1(cutoff * np.sqrt(
273
+ (x - (kernel_size - 1) / 2) ** 2 + (y - (kernel_size - 1) / 2) ** 2)) / ((2 * np.pi * np.sqrt(
274
+ (x - (kernel_size - 1) / 2) ** 2 + (y - (kernel_size - 1) / 2) ** 2)) + 1e-9), [kernel_size, kernel_size])
275
+ kernel[(kernel_size - 1) // 2, (kernel_size - 1) // 2] = cutoff ** 2 / (4 * np.pi)
276
+ kernel = kernel / np.sum(kernel)
277
+ if pad_to > kernel_size:
278
+ pad_size = (pad_to - kernel_size) // 2
279
+ kernel = np.pad(kernel, ((pad_size, pad_size), (pad_size, pad_size)))
280
+ return kernel
281
+
282
+
283
+ def filter2D(img, kernel):
284
+ """PyTorch version of cv2.filter2D
285
+ Args:
286
+ img (Tensor): (b, c, h, w)
287
+ kernel (Tensor): (b, k, k)
288
+ """
289
+ k = kernel.size(-1)
290
+ b, c, h, w = img.size()
291
+ if k % 2 == 1:
292
+ img = F.pad(img, (k // 2, k // 2, k // 2, k // 2), mode='reflect')
293
+ else:
294
+ raise ValueError('Wrong kernel size')
295
+
296
+ ph, pw = img.size()[-2:]
297
+
298
+ if kernel.size(0) == 1:
299
+ # apply the same kernel to all batch images
300
+ img = img.view(b * c, 1, ph, pw)
301
+ kernel = kernel.view(1, 1, k, k)
302
+ return F.conv2d(img, kernel, padding=0).view(b, c, h, w)
303
+ else:
304
+ img = img.view(1, b * c, ph, pw)
305
+ kernel = kernel.view(b, 1, k, k).repeat(1, c, 1, 1).view(b * c, 1, k, k)
306
+ return F.conv2d(img, kernel, groups=b * c).view(b, c, h, w)
307
+
308
+
309
+ def sinc(img, kernel_size,omega_c):
310
+
311
+ sinc_kernel = circular_lowpass_kernel(omega_c, kernel_size, pad_to=21)
312
+ sinc_kernel = torch.FloatTensor(sinc_kernel)
313
+
314
+ img = filter2D(img,sinc_kernel)
315
+
316
+ return img
317
+
318
+
319
+ def add_ringing(img):
320
+ # input: [0, 1]
321
+ img = img2tensor([img])[0].unsqueeze(0)
322
+ ks = 15
323
+ omega_c = round(1.2, 2)
324
+ img = sinc(img, ks, omega_c)
325
+ img = torch.clamp((img * 255.0).round(), 0, 255) / 255.
326
+ img = tensor2img(img, min_max=(0, 1))
327
+ img = img/255.0
328
+ return img
329
+
330
+
331
+ def low_light(img, lum_scale):
332
+ img = img*lum_scale
333
+ return img
334
+
335
+
336
+ def low_light_range(img):
337
+ lum_scale = random.uniform(0.1, 0.5)
338
+ img = img*lum_scale
339
+ return img
340
+
341
+
342
+ def iso_GaussianBlur(img, window, sigma):
343
+ img = cv2.GaussianBlur(img.copy(), (window, window), sigma)
344
+ return img
345
+
346
+
347
+ def iso_GaussianBlur_range(img, window, min_sigma=2, max_sigma=4):
348
+ sigma = random.uniform(min_sigma, max_sigma)
349
+ img = cv2.GaussianBlur(img.copy(), (window, window), sigma)
350
+ return img
351
+
352
+
353
+ def add_resize(img):
354
+ ori_H, ori_W = img.shape[0], img.shape[1]
355
+ rnum = np.random.rand()
356
+ if rnum > 0.8: # up
357
+ sf1 = random.uniform(1, 2)
358
+ elif rnum < 0.7: # down
359
+ sf1 = random.uniform(0.2, 1)
360
+ else:
361
+ sf1 = 1.0
362
+ img = cv2.resize(img, (int(sf1*img.shape[1]), int(sf1*img.shape[0])), interpolation=random.choice([1, 2, 3]))
363
+ img = cv2.resize(img, (int(ori_W), int(ori_H)), interpolation=random.choice([1, 2, 3]))
364
+
365
+ img = np.clip(img, 0.0, 1.0)
366
+
367
+ return img
368
+
369
+
370
+ def r_l(img):
371
+ img = img2tensor([img],bgr2rgb=False)[0].unsqueeze(0)
372
+ psf = np.ones((1, 1, 5, 5))
373
+ psf = psf / psf.sum()
374
+ img = img.numpy()
375
+ img = np.pad(img, ((0, 0), (0, 0), (7, 7), (7, 7)), 'linear_ramp')
376
+ img = restoration.richardson_lucy(img, psf, 1)
377
+ img = img[:, :, 7:-7, 7:-7]
378
+ img = torch.from_numpy(img)
379
+ img = img.squeeze(0).numpy().transpose(1, 2, 0)
380
+ return img
381
+
382
+
383
+ def inpainting(img,l_num,l_thick):
384
+
385
+ ori_h, ori_w = img.shape[0], img.shape[1]
386
+ mask = np.zeros((ori_h, ori_w, 3), np.uint8)
387
+ col = random.choice(['white', 'black'])
388
+ while (l_num):
389
+ x1, y1 = random.randint(0, ori_w), random.randint(0, ori_h)
390
+ x2, y2 = random.randint(0, ori_w), random.randint(0, ori_h)
391
+ pts = np.array([[x1, y1], [x2, y2]], np.int32)
392
+ pts = pts.reshape((-1, 1, 2))
393
+ mask = cv2.polylines(mask, [pts], 0, (1, 1, 1), l_thick)
394
+ l_num -= 1
395
+
396
+ if col == 'white':
397
+ img = np.clip(img + mask, 0, 1)
398
+ else:
399
+ img = np.clip(img - mask, 0, 1)
400
+
401
+ return img
degradation_toolkit/frost/frost1.png ADDED

Git LFS Details

  • SHA256: ff9f907860bd7a835d459e32f9d588062b7f61ee267343cc7222b56753a14755
  • Pointer size: 132 Bytes
  • Size of remote file: 1.2 MB
degradation_toolkit/frost/frost2.png ADDED

Git LFS Details

  • SHA256: fe211a89b336999c207a852ce05818d4545d0b57c5beadd824b4cc9d9a9b6137
  • Pointer size: 131 Bytes
  • Size of remote file: 299 kB
degradation_toolkit/frost/frost3.png ADDED

Git LFS Details

  • SHA256: 2d0d50b4a9bb213f38b024ef7768731bb83cc08d2f26b5766bbc167cdfa0e504
  • Pointer size: 131 Bytes
  • Size of remote file: 299 kB
degradation_toolkit/frost/frost4.jpg ADDED

Git LFS Details

  • SHA256: 3f8b91ca1a9fa7167b09e773da53f5ae60d0a1fd88f02a783f6e328a72887f6e
  • Pointer size: 130 Bytes
  • Size of remote file: 36.7 kB
degradation_toolkit/frost/frost5.jpg ADDED

Git LFS Details

  • SHA256: 5fc6a19df4a429ba68abdcc8f8a4278d4c9f81c9ccafd2c92ab0c8cf8992ebd2
  • Pointer size: 131 Bytes
  • Size of remote file: 155 kB
degradation_toolkit/frost/frost6.jpg ADDED

Git LFS Details

  • SHA256: 1f92b2f48408748085b68dd81d816ef239f42cef3029c25d041fcb6760fb4f25
  • Pointer size: 130 Bytes
  • Size of remote file: 90.2 kB
degradation_toolkit/image_operators.py ADDED
@@ -0,0 +1,420 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import numpy as np
4
+ import argparse
5
+ from skimage.filters import gaussian
6
+ from scipy.ndimage.interpolation import map_coordinates
7
+ from tqdm import tqdm
8
+ from PIL import Image
9
+
10
+
11
+ def single2uint(img):
12
+ return np.uint8((img.clip(0, 1)*255.).round())
13
+
14
+
15
+ def uint2single(img):
16
+ return np.float32(img/255.)
17
+
18
+
19
+ def Laplacian_edge_detector(img):
20
+ # input: [0, 1]
21
+ # return: [0, 1] (H, W, 3)
22
+ img = np.clip(img*255, 0, 255).astype(np.uint8) # (H, W, 3)
23
+ img = cv2.GaussianBlur(img, (3, 3), 0)
24
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
25
+ img = cv2.Laplacian(img, cv2.CV_16S) # (H, W)
26
+ img = cv2.convertScaleAbs(img)
27
+ img = img.astype(np.float32) / 255.
28
+ img = np.expand_dims(img, 2).repeat(3, axis=2) # (H, W, 3)
29
+ return img
30
+
31
+
32
+ def Laplacian_edge_detector_uint8(img):
33
+ # input: [0, 255]
34
+ # return: [0, 255] (H, W, 3)
35
+ img = cv2.GaussianBlur(img, (3, 3), 0)
36
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
37
+ img = cv2.Laplacian(img, cv2.CV_16S) # (H, W)
38
+ img = cv2.convertScaleAbs(img)
39
+ img = np.expand_dims(img, 2).repeat(3, axis=2) # (H, W, 3)
40
+ return img
41
+
42
+
43
+ def Canny_edge_detector(img):
44
+ # input: [0, 1]
45
+ # return: [0, 1] (H, W, 3)
46
+ img = np.clip(img*255, 0, 255).astype(np.uint8) # (H, W, 3)
47
+ img = cv2.GaussianBlur(img, (3, 3), 0)
48
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
49
+ img = cv2.Canny(img, 50, 200) # (H, W)
50
+ img = cv2.convertScaleAbs(img)
51
+ img = img.astype(np.float32) / 255.
52
+ img = np.expand_dims(img, 2).repeat(3, axis=2) # (H, W, 3)
53
+ return img
54
+
55
+
56
+ def Canny_edge_detector_uint8(img):
57
+ # input: [0, 255]
58
+ # return: [0, 255] (H, W, 3)
59
+ img = cv2.GaussianBlur(img, (3, 3), 0)
60
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
61
+ img = cv2.Canny(img, 50, 200) # (H, W)
62
+ img = cv2.convertScaleAbs(img)
63
+ img = np.expand_dims(img, 2).repeat(3, axis=2) # (H, W, 3)
64
+ return img
65
+
66
+
67
+ def Sobel_edge_detector(img):
68
+ # input: [0, 1]
69
+ # return: [0, 1] (H, W, 3)
70
+ img = np.clip(img*255, 0, 255).astype(np.uint8) # (H, W, 3)
71
+ img = cv2.GaussianBlur(img, (3, 3), 0)
72
+ img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
73
+ img = cv2.Sobel(img, cv2.CV_16S, 1, 1) # (H, W)
74
+ img = cv2.convertScaleAbs(img)
75
+ img = img.astype(np.float32) / 255.
76
+ img = np.expand_dims(img, 2).repeat(3, axis=2) # (H, W, 3)
77
+ return img
78
+
79
+
80
+ def erosion(img, kernel_size=5):
81
+ kernel = np.ones((kernel_size, kernel_size), np.uint8)
82
+ img = cv2.erode(img, kernel, iterations=1)
83
+ return img
84
+
85
+
86
+ def dilatation(img, kernel_size=5):
87
+ kernel = np.ones((kernel_size, kernel_size), np.uint8)
88
+ img = cv2.dilate(img, kernel, iterations=1)
89
+ return img
90
+
91
+
92
+ def opening(img):
93
+ return dilatation(erosion(img))
94
+
95
+
96
+ def closing(img):
97
+ return erosion(dilatation(img))
98
+
99
+
100
+ def morphological_gradient(img):
101
+ return dilatation(img) - erosion(img)
102
+
103
+
104
+ def top_hat(img):
105
+ return img - opening(img)
106
+
107
+
108
+ def black_hat(img):
109
+ return closing(img) - img
110
+
111
+
112
+ def adjust_contrast(image, clip_limit=2.0, tile_grid_size=(8, 8)):
113
+
114
+ image = single2uint(image)
115
+ lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB)
116
+
117
+ l, a, b = cv2.split(lab)
118
+
119
+ clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_grid_size)
120
+ l_eq = clahe.apply(l)
121
+
122
+ lab_eq = cv2.merge((l_eq, a, b))
123
+ result = cv2.cvtColor(lab_eq, cv2.COLOR_LAB2BGR)
124
+
125
+ result = uint2single(result)
126
+ return result
127
+
128
+
129
+ def embossing(img):
130
+ kernel = np.array([[0, -1, -1],
131
+ [1, 0, -1],
132
+ [1, 1, 0]])
133
+ return cv2.filter2D(img, -1, kernel)
134
+
135
+
136
+ def hough_transform_line_detection(img):
137
+ img = single2uint(img)
138
+ dst = cv2.Canny(img, 50, 200, apertureSize=3)
139
+ cdst = cv2.cvtColor(dst, cv2.COLOR_GRAY2BGR)
140
+ lines = cv2.HoughLinesP(dst, 1, np.pi / 180, 230, None, 0, 0)
141
+ if lines is not None:
142
+ for i in range(0, len(lines)):
143
+ rho = lines[i][0][0]
144
+ theta = lines[i][0][1]
145
+ a = np.cos(theta)
146
+ b = np.sin(theta)
147
+
148
+ x0 = a * rho
149
+ y0 = b * rho
150
+ pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
151
+
152
+ pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
153
+ cv2.line(img, pt1, pt2, (0, 0, 255), 3, cv2.LINE_AA)
154
+
155
+ return uint2single(img)
156
+
157
+
158
+ def hough_circle_detection(img):
159
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
160
+ circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 100, param1=100, param2=30, minRadius=50, maxRadius=200)
161
+ circles = np.uint16(np.around(circles))
162
+ for i in circles[0, :]:
163
+ cv2.circle(img, (i[0], i[1]), i[2], (0, 0, 255), 2)
164
+ return img
165
+
166
+
167
+ def disk(radius, alias_blur=0.1, dtype=np.float32):
168
+ if radius <= 8:
169
+ L = np.arange(-8, 8 + 1)
170
+ ksize = (3, 3)
171
+ else:
172
+ L = np.arange(-radius, radius + 1)
173
+ ksize = (5, 5)
174
+ X, Y = np.meshgrid(L, L)
175
+ aliased_disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
176
+ aliased_disk /= np.sum(aliased_disk)
177
+
178
+ # supersample disk to antialias
179
+ return cv2.GaussianBlur(aliased_disk, ksize=ksize, sigmaX=alias_blur)
180
+
181
+
182
+ def defocus_blur(image, level=(1, 0.1)):
183
+ c = level
184
+ kernel = disk(radius=c[0], alias_blur=c[1])
185
+
186
+ channels = []
187
+ for d in range(3):
188
+ channels.append(cv2.filter2D(image[:, :, d], -1, kernel))
189
+ channels = np.array(channels).transpose((1, 2, 0)) # 3x64x64 -> 64x64x3
190
+
191
+ return np.clip(channels, 0, 1)
192
+
193
+
194
+ def masks_CFA_Bayer(shape):
195
+ pattern = "RGGB"
196
+ channels = dict((channel, np.zeros(shape)) for channel in "RGB")
197
+ for channel, (y, x) in zip(pattern, [(0, 0), (0, 1), (1, 0), (1, 1)]):
198
+ channels[channel][y::2, x::2] = 1
199
+ return tuple(channels[c].astype(bool) for c in "RGB")
200
+
201
+
202
+ def cfa4_to_rgb(CFA4):
203
+ RGB = np.zeros((CFA4.shape[0]*2, CFA4.shape[1]*2, 3), dtype=np.uint8)
204
+ RGB[0::2, 0::2, 0] = CFA4[:, :, 0] # R
205
+ RGB[0::2, 1::2, 1] = CFA4[:, :, 1] # G on R row
206
+ RGB[1::2, 0::2, 1] = CFA4[:, :, 2] # G on B row
207
+ RGB[1::2, 1::2, 2] = CFA4[:, :, 3] # B
208
+
209
+ return RGB
210
+
211
+
212
+ def mosaic_CFA_Bayer(RGB):
213
+ RGB = single2uint(RGB)
214
+ R_m, G_m, B_m = masks_CFA_Bayer(RGB.shape[0:2])
215
+ mask = np.concatenate(
216
+ (R_m[..., np.newaxis], G_m[..., np.newaxis], B_m[..., np.newaxis]), axis=-1
217
+ )
218
+ mosaic = np.multiply(mask, RGB) # mask*RGB
219
+ CFA = mosaic.sum(2).astype(np.uint8)
220
+
221
+ CFA4 = np.zeros((RGB.shape[0] // 2, RGB.shape[1] // 2, 4), dtype=np.uint8)
222
+ CFA4[:, :, 0] = CFA[0::2, 0::2]
223
+ CFA4[:, :, 1] = CFA[0::2, 1::2]
224
+ CFA4[:, :, 2] = CFA[1::2, 0::2]
225
+ CFA4[:, :, 3] = CFA[1::2, 1::2]
226
+
227
+ rgb = cfa4_to_rgb(CFA4)
228
+ rgb = uint2single(rgb)
229
+ return rgb
230
+
231
+
232
+ def simulate_barrel_distortion(image, k1=0.02, k2=0.01):
233
+ height, width = image.shape[:2]
234
+ mapx, mapy = np.meshgrid(np.arange(width), np.arange(height))
235
+ mapx = 2 * mapx / (width - 1) - 1
236
+ mapy = 2 * mapy / (height - 1) - 1
237
+ r = np.sqrt(mapx**2 + mapy**2)
238
+ mapx = mapx * (1 + k1 * r**2 + k2 * r**4)
239
+ mapy = mapy * (1 + k1 * r**2 + k2 * r**4)
240
+ mapx = (mapx + 1) * (width - 1) / 2
241
+ mapy = (mapy + 1) * (height - 1) / 2
242
+ distorted_image = cv2.remap(image, mapx.astype(np.float32), mapy.astype(np.float32), cv2.INTER_LINEAR)
243
+ return distorted_image
244
+
245
+
246
+ def simulate_pincushion_distortion(image, k1=-0.02, k2=-0.01):
247
+ height, width = image.shape[:2]
248
+ mapx, mapy = np.meshgrid(np.arange(width), np.arange(height))
249
+ mapx = 2 * mapx / (width - 1) - 1
250
+ mapy = 2 * mapy / (height - 1) - 1
251
+ r = np.sqrt(mapx**2 + mapy**2)
252
+ mapx = mapx * (1 + k1 * r**2 + k2 * r**4)
253
+ mapy = mapy * (1 + k1 * r**2 + k2 * r**4)
254
+ mapx = (mapx + 1) * (width - 1) / 2
255
+ mapy = (mapy + 1) * (height - 1) / 2
256
+ distorted_image = cv2.remap(image, mapx.astype(np.float32), mapy.astype(np.float32), cv2.INTER_LINEAR)
257
+ return distorted_image
258
+
259
+
260
+ def rgb2gray(rgb):
261
+ return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140])
262
+
263
+
264
+ def spatter(x, severity=1):
265
+ c = [(0.65, 0.3, 4, 0.69, 0.6, 0),
266
+ (0.65, 0.3, 3, 0.68, 0.6, 0),
267
+ (0.65, 0.3, 2, 0.68, 0.5, 0),
268
+ (0.65, 0.3, 1, 0.65, 1.5, 1),
269
+ (0.67, 0.4, 1, 0.65, 1.5, 1)][severity - 1]
270
+ x_PIL = x
271
+ x = np.array(x, dtype=np.float32) / 255.
272
+
273
+ liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])
274
+
275
+ liquid_layer = gaussian(liquid_layer, sigma=c[2])
276
+ liquid_layer[liquid_layer < c[3]] = 0
277
+ if c[5] == 0:
278
+ liquid_layer = (liquid_layer * 255).astype(np.uint8)
279
+ dist = 255 - cv2.Canny(liquid_layer, 50, 150)
280
+ dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5)
281
+ _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC)
282
+ dist = cv2.blur(dist, (3, 3)).astype(np.uint8)
283
+ dist = cv2.equalizeHist(dist)
284
+ ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]])
285
+ dist = cv2.filter2D(dist, cv2.CV_8U, ker)
286
+ dist = cv2.blur(dist, (3, 3)).astype(np.float32)
287
+
288
+ m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA)
289
+ m /= np.max(m, axis=(0, 1))
290
+ m *= c[4]
291
+ # water is pale turqouise
292
+ color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]),
293
+ 238 / 255. * np.ones_like(m[..., :1]),
294
+ 238 / 255. * np.ones_like(m[..., :1])), axis=2)
295
+
296
+ color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA)
297
+
298
+ if len(x.shape) < 3 or x.shape[2] < 3:
299
+ add_spatter_color = cv2.cvtColor(np.clip(m * color, 0, 1),
300
+ cv2.COLOR_BGRA2BGR)
301
+ add_spatter_gray = rgb2gray(add_spatter_color)
302
+
303
+ return (np.clip(x + add_spatter_gray, 0, 1) * 255).astype(np.uint8)
304
+
305
+ else:
306
+
307
+ x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA)
308
+
309
+ return (cv2.cvtColor(np.clip(x + m * color, 0, 1),
310
+ cv2.COLOR_BGRA2BGR) * 255).astype(np.uint8)
311
+ else:
312
+ m = np.where(liquid_layer > c[3], 1, 0)
313
+ m = gaussian(m.astype(np.float32), sigma=c[4])
314
+ m[m < 0.8] = 0
315
+
316
+ x_rgb = np.array(x_PIL)
317
+
318
+ # mud brown
319
+ color = np.concatenate((63 / 255. * np.ones_like(x_rgb[..., :1]),
320
+ 42 / 255. * np.ones_like(x_rgb[..., :1]),
321
+ 20 / 255. * np.ones_like(x_rgb[..., :1])),
322
+ axis=2)
323
+ color *= m[..., np.newaxis]
324
+ if len(x.shape) < 3 or x.shape[2] < 3:
325
+ x *= (1 - m)
326
+ return (np.clip(x + rgb2gray(color), 0, 1) * 255).astype(np.uint8)
327
+
328
+ else:
329
+ x *= (1 - m[..., np.newaxis])
330
+ return (np.clip(x + color, 0, 1) * 255).astype(np.uint8)
331
+
332
+
333
+ # mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5
334
+ def elastic_transform(image, severity=3):
335
+ image = np.array(image, dtype=np.float32) / 255.
336
+ shape = image.shape
337
+ shape_size = shape[:2]
338
+
339
+ sigma = np.array(shape_size) * 0.01
340
+ alpha = [250 * 0.05, 250 * 0.065, 250 * 0.085, 250 * 0.1, 250 * 0.12][
341
+ severity - 1]
342
+ max_dx = shape[0] * 0.005
343
+ max_dy = shape[0] * 0.005
344
+
345
+ dx = (gaussian(np.random.uniform(-max_dx, max_dx, size=shape[:2]),
346
+ sigma, mode='reflect', truncate=3) * alpha).astype(
347
+ np.float32)
348
+ dy = (gaussian(np.random.uniform(-max_dy, max_dy, size=shape[:2]),
349
+ sigma, mode='reflect', truncate=3) * alpha).astype(
350
+ np.float32)
351
+
352
+ if len(image.shape) < 3 or image.shape[2] < 3:
353
+ x, y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))
354
+ indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx, (-1, 1))
355
+ else:
356
+ dx, dy = dx[..., np.newaxis], dy[..., np.newaxis]
357
+ x, y, z = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]),
358
+ np.arange(shape[2]))
359
+ indices = np.reshape(y + dy, (-1, 1)), np.reshape(x + dx,
360
+ (-1, 1)), np.reshape(
361
+ z, (-1, 1))
362
+ return np.clip(
363
+ map_coordinates(image, indices, order=1, mode='reflect').reshape(
364
+ shape), 0, 1) * 255
365
+
366
+
367
+ def frost(x, severity=2):
368
+ c = [(1, 0.4),
369
+ (0.8, 0.6),
370
+ (0.7, 0.7),
371
+ (0.65, 0.7),
372
+ (0.6, 0.75)][severity - 1]
373
+
374
+ idx = np.random.randint(5)
375
+ filename = [os.path.join("degradation_toolkit/frost", 'frost1.png'),
376
+ os.path.join("degradation_toolkit/frost", 'frost2.png'),
377
+ os.path.join("degradation_toolkit/frost", 'frost3.png'),
378
+ os.path.join("degradation_toolkit/frost", 'frost4.jpg'),
379
+ os.path.join("degradation_toolkit/frost", 'frost5.jpg'),
380
+ os.path.join("degradation_toolkit/frost", 'frost6.jpg')][idx]
381
+ frost = Image.open(filename)
382
+ frost = frost.convert("RGB")
383
+ frost = np.array(frost)
384
+ # frost = cv2.imread(filename)
385
+ frost = uint2single(frost)
386
+ frost_shape = frost.shape
387
+ x_shape = np.array(x).shape
388
+
389
+ # resize the frost image so it fits to the image dimensions
390
+ scaling_factor = 1
391
+ if frost_shape[0] >= x_shape[0] and frost_shape[1] >= x_shape[1]:
392
+ scaling_factor = 1
393
+ elif frost_shape[0] < x_shape[0] and frost_shape[1] >= x_shape[1]:
394
+ scaling_factor = x_shape[0] / frost_shape[0]
395
+ elif frost_shape[0] >= x_shape[0] and frost_shape[1] < x_shape[1]:
396
+ scaling_factor = x_shape[1] / frost_shape[1]
397
+ elif frost_shape[0] < x_shape[0] and frost_shape[1] < x_shape[
398
+ 1]: # If both dims are too small, pick the bigger scaling factor
399
+ scaling_factor_0 = x_shape[0] / frost_shape[0]
400
+ scaling_factor_1 = x_shape[1] / frost_shape[1]
401
+ scaling_factor = np.maximum(scaling_factor_0, scaling_factor_1)
402
+
403
+ scaling_factor *= 1.1
404
+ new_shape = (int(np.ceil(frost_shape[1] * scaling_factor)),
405
+ int(np.ceil(frost_shape[0] * scaling_factor)))
406
+ frost_rescaled = cv2.resize(frost, dsize=new_shape,
407
+ interpolation=cv2.INTER_CUBIC)
408
+
409
+ # randomly crop
410
+ x_start, y_start = np.random.randint(0, frost_rescaled.shape[0] - x_shape[
411
+ 0]), np.random.randint(0, frost_rescaled.shape[1] - x_shape[1])
412
+
413
+ if len(x_shape) < 3 or x_shape[2] < 3:
414
+ frost_rescaled = frost_rescaled[x_start:x_start + x_shape[0],
415
+ y_start:y_start + x_shape[1]]
416
+ frost_rescaled = rgb2gray(frost_rescaled)
417
+ else:
418
+ frost_rescaled = frost_rescaled[x_start:x_start + x_shape[0],
419
+ y_start:y_start + x_shape[1]][..., [2, 1, 0]]
420
+ return c[0] * np.array(x) + c[1] * frost_rescaled
degradation_toolkit/x_distortion/__init__.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .blur import *
2
+ from .brightness import *
3
+ from .quantization import *
4
+ from .compression import *
5
+ from .contrast import *
6
+ from .noise import *
7
+ from .oversharpen import *
8
+ from .pixelate import *
9
+ from .saturate import *
10
+
11
+
12
+ def add_distortion(img, severity=1, distortion_name=None):
13
+ """This function returns a distorted version of the given image.
14
+
15
+ @param img (np.ndarray, unit8): Input image, H x W x 3, RGB, [0, 255]
16
+ @param severity: Severity of distortion, [1, 5]
17
+ @distortion_name:
18
+ @return: Degraded image (np.ndarray, unit8), H x W x 3, RGB, [0, 255]
19
+ """
20
+
21
+ if not isinstance(img, np.ndarray):
22
+ raise AttributeError('Expecting type(img) to be numpy.ndarray')
23
+ if not (img.dtype.type is np.uint8):
24
+ raise AttributeError('Expecting img.dtype.type to be numpy.uint8')
25
+
26
+ if not (img.ndim in [2, 3]):
27
+ raise AttributeError('Expecting img.shape to be either (h x w) or (h x w x c)')
28
+ if img.ndim == 2:
29
+ img = np.stack((img,) * 3, axis=-1)
30
+
31
+ h, w, c = img.shape
32
+ if (h < 32 or w < 32):
33
+ raise AttributeError('The (w, h) must be at least 32 pixels')
34
+ if not (c in [1, 3]):
35
+ raise AttributeError('Expecting img to have either 1 or 3 chennels')
36
+ if c == 1:
37
+ img = np.stack((np.squeeze(img),) * 3, axis=-1)
38
+
39
+ if severity not in [1, 2, 3, 4, 5]:
40
+ raise AttributeError('The severity must be an integer in [1, 5]')
41
+
42
+ if distortion_name:
43
+ img_lq = globals()[distortion_name](img, severity)
44
+ else:
45
+ raise ValueError("The distortion_name must be passed")
46
+
47
+ return np.uint8(img_lq)
48
+
49
+
50
+ distortions_dict = {
51
+ "blur": [
52
+ "blur_gaussian",
53
+ "blur_motion",
54
+ "blur_glass",
55
+ "blur_lens",
56
+ "blur_zoom",
57
+ "blur_jitter",
58
+ ],
59
+ "noise": [
60
+ "noise_gaussian_RGB",
61
+ "noise_gaussian_YCrCb",
62
+ "noise_speckle",
63
+ "noise_spatially_correlated",
64
+ "noise_poisson",
65
+ "noise_impulse",
66
+ ],
67
+ "compression": [
68
+ "compression_jpeg",
69
+ "compression_jpeg_2000",
70
+ ],
71
+ "brighten": [
72
+ "brightness_brighten_shfit_HSV",
73
+ "brightness_brighten_shfit_RGB",
74
+ "brightness_brighten_gamma_HSV",
75
+ "brightness_brighten_gamma_RGB",
76
+ ],
77
+ "darken": [
78
+ "brightness_darken_shfit_HSV",
79
+ "brightness_darken_shfit_RGB",
80
+ "brightness_darken_gamma_HSV",
81
+ "brightness_darken_gamma_RGB",
82
+ ],
83
+ "contrast_strengthen": [
84
+ "contrast_strengthen_scale",
85
+ "contrast_strengthen_stretch",
86
+ ],
87
+ "contrast_weaken": [
88
+ "contrast_weaken_scale",
89
+ "contrast_weaken_stretch",
90
+ ],
91
+ "saturate_strengthen": [
92
+ "saturate_strengthen_HSV",
93
+ "saturate_strengthen_YCrCb",
94
+ ],
95
+ "saturate_weaken": [
96
+ "saturate_weaken_HSV",
97
+ "saturate_weaken_YCrCb",
98
+ ],
99
+ "oversharpen": [
100
+ "oversharpen",
101
+ ],
102
+ "pixelate": [
103
+ "pixelate",
104
+ ],
105
+ "quantization": [
106
+ "quantization_otsu",
107
+ "quantization_median",
108
+ "quantization_hist",
109
+ ],
110
+ "spatter": [
111
+ "spatter",
112
+ ],
113
+ }
114
+
115
+
116
+ def get_distortion_names(subset=None):
117
+ if subset in distortions_dict:
118
+ print(distortions_dict[subset])
119
+ else:
120
+ print(distortions_dict)
degradation_toolkit/x_distortion/blur.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+ from skimage.filters import gaussian
5
+ from .helper import (
6
+ _motion_blur,
7
+ shuffle_pixels_njit,
8
+ clipped_zoom,
9
+ gen_disk,
10
+ gen_lensmask,
11
+ )
12
+
13
+
14
+ def blur_gaussian(img, severity=1):
15
+ """
16
+ Gaussian Blur.
17
+ severity=[1, 2, 3, 4, 5] corresponding to sigma=[1, 2, 3, 4, 5].
18
+ severity mainly refer to KADID-10K and Imagecorruptions.
19
+
20
+ @param img: Input image, H x W x 3, value range [0, 255]
21
+ @param severity: Severity of distortion, [1, 5]
22
+ @return: Degraded image, H x W x 3, value range [0, 255]
23
+ """
24
+ c = [1, 2, 3, 4, 5][severity - 1]
25
+ img = np.array(img) / 255.
26
+ img = gaussian(img, sigma=c, channel_axis=-1)
27
+ img = np.clip(img, 0, 1) * 255
28
+ return img.round().astype(np.uint8)
29
+
30
+
31
+ def blur_gaussian_lensmask(img, severity=1):
32
+ """
33
+ Gaussian Blur with Lens Mask.
34
+ severity=[1, 2, 3, 4, 5] corresponding to
35
+ [gamma, sigma]=[[2.0, 2], [2.4, 4], [3.0, 6], [3.8, 8], [5.0, 10]].
36
+ severity mainly refer to PieAPP.
37
+
38
+ @param img: Input image, H x W x 3, value range [0, 255]
39
+ @param severity: Severity of distortion, [1, 5]
40
+ @return: Degraded image, H x W x 3, value range [0, 255]
41
+ """
42
+ c = [(2.0, 2), (2.4, 4), (3.0, 6), (3.8, 8), (5.0, 10)][severity - 1]
43
+ img_orig = np.array(img) / 255.
44
+ h, w = img.shape[:2]
45
+ mask = gen_lensmask(h, w, gamma=c[0])[:, :, None]
46
+ img = gaussian(img_orig, sigma=c[1], channel_axis=-1)
47
+ img = mask * img_orig + (1 - mask) * img
48
+ img = np.clip(img, 0, 1) * 255
49
+ return img.round().astype(np.uint8)
50
+
51
+
52
+ def blur_motion(img, severity=1):
53
+ """
54
+ Motion Blur.
55
+ severity = [1, 2, 3, 4, 5] corresponding to radius=[5, 10, 15, 15, 20] and
56
+ sigma=[1, 2, 3, 4, 5].
57
+ severity mainly refer to Imagecorruptions.
58
+
59
+ @param img: Input image, H x W x 3, value range [0, 255]
60
+ @param severity: Severity of distortion, [0, 5]
61
+ @return: Degraded image, H x W x 3, value range [0, 255]
62
+ """
63
+ c = [(5, 3), (10, 5), (15, 7), (15, 9), (20, 12)][severity - 1]
64
+ angle = np.random.uniform(-90, 90)
65
+ img = np.array(img)
66
+ img = _motion_blur(img, radius=c[0], sigma=c[1], angle=angle)
67
+ img = np.clip(img, 0, 255)
68
+ return img.round().astype(np.uint8)
69
+
70
+
71
+ def blur_glass(img, severity=1):
72
+ """
73
+ Glass Blur.
74
+ severity = [1, 2, 3, 4, 5] corresponding to
75
+ [sigma, shift, iteration]=[(0.7, 1, 1), (0.9, 2, 1), (1.2, 2, 2), (1.4, 3, 2), (1.6, 4, 2)].
76
+ severity mainly refer to Imagecorruptions.
77
+
78
+ @param img: Input image, H x W x 3, value range [0, 255]
79
+ @param severity: Severity of distortion, [0, 5]
80
+ @return: Degraded image, H x W x 3, value range [0, 255]
81
+ """
82
+ c = [(0.7, 1, 1), (0.9, 2, 1), (1.2, 2, 2), (1.4, 3, 2), (1.6, 4, 2)][severity - 1]
83
+ img = np.array(img) / 255.
84
+ img = gaussian(img, sigma=c[0], channel_axis=-1)
85
+ img = shuffle_pixels_njit(img, shift=c[1], iteration=c[2])
86
+ img = np.clip(gaussian(img, sigma=c[0], channel_axis=-1), 0, 1) * 255
87
+ return img.round().astype(np.uint8)
88
+
89
+
90
+ def blur_lens(img, severity=1):
91
+ """
92
+ Lens Blur.
93
+ severity = [1, 2, 3, 4, 5] corresponding to radius=[2, 3, 4, 6, 8].
94
+ severity mainly refer to KADID-10K.
95
+
96
+ @param img: Input image, H x W x 3, value range [0, 255]
97
+ @param severity: Severity of distortion, [0, 5]
98
+ @return: Degraded image, H x W x 3, value range [0, 255]
99
+ """
100
+ c = [2, 3, 4, 6, 8][severity - 1]
101
+ img = np.array(img) / 255.
102
+ kernel = gen_disk(radius=c)
103
+ img_lq = []
104
+ for i in range(3):
105
+ img_lq.append(cv2.filter2D(img[:, :, i], -1, kernel))
106
+ img_lq = np.array(img_lq).transpose((1, 2, 0))
107
+ img_lq = np.clip(img_lq, 0, 1) * 255
108
+ return img_lq.round().astype(np.uint8)
109
+
110
+
111
+ def blur_zoom(img, severity=1):
112
+ """
113
+ Zoom Blur.
114
+ severity = [1, 2, 3, 4, 5] corresponding to radius=
115
+ [np.arange(1, 1.03, 0.02),
116
+ np.arange(1, 1.06, 0.02),
117
+ np.arange(1, 1.10, 0.02),
118
+ np.arange(1, 1.15, 0.02),
119
+ np.arange(1, 1.21, 0.02)].
120
+ severity mainly refer to Imagecorruptions.
121
+
122
+ @param img: Input image, H x W x 3, value range [0, 255]
123
+ @param severity: Severity of distortion, [0, 5]
124
+ @return: Degraded image, H x W x 3, value range [0, 255]
125
+ """
126
+ c = [np.arange(1, 1.03, 0.02),
127
+ np.arange(1, 1.06, 0.02),
128
+ np.arange(1, 1.10, 0.02),
129
+ np.arange(1, 1.15, 0.02),
130
+ np.arange(1, 1.21, 0.02)][severity - 1]
131
+ img = (np.array(img) / 255.).astype(np.float32)
132
+ h, w = img.shape[:2]
133
+ img_lq = np.zeros_like(img)
134
+ for zoom_factor in c:
135
+ zoom_layer = clipped_zoom(img, zoom_factor)
136
+ img_lq += zoom_layer[:h, :w, :]
137
+ img_lq = (img + img_lq) / (len(c) + 1)
138
+ img_lq = np.clip(img_lq, 0, 1) * 255
139
+ return img_lq.round().astype(np.uint8)
140
+
141
+
142
+ def blur_jitter(img, severity=1):
143
+ """
144
+ Jitter Blur.
145
+ severity = [1, 2, 3, 4, 5] corresponding to shift=[1, 2, 3, 4, 5].
146
+ severity mainly refer to KADID-10K.
147
+
148
+ @param img: Input image, H x W x 3, value range [0, 255]
149
+ @param severity: Severity of distortion, [0, 5]
150
+ @return: Degraded image, H x W x 3, value range [0, 255]
151
+ """
152
+ c = [1, 2, 3, 4, 5][severity - 1]
153
+ img = np.array(img)
154
+ img_lq = shuffle_pixels_njit(img, shift=c, iteration=1)
155
+ return np.uint8(img_lq)
degradation_toolkit/x_distortion/brightness.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ from .helper import gen_lensmask
4
+
5
+
6
+ def brightness_brighten_shfit_HSV(img, severity=1):
7
+ """
8
+ The RGB image is mapping to HSV, and then enhance the brightness by V channel
9
+ severity=[1,2,3,4,5] is corresponding to c=[0.1, 0.2, 0.3, 0.4, 0.5]
10
+
11
+ @param img: Input image, H x W x RGB, value range [0, 255]
12
+ @param severity: Severity of distortion, [1, 5]
13
+ @return: Degraded image, H x W x RGB, value range [0, 255]
14
+ """
15
+ c = [0.1, 0.2, 0.3, 0.4, 0.5][severity-1]
16
+ img = np.float32(np.array(img) / 255.)
17
+ img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
18
+ img_hsv[:, :, 2] += c
19
+ img_lq = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB)
20
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
21
+
22
+
23
+ def brightness_brighten_shfit_RGB(img, severity=1):
24
+ """
25
+ The RGB image is directly enhanced by RGB mean shift
26
+ severity=[1,2,3,4,5] is corresponding to c=[0.1, 0.15, 0.2, 0.27, 0.35]
27
+
28
+ @param img: Input image, H x W x RGB, value range [0, 255]
29
+ @param severity: Severity of distortion, [1, 5]
30
+ @return: Degraded image, H x W x RGB, value range [0, 255]
31
+ """
32
+ c = [0.1, 0.15, 0.2, 0.27, 0.35][severity-1]
33
+ img = np.float32(np.array(img) / 255.)
34
+ img_lq = img + c
35
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
36
+
37
+
38
+ def brightness_brighten_gamma_RGB(img, severity=1):
39
+ """
40
+ The RGB image is enhanced by V channel with a gamma function
41
+ severity=[1,2,3,4,5] is corresponding to gamma=[0.8, 0.7, 0.6, 0.45, 0.3]
42
+
43
+ @param img: Input image, H x W x RGB, value range [0, 255]
44
+ @param severity: Severity of distortion, [1, 5]
45
+ @return: Degraded image, H x W x RGB, value range [0, 255]
46
+ """
47
+ gamma = [0.8, 0.7, 0.6, 0.45, 0.3][severity-1]
48
+ img = np.array(img / 255.)
49
+ img_lq = img ** gamma
50
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
51
+
52
+
53
+ def brightness_brighten_gamma_HSV(img, severity=1):
54
+ """
55
+ The RGB image is enhanced by V channel with a gamma function
56
+ severity=[1,2,3,4,5] is corresponding to gamma=[0.7, 0.55, 0.4, 0.25, 0.1]
57
+
58
+ @param img: Input image, H x W x RGB, value range [0, 255]
59
+ @param severity: Severity of distortion, [1, 5]
60
+ @return: Degraded image, H x W x RGB, value range [0, 255]
61
+ """
62
+ gamma = [0.7, 0.58, 0.47, 0.36, 0.25][severity-1]
63
+ img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
64
+ img_hsv = np.array(img_hsv / 255.)
65
+ img_hsv[:, :, 2] = img_hsv[:, :, 2] ** gamma
66
+ img_lq = np.uint8(np.clip(img_hsv, 0, 1) * 255.)
67
+ img_lq = cv2.cvtColor(img_lq, cv2.COLOR_HSV2RGB)
68
+ return img_lq
69
+
70
+
71
+ def brightness_darken_shfit_HSV(img, severity=1):
72
+ """
73
+ The RGB image is mapping to HSV, and then darken the brightness by V channel
74
+ severity=[1,2,3,4,5] is corresponding to c=[0.1, 0.2, 0.3, 0.4, 0.5]
75
+
76
+ @param img: Input image, H x W x RGB, value range [0, 255]
77
+ @param severity: Severity of distortion, [1, 5]
78
+ @return: Degraded image, H x W x RGB, value range [0, 255]
79
+ """
80
+ c = [0.1, 0.2, 0.3, 0.4, 0.5][severity-1]
81
+ img = np.float32(np.array(img) / 255.)
82
+ img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
83
+ img_hsv[:, :, 2] -= c
84
+ img_lq = cv2.cvtColor(img_hsv, cv2.COLOR_HSV2RGB)
85
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
86
+
87
+
88
+ def brightness_darken_shfit_RGB(img, severity=1):
89
+ """
90
+ The RGB image's brightness is directly reduced by RGB mean shift
91
+ severity=[1,2,3,4,5] is corresponding to c=[0.1, 0.15, 0.2, 0.27, 0.35]
92
+
93
+ @param img: Input image, H x W x RGB, value range [0, 255]
94
+ @param severity: Severity of distortion, [1, 5]
95
+ @return: Degraded image, H x W x RGB, value range [0, 255]
96
+ """
97
+ c = [0.1, 0.15, 0.2, 0.27, 0.35][severity-1]
98
+ img = np.float32(np.array(img)/255.)
99
+ img_lq = img - c
100
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
101
+
102
+
103
+ def brightness_darken_gamma_RGB(img, severity=1):
104
+ """
105
+ The RGB image is darkened by V channel with a gamma function
106
+ severity=[1,2,3,4,5] is corresponding to gamma=[1.4, 1.7, 2.1, 2.6, 3.2]
107
+
108
+ @param img: Input image, H x W x RGB, value range [0, 255]
109
+ @param severity: Severity of distortion, [1, 5]
110
+ @return: Degraded image, H x W x RGB, value range [0, 255]
111
+ """
112
+ gamma = [1.4, 1.7, 2.1, 2.6, 3.2][severity-1]
113
+ img = np.array(img / 255.)
114
+ img_lq = img ** gamma
115
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
116
+
117
+
118
+ def brightness_darken_gamma_HSV(img, severity=1):
119
+ """
120
+ The RGB image is enhanced by V channel with a gamma function
121
+ severity=[1,2,3,4,5] is corresponding to gamma=[1.5, 1.8, 2.2, 2.7, 3.5]
122
+
123
+ @param img: Input image, H x W x RGB, value range [0, 255]
124
+ @param severity: Severity of distortion, [1, 5]
125
+ @return: Degraded image, H x W x RGB, value range [0, 255]
126
+ """
127
+ gamma = [1.5, 1.8, 2.2, 2.7, 3.5][severity-1]
128
+ img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)
129
+ img_hsv = np.array(img_hsv / 255.)
130
+ img_hsv[:, :, 2] = img_hsv[:, :, 2] ** gamma
131
+ img_lq = np.uint8(np.clip(img_hsv, 0, 1) * 255.)
132
+ img_lq = cv2.cvtColor(img_lq, cv2.COLOR_HSV2RGB)
133
+ return img_lq
134
+
135
+
136
+ def brightness_vignette(img, severity=1):
137
+ """
138
+ The RGB image is suffered from the vignette effect.
139
+ severity=[1,2,3,4,5] is corresponding to gamma=[0.5, 0.875, 1.25, 1.625, 2]
140
+
141
+ @param img: Input image, H x W x RGB, value range [0, 255]
142
+ @param severity: Severity of distortion, [1, 5]
143
+ @return: Degraded image, H x W x RGB, value range [0, 255]
144
+ """
145
+ gamma = [0.5, 0.875, 1.25, 1.625, 2][severity - 1]
146
+ img = np.array(img)
147
+ h, w = img.shape[:2]
148
+ mask = gen_lensmask(h, w, gamma=gamma)[:, :, None]
149
+ img_lq = mask * img
150
+ return np.uint8(np.clip(img_lq, 0, 255))
degradation_toolkit/x_distortion/compression.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from PIL import Image
3
+ from io import BytesIO
4
+
5
+
6
+ def compression_jpeg(img, severity=1):
7
+ """
8
+ JPEG compression on a NumPy array.
9
+ severity=[1,2,3,4,5] corresponding to quality=[25,18,15,10,7].
10
+ from https://github.com/bethgelab/imagecorruptions/blob/master/imagecorruptions/corruptions.py
11
+
12
+ @param img: Input image as NumPy array, H x W x C, value range [0, 255]
13
+ @param severity: Severity of distortion, [1, 5]
14
+ @return: Degraded image as NumPy array, H x W x C, value range [0, 255]
15
+ """
16
+ assert img.dtype == np.uint8, "Image array should have dtype of np.uint8"
17
+ assert severity in [1, 2, 3, 4, 5], 'Severity must be an integer between 1 and 5.'
18
+
19
+ quality = [25, 18, 12, 8, 5][severity - 1]
20
+ output = BytesIO()
21
+ gray_scale = False
22
+ if img.shape[2] == 1: # Check if the image is grayscale
23
+ gray_scale = True
24
+ # Convert NumPy array to PIL Image
25
+ img = Image.fromarray(img)
26
+ if gray_scale:
27
+ img = img.convert('L')
28
+ else:
29
+ img = img.convert('RGB')
30
+ # Save image to a bytes buffer using JPEG compression
31
+ img.save(output, 'JPEG', quality=quality)
32
+ output.seek(0)
33
+ # Load the compressed image from the bytes buffer
34
+ img_lq = Image.open(output)
35
+ # Convert PIL Image back to NumPy array
36
+ if gray_scale:
37
+ img_lq = np.array(img_lq.convert('L'))
38
+ img_lq = img_lq.reshape((img_lq.shape[0], img_lq.shape[1], 1)) # Maintaining the original shape (H, W, 1)
39
+ else:
40
+ img_lq = np.array(img_lq.convert('RGB'))
41
+ return img_lq
42
+
43
+
44
+ def compression_jpeg_2000(img, severity=1):
45
+ """
46
+ JPEG2000 compression on a NumPy array.
47
+ severity=[1,2,3,4,5] corresponding to quality=[29,27.5,26,24.5,23], quality_mode='dB'.
48
+
49
+ @param x: Input image as NumPy array, H x W x C, value range [0, 255]
50
+ @param severity: Severity of distortion, [1, 5]
51
+ @return: Degraded image as NumPy array, H x W x C, value range [0, 255]
52
+ """
53
+ assert img.dtype == np.uint8, "Image array should have dtype of np.uint8"
54
+ assert severity in [1, 2, 3, 4, 5], 'Severity must be an integer between 1 and 5.'
55
+
56
+ quality = [29, 27.5, 26, 24.5, 23][severity - 1]
57
+ output = BytesIO()
58
+ gray_scale = False
59
+ if img.shape[2] == 1: # Check if the image is grayscale
60
+ gray_scale = True
61
+ # Convert NumPy array to PIL Image
62
+ img = Image.fromarray(img)
63
+ if gray_scale:
64
+ img = img.convert('L')
65
+ else:
66
+ img = img.convert('RGB')
67
+ # Save image to a bytes buffer using JPEG compression
68
+ img.save(output, 'JPEG2000', quality_mode='dB', quality_layers=[quality])
69
+ output.seek(0)
70
+ # Load the compressed image from the bytes buffer
71
+ img_lq = Image.open(output)
72
+ # Convert PIL Image back to NumPy array
73
+ if gray_scale:
74
+ img_lq = np.array(img_lq.convert('L'))
75
+ img_lq = img_lq.reshape((img_lq.shape[0], img_lq.shape[1], 1)) # Maintaining the original shape (H, W, 1)
76
+ else:
77
+ img_lq = np.array(img_lq.convert('RGB'))
78
+ return img_lq
degradation_toolkit/x_distortion/contrast.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image
4
+ from PIL import ImageEnhance
5
+
6
+
7
+ def contrast_weaken_scale(img, severity=1):
8
+ """
9
+ Contrast Weaken by scaling.
10
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[0.75, 0.6, 0.45, 0.3, 0.2].
11
+
12
+ @param img: Input image, H x W x 3, value range [0, 255]
13
+ @param severity: Severity of distortion, [1, 5]
14
+ @return: Degraded image, H x W x 3, value range [0, 255]
15
+ """
16
+ c = [0.75, 0.6, 0.45, 0.3, 0.2][severity - 1]
17
+ img = Image.fromarray(img)
18
+ enhancer = ImageEnhance.Contrast(img)
19
+ img = enhancer.enhance(c)
20
+ img = np.uint8(np.clip(np.array(img), 0, 255))
21
+ return img
22
+
23
+
24
+ def contrast_weaken_stretch(img, severity=1):
25
+ """
26
+ Contrast Weaken by stretching.
27
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[1.0, 0.9, 0.8, 0.6, 0.4].
28
+ severity mainly refer to PieAPP.
29
+
30
+ @param img: Input image, H x W x 3, value range [0, 255]
31
+ @param severity: Severity of distortion, [1, 5]
32
+ @return: Degraded image, H x W x 3, value range [0, 255]
33
+ """
34
+ c = [1.0, 0.9, 0.8, 0.6, 0.4][severity - 1]
35
+ img = np.array(img) / 255.
36
+ img_mean = np.mean(img, axis=(0,1), keepdims=True)
37
+ img = 1. / (1 + (img_mean / (img + 1e-12)) ** c)
38
+ img = np.uint8(np.clip(img, 0, 1) * 255)
39
+ return img
40
+
41
+
42
+ def contrast_strengthen_scale(img, severity=1):
43
+ """
44
+ Contrast Strengthen by scaling.
45
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[1.4, 1.7, 2.1, 2.6, 4.0].
46
+
47
+ @param img: Input image, H x W x 3, value range [0, 255]
48
+ @param severity: Severity of distortion, [1, 5]
49
+ @return: Degraded image, H x W x 3, value range [0, 255]
50
+ """
51
+ c = [1.4, 1.7, 2.1, 2.6, 4.0][severity - 1]
52
+ img = Image.fromarray(img)
53
+ enhancer = ImageEnhance.Contrast(img)
54
+ img = enhancer.enhance(c)
55
+ img = np.uint8(np.clip(np.array(img), 0, 255))
56
+ return img
57
+
58
+
59
+ def contrast_strengthen_stretch(img, severity=1):
60
+ """
61
+ Contrast Strengthen by stretching.
62
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[2.0, 4.0, 6.0, 8.0, 10.0].
63
+ severity mainly refer to PieAPP.
64
+
65
+ @param img: Input image, H x W x 3, value range [0, 255]
66
+ @param severity: Severity of distortion, [1, 5]
67
+ @return: Degraded image, H x W x 3, value range [0, 255]
68
+ """
69
+ c = [2.0, 4.0, 6.0, 8.0, 10.0][severity - 1]
70
+ img = np.array(img) / 255.
71
+ img_mean = np.mean(img, axis=(0,1), keepdims=True)
72
+ img = 1. / (1 + (img_mean / (img + 1e-12)) ** c)
73
+ img = np.uint8(np.clip(img, 0, 1) * 255)
74
+ return img
degradation_toolkit/x_distortion/helper.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ from scipy.ndimage import zoom as scizoom
3
+ from numba import njit, prange
4
+ import numpy as np
5
+ import math
6
+
7
+
8
+ def gen_lensmask(h, w, gamma):
9
+ """
10
+ Generate lens mask with shape (h, w).
11
+ For point (i, j),
12
+ distance = [(i - h // 2)^2 + (j - w // 2)^2] ^ (1/2) / [h // 2)^2 + (w // 2)^2] ^ (1/2)
13
+ mask = scale * (1 - distance) ^ gamma
14
+
15
+ @param h: height
16
+ @param w: width
17
+ @param gamma: exponential factor
18
+ @return: Mask, H x W
19
+ """
20
+ dist1 = np.array([list(range(w))] * h) - w // 2
21
+ dist2 = np.array([list(range(h))] * w) - h // 2
22
+ dist2 = np.transpose(dist2, (1, 0))
23
+ dist = np.sqrt((dist1 ** 2 + dist2 ** 2)) / np.sqrt((w ** 2 + h ** 2) / 4)
24
+ mask = (1 - dist) ** gamma
25
+ return mask
26
+
27
+
28
+ def gen_disk(radius, dtype=np.float32):
29
+ if radius <= 8:
30
+ L = np.arange(-8, 8 + 1)
31
+ else:
32
+ L = np.arange(-radius, radius + 1)
33
+ X, Y = np.meshgrid(L, L)
34
+ disk = np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
35
+ disk /= np.sum(disk)
36
+ return disk
37
+
38
+
39
+ # modification of https://github.com/FLHerne/mapgen/blob/master/diamondsquare.py
40
+ def plasma_fractal(mapsize=256, wibbledecay=3):
41
+ """
42
+ Generate a heightmap using diamond-square algorithm.
43
+ Return square 2d array, side length 'mapsize', of floats in range 0-255.
44
+ 'mapsize' must be a power of two.
45
+ """
46
+ assert (mapsize & (mapsize - 1) == 0)
47
+ maparray = np.empty((mapsize, mapsize), dtype=np.float_)
48
+ maparray[0, 0] = 0
49
+ stepsize = mapsize
50
+ wibble = 100
51
+
52
+ def wibbledmean(array):
53
+ return array / 4 + wibble * np.random.uniform(-wibble, wibble,
54
+ array.shape)
55
+
56
+ def fillsquares():
57
+ """For each square of points stepsize apart,
58
+ calculate middle value as mean of points + wibble"""
59
+ cornerref = maparray[0:mapsize:stepsize, 0:mapsize:stepsize]
60
+ squareaccum = cornerref + np.roll(cornerref, shift=-1, axis=0)
61
+ squareaccum += np.roll(squareaccum, shift=-1, axis=1)
62
+ maparray[stepsize // 2:mapsize:stepsize,
63
+ stepsize // 2:mapsize:stepsize] = wibbledmean(squareaccum)
64
+
65
+ def filldiamonds():
66
+ """For each diamond of points stepsize apart,
67
+ calculate middle value as mean of points + wibble"""
68
+ mapsize = maparray.shape[0]
69
+ drgrid = maparray[stepsize // 2:mapsize:stepsize,
70
+ stepsize // 2:mapsize:stepsize]
71
+ ulgrid = maparray[0:mapsize:stepsize, 0:mapsize:stepsize]
72
+ ldrsum = drgrid + np.roll(drgrid, 1, axis=0)
73
+ lulsum = ulgrid + np.roll(ulgrid, -1, axis=1)
74
+ ltsum = ldrsum + lulsum
75
+ maparray[0:mapsize:stepsize,
76
+ stepsize // 2:mapsize:stepsize] = wibbledmean(ltsum)
77
+ tdrsum = drgrid + np.roll(drgrid, 1, axis=1)
78
+ tulsum = ulgrid + np.roll(ulgrid, -1, axis=0)
79
+ ttsum = tdrsum + tulsum
80
+ maparray[stepsize // 2:mapsize:stepsize,
81
+ 0:mapsize:stepsize] = wibbledmean(ttsum)
82
+
83
+ while stepsize >= 2:
84
+ fillsquares()
85
+ filldiamonds()
86
+ stepsize //= 2
87
+ wibble /= wibbledecay
88
+
89
+ maparray -= maparray.min()
90
+ return maparray / maparray.max()
91
+
92
+
93
+ def clipped_zoom(img, zoom_factor):
94
+ # clipping along the width dimension:
95
+ ch0 = int(np.ceil(img.shape[0] / float(zoom_factor)))
96
+ top0 = (img.shape[0] - ch0) // 2
97
+
98
+ # clipping along the height dimension:
99
+ ch1 = int(np.ceil(img.shape[1] / float(zoom_factor)))
100
+ top1 = (img.shape[1] - ch1) // 2
101
+
102
+ img = scizoom(img[top0:top0 + ch0, top1:top1 + ch1],
103
+ (zoom_factor, zoom_factor, 1), order=1)
104
+
105
+ return img
106
+
107
+
108
+ def getOptimalKernelWidth1D(radius, sigma):
109
+ return radius * 2 + 1
110
+
111
+
112
+ def gauss_function(x, mean, sigma):
113
+ return (np.exp(- (x - mean)**2 / (2 * (sigma**2)))) / (np.sqrt(2 * np.pi) * sigma)
114
+
115
+
116
+ def getMotionBlurKernel(width, sigma):
117
+ k = gauss_function(np.arange(width), 0, sigma)
118
+ Z = np.sum(k)
119
+ return k/Z
120
+
121
+
122
+ def shift(image, dx, dy):
123
+ if(dx < 0):
124
+ shifted = np.roll(image, shift=image.shape[1]+dx, axis=1)
125
+ shifted[:,dx:] = shifted[:,dx-1:dx]
126
+ elif(dx > 0):
127
+ shifted = np.roll(image, shift=dx, axis=1)
128
+ shifted[:,:dx] = shifted[:,dx:dx+1]
129
+ else:
130
+ shifted = image
131
+
132
+ if(dy < 0):
133
+ shifted = np.roll(shifted, shift=image.shape[0]+dy, axis=0)
134
+ shifted[dy:,:] = shifted[dy-1:dy,:]
135
+ elif(dy > 0):
136
+ shifted = np.roll(shifted, shift=dy, axis=0)
137
+ shifted[:dy,:] = shifted[dy:dy+1,:]
138
+ return shifted
139
+
140
+
141
+ def _motion_blur(x, radius, sigma, angle):
142
+ width = getOptimalKernelWidth1D(radius, sigma)
143
+ kernel = getMotionBlurKernel(width, sigma)
144
+ point = (width * np.sin(np.deg2rad(angle)), width * np.cos(np.deg2rad(angle)))
145
+ hypot = math.hypot(point[0], point[1])
146
+
147
+ blurred = np.zeros_like(x, dtype=np.float32)
148
+ for i in range(width):
149
+ dy = -math.ceil(((i*point[0]) / hypot) - 0.5)
150
+ dx = -math.ceil(((i*point[1]) / hypot) - 0.5)
151
+ if (np.abs(dy) >= x.shape[0] or np.abs(dx) >= x.shape[1]):
152
+ # simulated motion exceeded image borders
153
+ break
154
+ shifted = shift(x, dx, dy)
155
+ blurred = blurred + kernel[i] * shifted
156
+ return blurred
157
+
158
+
159
+ # Numba nopython compilation to shuffle_pixles
160
+ @njit()
161
+ def shuffle_pixels_njit(img, shift, iteration):
162
+ height, width = img.shape[:2]
163
+ # locally shuffle pixels
164
+ for _ in range(iteration):
165
+ for h in range(height - shift, shift, -1):
166
+ for w in range(width - shift, shift, -1):
167
+ dx, dy = np.random.randint(-shift, shift, size=(2,))
168
+ h_prime, w_prime = h + dy, w + dx
169
+ # swap
170
+ img[h, w], img[h_prime, w_prime] = img[h_prime, w_prime], img[h, w]
171
+ return img
degradation_toolkit/x_distortion/noise.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ import skimage as sk
4
+
5
+
6
+ def noise_gaussian_RGB(img, severity=1):
7
+ """
8
+ Additive Gaussian noise in RGB channels.
9
+ severity=[1, 2, 3, 4, 5] is corresponding to sigma=[0.05, 0.1, 0.15, 0.2, 0.25].
10
+ severity mainly refer to KADID-10K and Imagecorruptions.
11
+
12
+ @param img: Input image, H x W x 3, value range [0, 255]
13
+ @param severity: Severity of distortion, [1, 5]
14
+ @return: Degraded image, H x W x 3, value range [0, 255]
15
+ """
16
+ sigma = [0.05, 0.1, 0.15, 0.2, 0.25][severity-1]
17
+ img = np.array(img) / 255.
18
+ noise = np.random.normal(0, sigma, img.shape)
19
+ img_lq = img + noise
20
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
21
+
22
+
23
+ def noise_gaussian_YCrCb(img, severity=1):
24
+ """
25
+ Additive Gaussian noise with higher noise in color channels.
26
+ severity=[1, 2, 3, 4, 5] is corresponding to
27
+ sigma_l=[0.05, 0.06, 0.07, 0.08, 0.09],
28
+ sigma_r=[1, 1.45, 1.9, 2.35, 2.8],
29
+ sigma_b=[1, 1.45, 1.9, 2.35, 2.8].
30
+
31
+ @param img: Input image, H x W x 3, value range [0, 255]
32
+ @param severity: Severity of distortion, [1, 5]
33
+ @return: Degraded image, H x W x 3, value range [0, 255]
34
+ """
35
+ sigma_l = [0.05, 0.06, 0.07, 0.08, 0.09][severity-1]
36
+ sigma_r = sigma_l * [1, 1.45, 1.9, 2.35, 2.8][severity - 1]
37
+ sigma_b = sigma_l * [1, 1.45, 1.9, 2.35, 2.8][severity - 1]
38
+ h, w = img.shape[:2]
39
+ img = np.float32(np.array(img) / 255.)
40
+ img = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB)
41
+ noise_l = np.expand_dims(np.random.normal(0, sigma_l, (h, w)), 2)
42
+ noise_r = np.expand_dims(np.random.normal(0, sigma_r, (h, w)), 2)
43
+ noise_b = np.expand_dims(np.random.normal(0, sigma_b, (h, w)), 2)
44
+ noise = np.concatenate((noise_l, noise_r, noise_b), axis=2)
45
+ img_lq = np.float32(img + noise)
46
+ img_lq = cv2.cvtColor(img_lq, cv2.COLOR_YCR_CB2RGB)
47
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
48
+
49
+
50
+ def noise_speckle(img, severity=1):
51
+ """
52
+ Multiplicative Gaussian noise.
53
+ severity=[1, 2, 3, 4, 5] is corresponding to sigma=[0.14, 0.21, 0.28, 0.35, 0.42].
54
+
55
+ @param img: Input image, H x W x 3, value range [0, 255]
56
+ @param severity: Severity of distortion, [1, 5]
57
+ @return: Degraded image, H x W x 3, value range [0, 255]
58
+ """
59
+ c = [0.14, 0.21, 0.28, 0.35, 0.42][severity - 1]
60
+ img = np.array(img) / 255.
61
+ noise = img * np.random.normal(size=img.shape, scale=c)
62
+ img_lq = img + noise
63
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
64
+
65
+
66
+ def noise_spatially_correlated(img, severity=1):
67
+ """
68
+ Spatially correlated noise.
69
+ severity=[1, 2, 3, 4, 5] is corresponding to sigma=[0.08, 0.11, 0.14, 0.18, 0.22].
70
+
71
+ @param img: Input image, H x W x 3, value range [0, 255]
72
+ @param severity: Severity of distortion, [1, 5]
73
+ @return: Degraded image, H x W x 3, value range [0, 255]
74
+ """
75
+ sigma = [0.08, 0.11, 0.14, 0.18, 0.22][severity - 1]
76
+ img = np.array(img) / 255.
77
+ noise = np.random.normal(0, sigma, img.shape)
78
+ img_lq = img + noise
79
+ img_lq = cv2.blur(img_lq, [3, 3])
80
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
81
+
82
+
83
+ def noise_poisson(img, severity=1):
84
+ """
85
+ Poisson noise.
86
+ PieAPP keeps this distortion free of additional parameters.
87
+ The default:
88
+ c = vals = len(np.unique(image))
89
+ vals = 2 ** np.ceil(np.log2(vals))
90
+ But Imagecorruptions introduces a extra parameter c
91
+ ranging [60, 25, 12, 5, 3] for sigma = sqrt(I / c).
92
+ severity=[1, 2, 3, 4, 5] is corresponding to c=[80, 60, 40, 25, 15].
93
+
94
+ @param img: Input image, H x W x 3, value range [0, 255]
95
+ @param severity: Severity of distortion, [1, 5]
96
+ @return: Degraded image, H x W x 3, value range [0, 255]
97
+ """
98
+ c = [80, 60, 40, 25, 15][severity - 1]
99
+ img = np.array(img) / 255.
100
+ img_lq = np.random.poisson(img * c) / float(c)
101
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
102
+
103
+
104
+ def noise_impulse(img, severity=1):
105
+ """
106
+ Impulse noise is also known as salt&pepper noise.
107
+ PieAPP introduce the range [1e-4, 0.045].
108
+ severity=[1, 2, 3, 4, 5] is corresponding to amount=[0.01, 0.03, 0.05, 0.07, 0.10].
109
+
110
+ @param img: Input image, H x W x 3, value range [0, 255]
111
+ @param severity: Severity of distortion, [1, 5]
112
+ @return: Degraded image, H x W x 3, value range [0, 255]
113
+ """
114
+ c = [0.01, 0.03, 0.05, 0.07, 0.10][severity - 1]
115
+ img = np.array(img) / 255.
116
+ img_lq = sk.util.random_noise(img, mode='s&p', amount=c)
117
+ return np.uint8(np.clip(img_lq, 0, 1) * 255.)
degradation_toolkit/x_distortion/oversharpen.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def oversharpen(img, severity=1):
6
+ """
7
+ OverSharpening filter on a NumPy array.
8
+ severity = [1, 5] corresponding to amount = [2, 4, 6, 8, 10]
9
+
10
+ @param x: Input image as NumPy array, H x W x C, value range [0, 255]
11
+ @param severity: Severity of distortion, [1, 5]
12
+ @return: Degraded image as NumPy array, H x W x C, value range [0, 255]
13
+ """
14
+ assert img.dtype == np.uint8, "Image array should have dtype of np.uint8"
15
+ assert severity in [1, 2, 3, 4, 5], 'Severity must be an integer between 1 and 5.'
16
+
17
+ amount = [2, 2.8, 4, 6, 8][severity - 1]
18
+
19
+ # Setting the kernel size and sigmaX value for Gaussian blur
20
+ # In OpenCV's Size(kernel_width, kernel_height), both kernel_width and kernel_height
21
+ # should be odd numbers; for example, we can use (2*radius+1, 2*radius+1)
22
+ blur_radius = 2 # The radius is the blur radius used to set the size of the Gaussian kernel
23
+ sigmaX = 0
24
+
25
+ # Create a blurred/smoothed version of the image
26
+ blurred = cv2.GaussianBlur(img, (2*blur_radius+1, 2*blur_radius+1), sigmaX)
27
+
28
+ # Compute the sharpened image with an enhancement factor of 'amount'
29
+ sharpened = cv2.addWeighted(img, 1 + amount, blurred, -amount, 0)
30
+
31
+ return sharpened
degradation_toolkit/x_distortion/pixelate.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from PIL import Image
4
+
5
+
6
+ def pixelate(img, severity=1):
7
+ """
8
+ Pixelate.
9
+ severity=[1, 2, 3, 4, 5] corresponding to sigma=[0.5, 0.4, 0.3, 0.25, 0.2].
10
+ severity mainly refer to Imagecorruptions.
11
+
12
+ @param img: Input image, H x W x 3, value range [0, 255]
13
+ @param severity: Severity of distortion, [1, 5]
14
+ @return: Degraded image, H x W x 3, value range [0, 255]
15
+ """
16
+ c = [0.5, 0.4, 0.3, 0.25, 0.2][severity - 1]
17
+ h, w = np.array(img).shape[:2]
18
+ img = Image.fromarray(img)
19
+ img = img.resize((int(w * c), int(h * c)), Image.BOX)
20
+ img = img.resize((w, h), Image.NEAREST)
21
+ return np.array(img).astype(np.uint8)
degradation_toolkit/x_distortion/quantization.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ from PIL import Image
4
+ from skimage.filters import threshold_multiotsu
5
+
6
+
7
+
8
+ def quantization_otsu(img, severity=1):
9
+ """
10
+ Color Quantization using OTSU method.
11
+ severity=[1, 2, 3, 4, 5] corresponding to num_classes=[15, 11, 8, 5, 3].
12
+ severity mainly refer to KADID-10K and Imagecorruptions.
13
+
14
+ @param img: Input image, H x W x 3, value range [0, 255]
15
+ @param severity: Severity of distortion, [1, 5]
16
+ @return: Degraded image, H x W x 3, value range [0, 255]
17
+ """
18
+ c = [15, 11, 8, 5, 3][severity - 1]
19
+ img = np.array(img).astype(np.float32)
20
+ for i in range(img.shape[2]):
21
+ img_gray = img[:, :, i]
22
+ thresholds = threshold_multiotsu(img_gray, classes=c, nbins=30) # modify skimage
23
+ v_max = img_gray.max()
24
+ v_min = img_gray.min()
25
+ img[:, :, i] = np.digitize(img[:, :, i], bins=thresholds) * (v_max - v_min) / c + v_min
26
+ img = np.clip(img, 0, 255)
27
+ return img
28
+
29
+
30
+ def quantization_median(img, severity=1):
31
+ """
32
+ Color Quantization using Histogram Median.
33
+ severity=[1, 2, 3, 4, 5] corresponding to num_classes=[20, 15, 10, 6, 3].
34
+ severity mainly refer to KADID-10K and Imagecorruptions.
35
+
36
+ @param img: Input image, H x W x 3, value range [0, 255]
37
+ @param severity: Severity of distortion, [1, 5]
38
+ @return: Degraded image, H x W x 3, value range [0, 255]
39
+ """
40
+ c = [20, 15, 10, 6, 3][severity - 1]
41
+ for i in range(img.shape[2]):
42
+ img_gray = Image.fromarray(img[:, :, i])
43
+ img_gray = img_gray.quantize(colors=c, method=Image.Quantize.MEDIANCUT).convert("L")
44
+ img[:, :, i] = np.array(img_gray)
45
+ img = np.clip(img, 0, 255)
46
+ return img
47
+
48
+
49
+ def quantization_hist(img, severity=1):
50
+ """
51
+ Color Quantization using Histogram Equalization.
52
+ severity=[1, 2, 3, 4, 5] corresponding to num_classes=[24, 16, 8, 6, 4].
53
+ severity mainly refer to KADID-10K and Imagecorruptions.
54
+
55
+ @param img: Input image, H x W x 3, value range [0, 255]
56
+ @param severity: Severity of distortion, [1, 5]
57
+ @return: Degraded image, H x W x 3, value range [0, 255]
58
+ """
59
+ c = [24, 16, 8, 6, 4][severity - 1]
60
+ hist, _ = np.histogram(img.flatten(), bins=c, range=[0, 255])
61
+ cdf = hist.cumsum()
62
+ cdf_m = np.ma.masked_equal(cdf, 0)
63
+ cdf_m = (cdf_m - cdf_m.min()) * 255 / (cdf_m.max() - cdf_m.min())
64
+ cdf = np.ma.filled(cdf_m, 0).astype('uint8')
65
+ img = np.uint8(np.round(img / 255 * (c - 1)))
66
+ img = cdf[img]
67
+ img = np.clip(img, 0, 255)
68
+ return img
degradation_toolkit/x_distortion/saturate.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+
4
+
5
+ def saturate_weaken_HSV(img, severity=1):
6
+ """
7
+ Saturate Weaken by scaling S channel in HSV.
8
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[0.7, 0.55, 0.4, 0.2, 0.0].
9
+ severity mainly refer to KADID-10K.
10
+
11
+ @param img: Input image, H x W x 3, value range [0, 255]
12
+ @param severity: Severity of distortion, [1, 5]
13
+ @return: Degraded image, H x W x 3, value range [0, 255]
14
+ """
15
+ c = [0.7, 0.55, 0.4, 0.2, 0.0][severity - 1]
16
+ hsv = np.array(cv2.cvtColor(img, cv2.COLOR_RGB2HSV), dtype=np.float32)
17
+ hsv[:, :, 1] = c * hsv[:, :, 1]
18
+ hsv = np.uint8(np.clip(hsv, 0, 255))
19
+ img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
20
+ return img
21
+
22
+
23
+ def saturate_weaken_YCrCb(img, severity=1):
24
+ """
25
+ Saturate Weaken by scaling S channel in YCrCb.
26
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[0.6, 0.4, 0.2, 0.1, 0.0].
27
+ severity mainly refer to PieAPP.
28
+
29
+ @param img: Input image, H x W x 3, value range [0, 255]
30
+ @param severity: Severity of distortion, [1, 5]
31
+ @return: Degraded image, H x W x 3, value range [0, 255]
32
+ """
33
+ c = [0.6, 0.4, 0.2, 0.1, 0.0][severity - 1]
34
+ ycrcb = np.array(cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB), dtype=np.float32)
35
+ ycrcb[:, :, 1] = 128 + (ycrcb[:, :, 1] - 128) * c
36
+ ycrcb[:, :, 2] = 128 + (ycrcb[:, :, 2] - 128) * c
37
+ ycrcb = np.uint8(np.clip(ycrcb, 0, 255))
38
+ img = cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2RGB)
39
+ return img
40
+
41
+
42
+ def saturate_strengthen_HSV(img, severity=1):
43
+ """
44
+ Saturate Strengthen by scaling S channel in HSV.
45
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[3.0, 6.0, 12.0, 20.0, 64.0].
46
+
47
+ @param img: Input image, H x W x 3, value range [0, 255]
48
+ @param severity: Severity of distortion, [1, 5]
49
+ @return: Degraded image, H x W x 3, value range [0, 255]
50
+ """
51
+ c = [3.0, 6.0, 12.0, 20.0, 64.0][severity - 1]
52
+ hsv = np.array(cv2.cvtColor(img, cv2.COLOR_RGB2HSV), dtype=np.float32)
53
+ hsv[:, :, 1] = c * hsv[:, :, 1]
54
+ hsv = np.uint8(np.clip(hsv, 0, 255))
55
+ img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)
56
+ return img
57
+
58
+
59
+ def saturate_strengthen_YCrCb(img, severity=1):
60
+ """
61
+ Saturate Strengthen by scaling S channel in YCrCb.
62
+ severity=[1, 2, 3, 4, 5] corresponding to scale=[2.0, 3.0, 5.0, 8.0, 16.0].
63
+ severity mainly refer to PieAPP.
64
+
65
+ @param img: Input image, H x W x 3, value range [0, 255]
66
+ @param severity: Severity of distortion, [1, 5]
67
+ @return: Degraded image, H x W x 3, value range [0, 255]
68
+ """
69
+ c = [2.0, 3.0, 5.0, 8.0, 16.0][severity - 1]
70
+ ycrcb = np.array(cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB), dtype=np.float32)
71
+ ycrcb[:, :, 1] = 128 + (ycrcb[:, :, 1] - 128) * c
72
+ ycrcb[:, :, 2] = 128 + (ycrcb[:, :, 2] - 128) * c
73
+ ycrcb = np.uint8(np.clip(ycrcb, 0, 255))
74
+ img = cv2.cvtColor(ycrcb, cv2.COLOR_YCR_CB2RGB)
75
+ return img
degradation_toolkit/x_distortion/spatter.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from skimage.filters import gaussian
4
+
5
+ def rgb2gray(rgb):
6
+ return np.dot(rgb[..., :3], [0.2989, 0.5870, 0.1140])
7
+
8
+ def spatter(x, severity=1):
9
+ c = [(0.65, 0.3, 4, 0.69, 0.6, 0),
10
+ (0.65, 0.3, 3, 0.68, 0.6, 0),
11
+ (0.65, 0.3, 2, 0.68, 0.5, 0),
12
+ (0.65, 0.3, 1, 0.65, 1.5, 1),
13
+ (0.67, 0.4, 1, 0.65, 1.5, 1)][severity - 1]
14
+ x_PIL = x
15
+ x = np.array(x, dtype=np.float32) / 255.
16
+
17
+ liquid_layer = np.random.normal(size=x.shape[:2], loc=c[0], scale=c[1])
18
+
19
+ liquid_layer = gaussian(liquid_layer, sigma=c[2])
20
+ liquid_layer[liquid_layer < c[3]] = 0
21
+ if c[5] == 0:
22
+ liquid_layer = (liquid_layer * 255).astype(np.uint8)
23
+ dist = 255 - cv2.Canny(liquid_layer, 50, 150)
24
+ dist = cv2.distanceTransform(dist, cv2.DIST_L2, 5)
25
+ _, dist = cv2.threshold(dist, 20, 20, cv2.THRESH_TRUNC)
26
+ dist = cv2.blur(dist, (3, 3)).astype(np.uint8)
27
+ dist = cv2.equalizeHist(dist)
28
+ ker = np.array([[-2, -1, 0], [-1, 1, 1], [0, 1, 2]])
29
+ dist = cv2.filter2D(dist, cv2.CV_8U, ker)
30
+ dist = cv2.blur(dist, (3, 3)).astype(np.float32)
31
+
32
+ m = cv2.cvtColor(liquid_layer * dist, cv2.COLOR_GRAY2BGRA)
33
+ m /= np.max(m, axis=(0, 1))
34
+ m *= c[4]
35
+ # water is pale turqouise
36
+ color = np.concatenate((175 / 255. * np.ones_like(m[..., :1]),
37
+ 238 / 255. * np.ones_like(m[..., :1]),
38
+ 238 / 255. * np.ones_like(m[..., :1])), axis=2)
39
+
40
+ color = cv2.cvtColor(color, cv2.COLOR_BGR2BGRA)
41
+
42
+ if len(x.shape) < 3 or x.shape[2] < 3:
43
+ add_spatter_color = cv2.cvtColor(np.clip(m * color, 0, 1),
44
+ cv2.COLOR_BGRA2BGR)
45
+ add_spatter_gray = rgb2gray(add_spatter_color)
46
+
47
+ return np.clip(x + add_spatter_gray, 0, 1) * 255
48
+
49
+ else:
50
+
51
+ x = cv2.cvtColor(x, cv2.COLOR_BGR2BGRA)
52
+
53
+ return cv2.cvtColor(np.clip(x + m * color, 0, 1),
54
+ cv2.COLOR_BGRA2BGR) * 255
55
+ else:
56
+ m = np.where(liquid_layer > c[3], 1, 0)
57
+ m = gaussian(m.astype(np.float32), sigma=c[4])
58
+ m[m < 0.8] = 0
59
+
60
+ x_rgb = np.array(x_PIL.convert('RGB'))
61
+
62
+ # mud brown
63
+ color = np.concatenate((63 / 255. * np.ones_like(x_rgb[..., :1]),
64
+ 42 / 255. * np.ones_like(x_rgb[..., :1]),
65
+ 20 / 255. * np.ones_like(x_rgb[..., :1])),
66
+ axis=2)
67
+ color *= m[..., np.newaxis]
68
+ if len(x.shape) < 3 or x.shape[2] < 3:
69
+ x *= (1 - m)
70
+ return np.clip(x + rgb2gray(color), 0, 1) * 255
71
+
72
+ else:
73
+ x *= (1 - m[..., np.newaxis])
74
+ return np.clip(x + color, 0, 1) * 255
degradation_utils.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import cv2
3
+ import random
4
+ from PIL import Image
5
+
6
+ from degradation_toolkit.add_degradation_various import *
7
+ from degradation_toolkit.image_operators import *
8
+ from degradation_toolkit.x_distortion import *
9
+
10
+
11
+ degradation_list1 = [
12
+ 'blur',
13
+ 'noise',
14
+ 'compression',
15
+ 'brighten',
16
+ 'darken',
17
+ 'spatter',
18
+ 'contrast_strengthen',
19
+ 'contrast_weaken',
20
+ 'saturate_strengthen',
21
+ 'saturate_weaken',
22
+ 'oversharpen',
23
+ 'pixelate',
24
+ 'quantization',
25
+ ]
26
+
27
+
28
+ degradation_list2 = [
29
+ 'Rain',
30
+ 'Ringing',
31
+ 'r_l',
32
+ 'Inpainting',
33
+ 'mosaic',
34
+ 'SRx2',
35
+ 'SRx4',
36
+ 'GaussianNoise',
37
+ 'GaussianBlur',
38
+ 'JPEG',
39
+ 'Resize',
40
+ 'SPNoise',
41
+ 'LowLight',
42
+ 'PoissonNoise',
43
+ 'gray',
44
+ 'ColorDistortion',
45
+ ]
46
+
47
+
48
+ degradation_list3 = [
49
+ 'Laplacian',
50
+ 'Canny',
51
+ 'Sobel',
52
+ 'Defocus',
53
+ 'Mosaic',
54
+ 'Barrel',
55
+ 'Pincushion',
56
+ 'Spatter',
57
+ 'Elastic',
58
+ 'Frost',
59
+ 'Contrast',
60
+ ]
61
+
62
+
63
+ degradation_list4 = [
64
+ 'flip',
65
+ 'rotate90',
66
+ 'rotate180',
67
+ 'rotate270',
68
+ 'identity',
69
+ ]
70
+
71
+
72
+ all_degradation_types = degradation_list1 + degradation_list2 + degradation_list3 + degradation_list4
73
+
74
+
75
+ def single2uint(img):
76
+ return np.uint8((img.clip(0, 1) * 255.0).round())
77
+
78
+
79
+ def uint2single(img):
80
+ return np.float32(img / 255.0)
81
+
82
+
83
+ def add_x_distortion_single_images(img_gt1, deg_type):
84
+ # np.uint8, BGR
85
+ x_distortion_dict = distortions_dict
86
+ severity = random.choice([1, 2, 3, 4, 5])
87
+ if deg_type == 'compression' or deg_type == "quantization":
88
+ severity = min(3, severity)
89
+ deg_type = random.choice(x_distortion_dict[deg_type])
90
+
91
+ img_gt1 = cv2.cvtColor(img_gt1, cv2.COLOR_BGR2RGB)
92
+ img_lq1 = globals()[deg_type](img_gt1, severity)
93
+
94
+ img_gt1 = cv2.cvtColor(img_gt1, cv2.COLOR_RGB2BGR)
95
+ img_lq1 = cv2.cvtColor(img_lq1, cv2.COLOR_RGB2BGR)
96
+
97
+ return img_lq1, img_gt1, deg_type
98
+
99
+
100
+ def add_degradation_single_images(img_gt1, deg_type):
101
+ if deg_type == 'Rain':
102
+ value = random.uniform(40, 200)
103
+ img_lq1 = add_rain(img_gt1, value=value)
104
+ elif deg_type == 'Ringing':
105
+ img_lq1 = add_ringing(img_gt1)
106
+ elif deg_type == 'r_l':
107
+ img_lq1 = r_l(img_gt1)
108
+ elif deg_type == 'Inpainting':
109
+ l_num = random.randint(20, 50)
110
+ l_thick = random.randint(10, 20)
111
+ img_lq1 = inpainting(img_gt1, l_num=l_num, l_thick=l_thick)
112
+ elif deg_type == 'mosaic':
113
+ img_lq1 = mosaic_CFA_Bayer(img_gt1)
114
+ elif deg_type == 'SRx2':
115
+ H, W, _ = img_gt1.shape
116
+ img_lq1 = cv2.resize(img_gt1, (W//2, H//2), interpolation=cv2.INTER_CUBIC)
117
+ img_lq1 = cv2.resize(img_lq1, (W, H), interpolation=cv2.INTER_CUBIC)
118
+ elif deg_type == 'SRx4':
119
+ H, W, _ = img_gt1.shape
120
+ img_lq1 = cv2.resize(img_gt1, (W//4, H//4), interpolation=cv2.INTER_CUBIC)
121
+ img_lq1 = cv2.resize(img_lq1, (W, H), interpolation=cv2.INTER_CUBIC)
122
+
123
+ elif deg_type == 'GaussianNoise':
124
+ level = random.uniform(10, 50)
125
+ img_lq1 = add_Gaussian_noise(img_gt1, level=level)
126
+ elif deg_type == 'GaussianBlur':
127
+ sigma = random.uniform(2, 4)
128
+ img_lq1 = iso_GaussianBlur(img_gt1, window=15, sigma=sigma)
129
+ elif deg_type == 'JPEG':
130
+ level = random.randint(10, 40)
131
+ img_lq1 = add_JPEG_noise(img_gt1, level=level)
132
+ elif deg_type == 'Resize':
133
+ img_lq1 = add_resize(img_gt1)
134
+ elif deg_type == 'SPNoise':
135
+ img_lq1 = add_sp_noise(img_gt1)
136
+ elif deg_type == 'LowLight':
137
+ lum_scale = random.uniform(0.3, 0.4)
138
+ img_lq1 = low_light(img_gt1, lum_scale=lum_scale)
139
+ elif deg_type == 'PoissonNoise':
140
+ img_lq1 = add_Poisson_noise(img_gt1, level=2)
141
+ elif deg_type == 'gray':
142
+ img_lq1 = cv2.cvtColor(img_gt1, cv2.COLOR_BGR2GRAY)
143
+ img_lq1 = np.expand_dims(img_lq1, axis=2)
144
+ img_lq1 = np.concatenate((img_lq1, img_lq1, img_lq1), axis=2)
145
+ elif deg_type == 'None':
146
+ img_lq1 = img_gt1
147
+ elif deg_type == 'ColorDistortion':
148
+ if random.random() < 0.5:
149
+ channels = list(range(3))
150
+ random.shuffle(channels)
151
+ img_lq1 = img_gt1[..., channels]
152
+ else:
153
+ channel = random.randint(0, 2)
154
+ img_lq1 = img_gt1.copy()
155
+ if random.random() < 0.5:
156
+ img_lq1[..., channel] = 0
157
+ else:
158
+ img_lq1[..., channel] = 1
159
+ else:
160
+ print('Error!', '-', deg_type, '-')
161
+ exit()
162
+ img_lq1 = np.clip(img_lq1 * 255, 0, 255).round().astype(np.uint8)
163
+ img_lq1 = img_lq1.astype(np.float32) / 255.0
164
+ img_gt1 = np.clip(img_gt1 * 255, 0, 255).round().astype(np.uint8)
165
+ img_gt1 = img_gt1.astype(np.float32) / 255.0
166
+
167
+ return img_lq1, img_gt1
168
+
169
+
170
+ def calculate_operators_single_images(img_gt1, deg_type):
171
+ img_gt1 = img_gt1.copy()
172
+
173
+ if deg_type == 'Laplacian':
174
+ img_lq1 = Laplacian_edge_detector(img_gt1)
175
+ elif deg_type == 'Canny':
176
+ img_lq1 = Canny_edge_detector(img_gt1)
177
+ elif deg_type == 'Sobel':
178
+ img_lq1 = Sobel_edge_detector(img_gt1)
179
+ elif deg_type == 'Defocus':
180
+ img_lq1 = defocus_blur(img_gt1, level=(3, 0.2))
181
+ elif deg_type == 'Mosaic':
182
+ img_lq1 = mosaic_CFA_Bayer(img_gt1)
183
+ elif deg_type == 'Barrel':
184
+ img_lq1 = simulate_barrel_distortion(img_gt1, k1=0.1, k2=0.05)
185
+ elif deg_type == 'Pincushion':
186
+ img_lq1 = simulate_pincushion_distortion(img_gt1, k1=-0.1, k2=-0.05)
187
+ elif deg_type == 'Spatter':
188
+ img_lq1 = uint2single(spatter((img_gt1), severity=1))
189
+ elif deg_type == 'Elastic':
190
+ img_lq1 = elastic_transform((img_gt1), severity=4)
191
+ elif deg_type == 'Frost':
192
+ img_lq1 = uint2single(frost(img_gt1, severity=4))
193
+ elif deg_type == 'Contrast':
194
+ img_lq1 = adjust_contrast(img_gt1, clip_limit=4.0, tile_grid_size=(4, 4))
195
+
196
+ if np.mean(img_lq1).astype(np.float16) == 0:
197
+ print(deg_type, 'prompt&query zero images.')
198
+ img_lq1 = img_gt1.copy()
199
+
200
+ return img_lq1, img_gt1
201
+
202
+
203
+ def add_degradation(image, deg_type):
204
+ if deg_type in degradation_list1:
205
+ list_idx = 1
206
+ img_lq1, _, _ = add_x_distortion_single_images(np.copy(image), deg_type)
207
+ img_lq1 = uint2single(img_lq1)
208
+ elif deg_type in degradation_list2:
209
+ list_idx = 2
210
+ img_lq1, _ = add_degradation_single_images(np.copy(uint2single(image)), deg_type)
211
+ elif deg_type in degradation_list3:
212
+ list_idx = 3
213
+ if deg_type in ['Laplacian', 'Canny', 'Sobel', 'Frost']:
214
+ img_lq1, _ = calculate_operators_single_images(np.copy(image), deg_type)
215
+ else:
216
+ img_lq1, _ = calculate_operators_single_images(np.copy(uint2single(image)), deg_type)
217
+ if img_lq1.max() > 1:
218
+ img_lq1 = uint2single(img_lq1)
219
+ elif deg_type in degradation_list4:
220
+ list_idx = 4
221
+ img_lq1 = np.copy(uint2single(image))
222
+ if deg_type == 'flip':
223
+ img_lq1 = np.flip(img_lq1, axis=1)
224
+ elif deg_type == 'rotate90':
225
+ img_lq1 = np.rot90(img_lq1, k=1)
226
+ elif deg_type == 'rotate180':
227
+ img_lq1 = np.rot90(img_lq1, k=2)
228
+ elif deg_type == 'rotate270':
229
+ img_lq1 = np.rot90(img_lq1, k=3)
230
+ elif deg_type == 'identity':
231
+ pass
232
+ return Image.fromarray(single2uint(img_lq1)), list_idx
demo_tasks/__init__.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .gradio_tasks import dense_prediction_text, conditional_generation_text, process_dense_prediction_tasks, process_conditional_generation_tasks
2
+ from .gradio_tasks_restoration import image_restoration_text, process_image_restoration_tasks
3
+ from .gradio_tasks_style import style_transfer_text, style_condition_fusion_text, process_style_transfer_tasks, process_style_condition_fusion_tasks
4
+ from .gradio_tasks_tryon import tryon_text, process_tryon_tasks
5
+ from .gradio_tasks_editing import editing_text, process_editing_tasks
6
+ from .gradio_tasks_photodoodle import photodoodle_text, process_photodoodle_tasks
7
+ from .gradio_tasks_editing_subject import editing_with_subject_text, process_editing_with_subject_tasks
8
+ from .gradio_tasks_relighting import relighting_text, process_relighting_tasks
9
+ from .gradio_tasks_unseen import unseen_tasks_text, process_unseen_tasks
10
+ from .gradio_tasks_subject import subject_driven_text, condition_subject_fusion_text, condition_subject_style_fusion_text, style_transfer_with_subject_text, \
11
+ image_restoration_with_subject_text, \
12
+ process_subject_driven_tasks, process_image_restoration_with_subject_tasks, process_style_transfer_with_subject_tasks, process_condition_subject_style_fusion_tasks, \
13
+ process_condition_subject_fusion_tasks
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9.jpg ADDED

Git LFS Details

  • SHA256: e0c4bde1a615edc572ce74f5e334c7cd035f686bf94d00fa13de1c825a837010
  • Pointer size: 131 Bytes
  • Size of remote file: 228 kB
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_ben2-background-removal.jpg ADDED

Git LFS Details

  • SHA256: 59ecf637fce4eb98d75a9f17f005887b62fcf4f25db258a0e3f39f93a0704014
  • Pointer size: 130 Bytes
  • Size of remote file: 47.1 kB
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_canny_100_200_512.jpg ADDED

Git LFS Details

  • SHA256: a78563977bc2236d93bff7a2e1459efcb737eabe5e044c70ce627840796106e9
  • Pointer size: 131 Bytes
  • Size of remote file: 184 kB
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_depth-anything-v2_Large.jpg ADDED

Git LFS Details

  • SHA256: 944b88ce7c555db6653fab381d475d7af2d5552dd732c9fe3b81c28a9aa6b425
  • Pointer size: 130 Bytes
  • Size of remote file: 80.7 kB
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_dsine_normal_map.jpg ADDED

Git LFS Details

  • SHA256: 107b1cfe736e79078760fbbeffa050e82584e4265eb632948107926a2e0b1ed3
  • Pointer size: 131 Bytes
  • Size of remote file: 143 kB
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_hed_512.jpg ADDED

Git LFS Details

  • SHA256: 7db142dd0065491bc4c8367cd1b5c7fbaaa754eafed5ab80a9980d43c6c5a326
  • Pointer size: 131 Bytes
  • Size of remote file: 165 kB
demo_tasks/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_sam2_mask.jpg ADDED

Git LFS Details

  • SHA256: c2439f48bf3a32e2e380c6c73016d63660a6a36cc8fbeeb3737c8b92c9ca3a07
  • Pointer size: 131 Bytes
  • Size of remote file: 229 kB
demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3.jpg ADDED

Git LFS Details

  • SHA256: 59350c813475dce227e740d946c5b7664c4390c6d26f3261ec0202a2480c5b74
  • Pointer size: 131 Bytes
  • Size of remote file: 243 kB
demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0.jpg ADDED

Git LFS Details

  • SHA256: 19c642b67133efe536ee9a7cf9016e7f269db2d23c2bea9a077e83460cd7d629
  • Pointer size: 131 Bytes
  • Size of remote file: 249 kB
demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0_style.jpg ADDED

Git LFS Details

  • SHA256: 0796121fe4d6a689278cf5af4f0428793b38c3ce9d5c39072a45a3c6a0dfe21e
  • Pointer size: 131 Bytes
  • Size of remote file: 342 kB
demo_tasks/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_qwen2_5_mask.jpg ADDED

Git LFS Details

  • SHA256: 85dc6eb30251a4c7bb45d6a8caea4f9d93f40543dfb4ad6d50d647ab49a15bee
  • Pointer size: 130 Bytes
  • Size of remote file: 65.9 kB
demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462.jpg ADDED

Git LFS Details

  • SHA256: 156bcd9d1123e6732829ccca11eda8761191f219de538e5b1746c9d283c47627
  • Pointer size: 131 Bytes
  • Size of remote file: 216 kB
demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0.jpg ADDED

Git LFS Details

  • SHA256: 4c9beac8a2d2713b06311394315c006192a1ea35f17ee80e8fc4d6f6a93464b4
  • Pointer size: 131 Bytes
  • Size of remote file: 382 kB
demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0_style.jpg ADDED

Git LFS Details

  • SHA256: f91bd76cd88742f32d48f659d7e1890e5f6c7986f542b4a4b5041d9aa4cd6e23
  • Pointer size: 131 Bytes
  • Size of remote file: 458 kB
demo_tasks/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_qwen2_5_mask.jpg ADDED

Git LFS Details

  • SHA256: 538a5a535aad2befabcdb23914d8e4bf2dd00aedc0ec7f460742ce3a2d3ebb44
  • Pointer size: 130 Bytes
  • Size of remote file: 53 kB
demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3.jpg ADDED

Git LFS Details

  • SHA256: e92c8ccfb16feac9a6ebb408c459cacb1480984b1f2069939834e1e22f342f82
  • Pointer size: 131 Bytes
  • Size of remote file: 224 kB
demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_canny_100_200_512.jpg ADDED

Git LFS Details

  • SHA256: 680ad5e599de63a1cdcf11fb52c81688c26ee1a49664940388b6526a01bce4ba
  • Pointer size: 131 Bytes
  • Size of remote file: 227 kB
demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_depth-anything-v2_Large.jpg ADDED

Git LFS Details

  • SHA256: a85966b4f60297e0b4c4cf50d1a5052589f4a56b12683aefaa508101fb0f1b75
  • Pointer size: 130 Bytes
  • Size of remote file: 72.6 kB
demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_dsine_normal_map.jpg ADDED

Git LFS Details

  • SHA256: 2bcd73f41f18c76353aedea03130566b5fa7e63ac11e429eaa2a1e6469f8192c
  • Pointer size: 131 Bytes
  • Size of remote file: 230 kB
demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_hed_512.jpg ADDED

Git LFS Details

  • SHA256: ac807b0fa0c1dfd41fc8b4b0a20d5cd74eb414f53020d6471dabb269b6f67303
  • Pointer size: 131 Bytes
  • Size of remote file: 170 kB
demo_tasks/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_openpose_fullres_nohand.jpg ADDED

Git LFS Details

  • SHA256: 0dd5fa3b2ee1b2d71603a266f3b45b2f9e3bfe2be5ee9279d3ba98d0dc6b8231
  • Pointer size: 131 Bytes
  • Size of remote file: 127 kB