Spaces:
Running
on
Zero
Running
on
Zero
lzyhha
commited on
Commit
·
af44a4b
1
Parent(s):
a801f0e
clean
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- app.py +52 -51
- data/degradation_toolkit/__init__.py +0 -0
- data/degradation_toolkit/add_degradation_various.py +401 -0
- data/degradation_toolkit/degradation_utils.py +232 -0
- data/degradation_toolkit/frost/frost1.png +3 -0
- data/degradation_toolkit/frost/frost2.png +3 -0
- data/degradation_toolkit/frost/frost3.png +3 -0
- data/degradation_toolkit/frost/frost4.jpg +3 -0
- data/degradation_toolkit/frost/frost5.jpg +3 -0
- data/degradation_toolkit/frost/frost6.jpg +3 -0
- data/degradation_toolkit/image_operators.py +420 -0
- data/degradation_toolkit/x_distortion/__init__.py +120 -0
- data/degradation_toolkit/x_distortion/blur.py +155 -0
- data/degradation_toolkit/x_distortion/brightness.py +150 -0
- data/degradation_toolkit/x_distortion/compression.py +78 -0
- data/degradation_toolkit/x_distortion/contrast.py +74 -0
- data/degradation_toolkit/x_distortion/helper.py +171 -0
- data/degradation_toolkit/x_distortion/noise.py +117 -0
- data/degradation_toolkit/x_distortion/oversharpen.py +31 -0
- data/degradation_toolkit/x_distortion/pixelate.py +21 -0
- data/degradation_toolkit/x_distortion/quantization.py +68 -0
- data/degradation_toolkit/x_distortion/saturate.py +75 -0
- data/degradation_toolkit/x_distortion/spatter.py +74 -0
- imgproc.py → data/imgproc.py +0 -0
- examples/__init__.py +13 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9.jpg +3 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_ben2-background-removal.jpg +3 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_canny_100_200_512.jpg +3 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_depth-anything-v2_Large.jpg +3 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_dsine_normal_map.jpg +3 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_hed_512.jpg +3 -0
- examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_sam2_mask.jpg +3 -0
- examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3.jpg +3 -0
- examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0.jpg +3 -0
- examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0_style.jpg +3 -0
- examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_qwen2_5_mask.jpg +3 -0
- examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462.jpg +3 -0
- examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0.jpg +3 -0
- examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0_style.jpg +3 -0
- examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_qwen2_5_mask.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_canny_100_200_512.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_depth-anything-v2_Large.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_dsine_normal_map.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_hed_512.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_openpose_fullres_nohand.jpg +3 -0
- examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_sam2_mask.jpg +3 -0
- examples/examples/2c4e256fa512cb7e7f433f4c7f9101de/2c4e256fa512cb7e7f433f4c7f9101de.jpg +3 -0
- examples/examples/2c4e256fa512cb7e7f433f4c7f9101de/2c4e256fa512cb7e7f433f4c7f9101de_ben2-background-removal.jpg +3 -0
- examples/examples/2c4e256fa512cb7e7f433f4c7f9101de/2c4e256fa512cb7e7f433f4c7f9101de_canny_100_200_512.jpg +3 -0
app.py
CHANGED
@@ -1,8 +1,8 @@
|
|
1 |
import argparse
|
2 |
-
import spaces
|
3 |
from visualcloze import VisualClozeModel
|
4 |
import gradio as gr
|
5 |
-
import
|
6 |
from functools import partial
|
7 |
from data.prefix_instruction import get_layout_instruction
|
8 |
from huggingface_hub import snapshot_download
|
@@ -15,11 +15,8 @@ default_grid_w = 3
|
|
15 |
default_upsampling_noise = 0.4
|
16 |
default_steps = 30
|
17 |
|
18 |
-
GUIDANCE = """
|
19 |
-
|
20 |
|
21 |
-
|
22 |
-
Need help or have questions? Contact us at: lizhongyu [AT] mail.nankai.edu.cn.
|
23 |
|
24 |
## 📋 Quick Start Guide:
|
25 |
1. Adjust **Number of In-context Examples**, 0 disables in-context learning.
|
@@ -41,6 +38,7 @@ When generating three images in a 3x4 grid, i.e., Image to Depth + Normal + Hed,
|
|
41 |
the runtime is approximately **110s**.
|
42 |
**Deploying locally with an 80G A100 can reduce the runtime by more than half.**
|
43 |
|
|
|
44 |
"""
|
45 |
|
46 |
CITATION = r"""
|
@@ -53,13 +51,17 @@ If our work is useful for your research, please consider citing:
|
|
53 |
@article{li2025visualcloze,
|
54 |
title={VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning},
|
55 |
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},
|
56 |
-
|
57 |
year={2025}
|
58 |
}
|
59 |
```
|
60 |
📋 **License**
|
61 |
<br>
|
62 |
-
This project is licensed under
|
|
|
|
|
|
|
|
|
63 |
"""
|
64 |
|
65 |
NOTE = r"""
|
@@ -150,7 +152,7 @@ def create_demo(model):
|
|
150 |
steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=default_steps, step=1)
|
151 |
cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=50.0, value=30, step=1)
|
152 |
upsampling_steps = gr.Slider(label="Upsampling steps (SDEdit)", minimum=1, maximum=100.0, value=10, step=1)
|
153 |
-
upsampling_noise = gr.Slider(label="Upsampling noise (SDEdit)", minimum=0, maximum=1.0, value=default_upsampling_noise, step=0.
|
154 |
|
155 |
gr.Markdown(CITATION)
|
156 |
|
@@ -170,70 +172,70 @@ def create_demo(model):
|
|
170 |
gr.Markdown("# Task Examples")
|
171 |
text_dense_prediction_tasks = gr.Textbox(label="Task", visible=False)
|
172 |
dense_prediction_tasks = gr.Dataset(
|
173 |
-
samples=
|
174 |
label='Dense Prediction',
|
175 |
samples_per_page=1000,
|
176 |
components=[text_dense_prediction_tasks])
|
177 |
|
178 |
text_conditional_generation_tasks = gr.Textbox(label="Task", visible=False)
|
179 |
conditional_generation_tasks = gr.Dataset(
|
180 |
-
samples=
|
181 |
label='Conditional Generation',
|
182 |
samples_per_page=1000,
|
183 |
components=[text_conditional_generation_tasks])
|
184 |
|
185 |
text_image_restoration_tasks = gr.Textbox(label="Task", visible=False)
|
186 |
image_restoration_tasks = gr.Dataset(
|
187 |
-
samples=
|
188 |
label='Image Restoration',
|
189 |
samples_per_page=1000,
|
190 |
components=[text_image_restoration_tasks])
|
191 |
|
192 |
text_style_transfer_tasks = gr.Textbox(label="Task", visible=False)
|
193 |
style_transfer_tasks = gr.Dataset(
|
194 |
-
samples=
|
195 |
label='Style Transfer',
|
196 |
samples_per_page=1000,
|
197 |
components=[text_style_transfer_tasks])
|
198 |
|
199 |
text_style_condition_fusion_tasks = gr.Textbox(label="Task", visible=False)
|
200 |
style_condition_fusion_tasks = gr.Dataset(
|
201 |
-
samples=
|
202 |
label='Style Condition Fusion',
|
203 |
samples_per_page=1000,
|
204 |
components=[text_style_condition_fusion_tasks])
|
205 |
|
206 |
text_tryon_tasks = gr.Textbox(label="Task", visible=False)
|
207 |
tryon_tasks = gr.Dataset(
|
208 |
-
samples=
|
209 |
label='Virtual Try-On',
|
210 |
samples_per_page=1000,
|
211 |
components=[text_tryon_tasks])
|
212 |
|
213 |
text_relighting_tasks = gr.Textbox(label="Task", visible=False)
|
214 |
relighting_tasks = gr.Dataset(
|
215 |
-
samples=
|
216 |
label='Relighting',
|
217 |
samples_per_page=1000,
|
218 |
components=[text_relighting_tasks])
|
219 |
|
220 |
text_photodoodle_tasks = gr.Textbox(label="Task", visible=False)
|
221 |
photodoodle_tasks = gr.Dataset(
|
222 |
-
samples=
|
223 |
label='Photodoodle',
|
224 |
samples_per_page=1000,
|
225 |
components=[text_photodoodle_tasks])
|
226 |
|
227 |
text_editing_tasks = gr.Textbox(label="Task", visible=False)
|
228 |
editing_tasks = gr.Dataset(
|
229 |
-
samples=
|
230 |
label='Editing',
|
231 |
samples_per_page=1000,
|
232 |
components=[text_editing_tasks])
|
233 |
|
234 |
text_unseen_tasks = gr.Textbox(label="Task", visible=False)
|
235 |
unseen_tasks = gr.Dataset(
|
236 |
-
samples=
|
237 |
label='Unseen Tasks (May produce unstable effects)',
|
238 |
samples_per_page=1000,
|
239 |
components=[text_unseen_tasks])
|
@@ -241,42 +243,42 @@ def create_demo(model):
|
|
241 |
gr.Markdown("# Subject-driven Tasks Examples")
|
242 |
text_subject_driven_tasks = gr.Textbox(label="Task", visible=False)
|
243 |
subject_driven_tasks = gr.Dataset(
|
244 |
-
samples=
|
245 |
label='Subject-driven Generation',
|
246 |
samples_per_page=1000,
|
247 |
components=[text_subject_driven_tasks])
|
248 |
|
249 |
text_condition_subject_fusion_tasks = gr.Textbox(label="Task", visible=False)
|
250 |
condition_subject_fusion_tasks = gr.Dataset(
|
251 |
-
samples=
|
252 |
label='Condition+Subject Fusion',
|
253 |
samples_per_page=1000,
|
254 |
components=[text_condition_subject_fusion_tasks])
|
255 |
|
256 |
text_style_transfer_with_subject_tasks = gr.Textbox(label="Task", visible=False)
|
257 |
style_transfer_with_subject_tasks = gr.Dataset(
|
258 |
-
samples=
|
259 |
label='Style Transfer with Subject',
|
260 |
samples_per_page=1000,
|
261 |
components=[text_style_transfer_with_subject_tasks])
|
262 |
|
263 |
text_condition_subject_style_fusion_tasks = gr.Textbox(label="Task", visible=False)
|
264 |
condition_subject_style_fusion_tasks = gr.Dataset(
|
265 |
-
samples=
|
266 |
label='Condition+Subject+Style Fusion',
|
267 |
samples_per_page=1000,
|
268 |
components=[text_condition_subject_style_fusion_tasks])
|
269 |
|
270 |
text_editing_with_subject_tasks = gr.Textbox(label="Task", visible=False)
|
271 |
editing_with_subject_tasks = gr.Dataset(
|
272 |
-
samples=
|
273 |
label='Editing with Subject',
|
274 |
samples_per_page=1000,
|
275 |
components=[text_editing_with_subject_tasks])
|
276 |
|
277 |
text_image_restoration_with_subject_tasks = gr.Textbox(label="Task", visible=False)
|
278 |
image_restoration_with_subject_tasks = gr.Dataset(
|
279 |
-
samples=
|
280 |
label='Image Restoration with Subject',
|
281 |
samples_per_page=1000,
|
282 |
components=[text_image_restoration_with_subject_tasks])
|
@@ -318,7 +320,6 @@ def create_demo(model):
|
|
318 |
def generate_image(*inputs):
|
319 |
images = []
|
320 |
if grid_h.value + 1 != model.grid_h or grid_w.value != model.grid_w:
|
321 |
-
print(grid_h.value, grid_w.value, model.grid_h, model.grid_w, type(grid_h.value), type(model.grid_h))
|
322 |
raise gr.Error('Please wait for the loading to complete.')
|
323 |
for i in range(model.grid_h):
|
324 |
images.append([])
|
@@ -337,7 +338,7 @@ def create_demo(model):
|
|
337 |
upsampling_steps=upsampling_steps, upsampling_noise=upsampling_noise
|
338 |
)
|
339 |
except Exception as e:
|
340 |
-
raise gr.Error('Process error. Possible that the task examples have not finished loading yet. Error: ' +
|
341 |
|
342 |
output = gr.update(
|
343 |
elem_id='output_gallery',
|
@@ -375,104 +376,104 @@ def create_demo(model):
|
|
375 |
update_grid(cur_hrid_h, cur_hrid_w)
|
376 |
output = gr.update(
|
377 |
elem_id='output_gallery',
|
378 |
-
value=output,
|
379 |
-
columns=min(
|
380 |
-
rows=int(
|
381 |
return [output] + current_example + state
|
382 |
|
383 |
dense_prediction_tasks.click(
|
384 |
-
partial(process_tasks, func=
|
385 |
inputs=[dense_prediction_tasks],
|
386 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
387 |
show_progress="full",
|
388 |
show_progress_on=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps] + [generate_btn])
|
389 |
|
390 |
conditional_generation_tasks.click(
|
391 |
-
partial(process_tasks, func=
|
392 |
inputs=[conditional_generation_tasks],
|
393 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
394 |
show_progress="full")
|
395 |
|
396 |
image_restoration_tasks.click(
|
397 |
-
partial(process_tasks, func=
|
398 |
inputs=[image_restoration_tasks],
|
399 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
400 |
show_progress="full")
|
401 |
|
402 |
style_transfer_tasks.click(
|
403 |
-
partial(process_tasks, func=
|
404 |
inputs=[style_transfer_tasks],
|
405 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
406 |
show_progress="full")
|
407 |
|
408 |
style_condition_fusion_tasks.click(
|
409 |
-
partial(process_tasks, func=
|
410 |
inputs=[style_condition_fusion_tasks],
|
411 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
412 |
show_progress="full")
|
413 |
|
414 |
relighting_tasks.click(
|
415 |
-
partial(process_tasks, func=
|
416 |
inputs=[relighting_tasks],
|
417 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
418 |
show_progress="full")
|
419 |
|
420 |
tryon_tasks.click(
|
421 |
-
partial(process_tasks, func=
|
422 |
inputs=[tryon_tasks],
|
423 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
424 |
show_progress="full")
|
425 |
|
426 |
photodoodle_tasks.click(
|
427 |
-
partial(process_tasks, func=
|
428 |
inputs=[photodoodle_tasks],
|
429 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
430 |
show_progress="full")
|
431 |
|
432 |
editing_tasks.click(
|
433 |
-
partial(process_tasks, func=
|
434 |
inputs=[editing_tasks],
|
435 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
436 |
show_progress="full")
|
437 |
|
438 |
unseen_tasks.click(
|
439 |
-
partial(process_tasks, func=
|
440 |
inputs=[unseen_tasks],
|
441 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
442 |
show_progress="full")
|
443 |
|
444 |
subject_driven_tasks.click(
|
445 |
-
partial(process_tasks, func=
|
446 |
inputs=[subject_driven_tasks],
|
447 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
448 |
show_progress="full")
|
449 |
|
450 |
style_transfer_with_subject_tasks.click(
|
451 |
-
partial(process_tasks, func=
|
452 |
inputs=[style_transfer_with_subject_tasks],
|
453 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
454 |
show_progress="full")
|
455 |
|
456 |
condition_subject_fusion_tasks.click(
|
457 |
-
partial(process_tasks, func=
|
458 |
inputs=[condition_subject_fusion_tasks],
|
459 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
460 |
show_progress="full")
|
461 |
|
462 |
condition_subject_style_fusion_tasks.click(
|
463 |
-
partial(process_tasks, func=
|
464 |
inputs=[condition_subject_style_fusion_tasks],
|
465 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
466 |
show_progress="full")
|
467 |
|
468 |
editing_with_subject_tasks.click(
|
469 |
-
partial(process_tasks, func=
|
470 |
inputs=[editing_with_subject_tasks],
|
471 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
472 |
show_progress="full")
|
473 |
|
474 |
image_restoration_with_subject_tasks.click(
|
475 |
-
partial(process_tasks, func=
|
476 |
inputs=[image_restoration_with_subject_tasks],
|
477 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
478 |
show_progress="full")
|
@@ -496,7 +497,7 @@ def create_demo(model):
|
|
496 |
|
497 |
|
498 |
# @spaces.GPU(duration=120)
|
499 |
-
@spaces.GPU(duration=10)
|
500 |
def generate(
|
501 |
images,
|
502 |
prompts,
|
@@ -514,7 +515,7 @@ def generate(
|
|
514 |
|
515 |
def parse_args():
|
516 |
parser = argparse.ArgumentParser()
|
517 |
-
parser.add_argument("--model_path", type=str, default="
|
518 |
parser.add_argument("--precision", type=str, choices=["fp32", "bf16", "fp16"], default="bf16")
|
519 |
parser.add_argument("--resolution", type=int, default=384)
|
520 |
return parser.parse_args()
|
@@ -523,7 +524,7 @@ def parse_args():
|
|
523 |
if __name__ == "__main__":
|
524 |
args = parse_args()
|
525 |
|
526 |
-
# snapshot_download(repo_id="VisualCloze/VisualCloze", repo_type="model", local_dir="
|
527 |
|
528 |
# Initialize model
|
529 |
model = VisualClozeModel(resolution=args.resolution, model_path=args.model_path, precision=args.precision)
|
@@ -532,5 +533,5 @@ if __name__ == "__main__":
|
|
532 |
demo = create_demo(model)
|
533 |
|
534 |
# Start Gradio server
|
535 |
-
demo.launch()
|
536 |
-
|
|
|
1 |
import argparse
|
2 |
+
# import spaces
|
3 |
from visualcloze import VisualClozeModel
|
4 |
import gradio as gr
|
5 |
+
import examples
|
6 |
from functools import partial
|
7 |
from data.prefix_instruction import get_layout_instruction
|
8 |
from huggingface_hub import snapshot_download
|
|
|
15 |
default_upsampling_noise = 0.4
|
16 |
default_steps = 30
|
17 |
|
|
|
|
|
18 |
|
19 |
+
GUIDANCE = """
|
|
|
20 |
|
21 |
## 📋 Quick Start Guide:
|
22 |
1. Adjust **Number of In-context Examples**, 0 disables in-context learning.
|
|
|
38 |
the runtime is approximately **110s**.
|
39 |
**Deploying locally with an 80G A100 can reduce the runtime by more than half.**
|
40 |
|
41 |
+
### Note: For better quality, you can deploy the demo locally using the [model](https://huggingface.co/VisualCloze/VisualCloze/blob/main/visualcloze-512-lora.pth), which supports a higher resolution than this online demo, by following the instructions in the [GitHub repository](https://github.com/lzyhha/VisualCloze/tree/main?tab=readme-ov-file#2-web-demo-gradio).
|
42 |
"""
|
43 |
|
44 |
CITATION = r"""
|
|
|
51 |
@article{li2025visualcloze,
|
52 |
title={VisualCloze: A Universal Image Generation Framework via Visual In-Context Learning},
|
53 |
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},
|
54 |
+
journal={arXiv preprint arxiv:},
|
55 |
year={2025}
|
56 |
}
|
57 |
```
|
58 |
📋 **License**
|
59 |
<br>
|
60 |
+
This project is licensed under apache-2.0.
|
61 |
+
|
62 |
+
📧 **Contact**
|
63 |
+
<br>
|
64 |
+
Need help or have questions? Contact us at: lizhongyu [AT] mail.nankai.edu.cn.
|
65 |
"""
|
66 |
|
67 |
NOTE = r"""
|
|
|
152 |
steps = gr.Slider(label="Steps", minimum=1, maximum=100, value=default_steps, step=1)
|
153 |
cfg = gr.Slider(label="CFG Scale", minimum=1.0, maximum=50.0, value=30, step=1)
|
154 |
upsampling_steps = gr.Slider(label="Upsampling steps (SDEdit)", minimum=1, maximum=100.0, value=10, step=1)
|
155 |
+
upsampling_noise = gr.Slider(label="Upsampling noise (SDEdit)", minimum=0, maximum=1.0, value=default_upsampling_noise, step=0.05)
|
156 |
|
157 |
gr.Markdown(CITATION)
|
158 |
|
|
|
172 |
gr.Markdown("# Task Examples")
|
173 |
text_dense_prediction_tasks = gr.Textbox(label="Task", visible=False)
|
174 |
dense_prediction_tasks = gr.Dataset(
|
175 |
+
samples=examples.dense_prediction_text,
|
176 |
label='Dense Prediction',
|
177 |
samples_per_page=1000,
|
178 |
components=[text_dense_prediction_tasks])
|
179 |
|
180 |
text_conditional_generation_tasks = gr.Textbox(label="Task", visible=False)
|
181 |
conditional_generation_tasks = gr.Dataset(
|
182 |
+
samples=examples.conditional_generation_text,
|
183 |
label='Conditional Generation',
|
184 |
samples_per_page=1000,
|
185 |
components=[text_conditional_generation_tasks])
|
186 |
|
187 |
text_image_restoration_tasks = gr.Textbox(label="Task", visible=False)
|
188 |
image_restoration_tasks = gr.Dataset(
|
189 |
+
samples=examples.image_restoration_text,
|
190 |
label='Image Restoration',
|
191 |
samples_per_page=1000,
|
192 |
components=[text_image_restoration_tasks])
|
193 |
|
194 |
text_style_transfer_tasks = gr.Textbox(label="Task", visible=False)
|
195 |
style_transfer_tasks = gr.Dataset(
|
196 |
+
samples=examples.style_transfer_text,
|
197 |
label='Style Transfer',
|
198 |
samples_per_page=1000,
|
199 |
components=[text_style_transfer_tasks])
|
200 |
|
201 |
text_style_condition_fusion_tasks = gr.Textbox(label="Task", visible=False)
|
202 |
style_condition_fusion_tasks = gr.Dataset(
|
203 |
+
samples=examples.style_condition_fusion_text,
|
204 |
label='Style Condition Fusion',
|
205 |
samples_per_page=1000,
|
206 |
components=[text_style_condition_fusion_tasks])
|
207 |
|
208 |
text_tryon_tasks = gr.Textbox(label="Task", visible=False)
|
209 |
tryon_tasks = gr.Dataset(
|
210 |
+
samples=examples.tryon_text,
|
211 |
label='Virtual Try-On',
|
212 |
samples_per_page=1000,
|
213 |
components=[text_tryon_tasks])
|
214 |
|
215 |
text_relighting_tasks = gr.Textbox(label="Task", visible=False)
|
216 |
relighting_tasks = gr.Dataset(
|
217 |
+
samples=examples.relighting_text,
|
218 |
label='Relighting',
|
219 |
samples_per_page=1000,
|
220 |
components=[text_relighting_tasks])
|
221 |
|
222 |
text_photodoodle_tasks = gr.Textbox(label="Task", visible=False)
|
223 |
photodoodle_tasks = gr.Dataset(
|
224 |
+
samples=examples.photodoodle_text,
|
225 |
label='Photodoodle',
|
226 |
samples_per_page=1000,
|
227 |
components=[text_photodoodle_tasks])
|
228 |
|
229 |
text_editing_tasks = gr.Textbox(label="Task", visible=False)
|
230 |
editing_tasks = gr.Dataset(
|
231 |
+
samples=examples.editing_text,
|
232 |
label='Editing',
|
233 |
samples_per_page=1000,
|
234 |
components=[text_editing_tasks])
|
235 |
|
236 |
text_unseen_tasks = gr.Textbox(label="Task", visible=False)
|
237 |
unseen_tasks = gr.Dataset(
|
238 |
+
samples=examples.unseen_tasks_text,
|
239 |
label='Unseen Tasks (May produce unstable effects)',
|
240 |
samples_per_page=1000,
|
241 |
components=[text_unseen_tasks])
|
|
|
243 |
gr.Markdown("# Subject-driven Tasks Examples")
|
244 |
text_subject_driven_tasks = gr.Textbox(label="Task", visible=False)
|
245 |
subject_driven_tasks = gr.Dataset(
|
246 |
+
samples=examples.subject_driven_text,
|
247 |
label='Subject-driven Generation',
|
248 |
samples_per_page=1000,
|
249 |
components=[text_subject_driven_tasks])
|
250 |
|
251 |
text_condition_subject_fusion_tasks = gr.Textbox(label="Task", visible=False)
|
252 |
condition_subject_fusion_tasks = gr.Dataset(
|
253 |
+
samples=examples.condition_subject_fusion_text,
|
254 |
label='Condition+Subject Fusion',
|
255 |
samples_per_page=1000,
|
256 |
components=[text_condition_subject_fusion_tasks])
|
257 |
|
258 |
text_style_transfer_with_subject_tasks = gr.Textbox(label="Task", visible=False)
|
259 |
style_transfer_with_subject_tasks = gr.Dataset(
|
260 |
+
samples=examples.style_transfer_with_subject_text,
|
261 |
label='Style Transfer with Subject',
|
262 |
samples_per_page=1000,
|
263 |
components=[text_style_transfer_with_subject_tasks])
|
264 |
|
265 |
text_condition_subject_style_fusion_tasks = gr.Textbox(label="Task", visible=False)
|
266 |
condition_subject_style_fusion_tasks = gr.Dataset(
|
267 |
+
samples=examples.condition_subject_style_fusion_text,
|
268 |
label='Condition+Subject+Style Fusion',
|
269 |
samples_per_page=1000,
|
270 |
components=[text_condition_subject_style_fusion_tasks])
|
271 |
|
272 |
text_editing_with_subject_tasks = gr.Textbox(label="Task", visible=False)
|
273 |
editing_with_subject_tasks = gr.Dataset(
|
274 |
+
samples=examples.editing_with_subject_text,
|
275 |
label='Editing with Subject',
|
276 |
samples_per_page=1000,
|
277 |
components=[text_editing_with_subject_tasks])
|
278 |
|
279 |
text_image_restoration_with_subject_tasks = gr.Textbox(label="Task", visible=False)
|
280 |
image_restoration_with_subject_tasks = gr.Dataset(
|
281 |
+
samples=examples.image_restoration_with_subject_text,
|
282 |
label='Image Restoration with Subject',
|
283 |
samples_per_page=1000,
|
284 |
components=[text_image_restoration_with_subject_tasks])
|
|
|
320 |
def generate_image(*inputs):
|
321 |
images = []
|
322 |
if grid_h.value + 1 != model.grid_h or grid_w.value != model.grid_w:
|
|
|
323 |
raise gr.Error('Please wait for the loading to complete.')
|
324 |
for i in range(model.grid_h):
|
325 |
images.append([])
|
|
|
338 |
upsampling_steps=upsampling_steps, upsampling_noise=upsampling_noise
|
339 |
)
|
340 |
except Exception as e:
|
341 |
+
raise gr.Error('Process error. Possible that the task examples have not finished loading yet. Error: ' + e)
|
342 |
|
343 |
output = gr.update(
|
344 |
elem_id='output_gallery',
|
|
|
376 |
update_grid(cur_hrid_h, cur_hrid_w)
|
377 |
output = gr.update(
|
378 |
elem_id='output_gallery',
|
379 |
+
value=[o for o, m in zip(output, mask) if m == 1],
|
380 |
+
columns=min(sum(mask), 2),
|
381 |
+
rows=int(sum(mask) / 2 + 0.5))
|
382 |
return [output] + current_example + state
|
383 |
|
384 |
dense_prediction_tasks.click(
|
385 |
+
partial(process_tasks, func=examples.process_dense_prediction_tasks),
|
386 |
inputs=[dense_prediction_tasks],
|
387 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
388 |
show_progress="full",
|
389 |
show_progress_on=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps] + [generate_btn])
|
390 |
|
391 |
conditional_generation_tasks.click(
|
392 |
+
partial(process_tasks, func=examples.process_conditional_generation_tasks),
|
393 |
inputs=[conditional_generation_tasks],
|
394 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
395 |
show_progress="full")
|
396 |
|
397 |
image_restoration_tasks.click(
|
398 |
+
partial(process_tasks, func=examples.process_image_restoration_tasks),
|
399 |
inputs=[image_restoration_tasks],
|
400 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
401 |
show_progress="full")
|
402 |
|
403 |
style_transfer_tasks.click(
|
404 |
+
partial(process_tasks, func=examples.process_style_transfer_tasks),
|
405 |
inputs=[style_transfer_tasks],
|
406 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
407 |
show_progress="full")
|
408 |
|
409 |
style_condition_fusion_tasks.click(
|
410 |
+
partial(process_tasks, func=examples.process_style_condition_fusion_tasks),
|
411 |
inputs=[style_condition_fusion_tasks],
|
412 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
413 |
show_progress="full")
|
414 |
|
415 |
relighting_tasks.click(
|
416 |
+
partial(process_tasks, func=examples.process_relighting_tasks),
|
417 |
inputs=[relighting_tasks],
|
418 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
419 |
show_progress="full")
|
420 |
|
421 |
tryon_tasks.click(
|
422 |
+
partial(process_tasks, func=examples.process_tryon_tasks),
|
423 |
inputs=[tryon_tasks],
|
424 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
425 |
show_progress="full")
|
426 |
|
427 |
photodoodle_tasks.click(
|
428 |
+
partial(process_tasks, func=examples.process_photodoodle_tasks),
|
429 |
inputs=[photodoodle_tasks],
|
430 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
431 |
show_progress="full")
|
432 |
|
433 |
editing_tasks.click(
|
434 |
+
partial(process_tasks, func=examples.process_editing_tasks),
|
435 |
inputs=[editing_tasks],
|
436 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
437 |
show_progress="full")
|
438 |
|
439 |
unseen_tasks.click(
|
440 |
+
partial(process_tasks, func=examples.process_unseen_tasks),
|
441 |
inputs=[unseen_tasks],
|
442 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
443 |
show_progress="full")
|
444 |
|
445 |
subject_driven_tasks.click(
|
446 |
+
partial(process_tasks, func=examples.process_subject_driven_tasks),
|
447 |
inputs=[subject_driven_tasks],
|
448 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
449 |
show_progress="full")
|
450 |
|
451 |
style_transfer_with_subject_tasks.click(
|
452 |
+
partial(process_tasks, func=examples.process_style_transfer_with_subject_tasks),
|
453 |
inputs=[style_transfer_with_subject_tasks],
|
454 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
455 |
show_progress="full")
|
456 |
|
457 |
condition_subject_fusion_tasks.click(
|
458 |
+
partial(process_tasks, func=examples.process_condition_subject_fusion_tasks),
|
459 |
inputs=[condition_subject_fusion_tasks],
|
460 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
461 |
show_progress="full")
|
462 |
|
463 |
condition_subject_style_fusion_tasks.click(
|
464 |
+
partial(process_tasks, func=examples.process_condition_subject_style_fusion_tasks),
|
465 |
inputs=[condition_subject_style_fusion_tasks],
|
466 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
467 |
show_progress="full")
|
468 |
|
469 |
editing_with_subject_tasks.click(
|
470 |
+
partial(process_tasks, func=examples.process_editing_with_subject_tasks),
|
471 |
inputs=[editing_with_subject_tasks],
|
472 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
473 |
show_progress="full")
|
474 |
|
475 |
image_restoration_with_subject_tasks.click(
|
476 |
+
partial(process_tasks, func=examples.process_image_restoration_with_subject_tasks),
|
477 |
inputs=[image_restoration_with_subject_tasks],
|
478 |
outputs=[output_gallery] + all_image_inputs + [grid_h, grid_w, layout_prompt, task_prompt, content_prompt, upsampling_noise, steps],
|
479 |
show_progress="full")
|
|
|
497 |
|
498 |
|
499 |
# @spaces.GPU(duration=120)
|
500 |
+
# @spaces.GPU(duration=10)
|
501 |
def generate(
|
502 |
images,
|
503 |
prompts,
|
|
|
515 |
|
516 |
def parse_args():
|
517 |
parser = argparse.ArgumentParser()
|
518 |
+
parser.add_argument("--model_path", type=str, default="checkpoints/visualcloze-384-lora.pth")
|
519 |
parser.add_argument("--precision", type=str, choices=["fp32", "bf16", "fp16"], default="bf16")
|
520 |
parser.add_argument("--resolution", type=int, default=384)
|
521 |
return parser.parse_args()
|
|
|
524 |
if __name__ == "__main__":
|
525 |
args = parse_args()
|
526 |
|
527 |
+
# snapshot_download(repo_id="VisualCloze/VisualCloze", repo_type="model", local_dir="checkpoints")
|
528 |
|
529 |
# Initialize model
|
530 |
model = VisualClozeModel(resolution=args.resolution, model_path=args.model_path, precision=args.precision)
|
|
|
533 |
demo = create_demo(model)
|
534 |
|
535 |
# Start Gradio server
|
536 |
+
# demo.launch()
|
537 |
+
demo.launch(share=False, server_port=10050, server_name="0.0.0.0")
|
data/degradation_toolkit/__init__.py
ADDED
File without changes
|
data/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
|
data/degradation_toolkit/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 data.degradation_toolkit.add_degradation_various import *
|
7 |
+
from data.degradation_toolkit.image_operators import *
|
8 |
+
from data.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
|
data/degradation_toolkit/frost/frost1.png
ADDED
![]() |
Git LFS Details
|
data/degradation_toolkit/frost/frost2.png
ADDED
![]() |
Git LFS Details
|
data/degradation_toolkit/frost/frost3.png
ADDED
![]() |
Git LFS Details
|
data/degradation_toolkit/frost/frost4.jpg
ADDED
![]() |
Git LFS Details
|
data/degradation_toolkit/frost/frost5.jpg
ADDED
![]() |
Git LFS Details
|
data/degradation_toolkit/frost/frost6.jpg
ADDED
![]() |
Git LFS Details
|
data/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
|
data/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)
|
data/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)
|
data/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))
|
data/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
|
data/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
|
data/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
|
data/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.)
|
data/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
|
data/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)
|
data/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
|
data/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
|
data/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
|
imgproc.py → data/imgproc.py
RENAMED
File without changes
|
examples/__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
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_ben2-background-removal.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_canny_100_200_512.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_depth-anything-v2_Large.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_dsine_normal_map.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_hed_512.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/012cd3921e1f97d761eeff580f918ff9/012cd3921e1f97d761eeff580f918ff9_sam2_mask.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_instantx-style_0_style.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/0fdaecdb7906a1bf0d6e202363f15de3/0fdaecdb7906a1bf0d6e202363f15de3_qwen2_5_mask.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_instantx-style_0_style.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/10d7dcae5240b8cc8c9427e876b4f462/10d7dcae5240b8cc8c9427e876b4f462_qwen2_5_mask.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_canny_100_200_512.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_depth-anything-v2_Large.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_dsine_normal_map.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_hed_512.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_openpose_fullres_nohand.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2b74476568f7562a6aa832d423132ed3/2b74476568f7562a6aa832d423132ed3_sam2_mask.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2c4e256fa512cb7e7f433f4c7f9101de/2c4e256fa512cb7e7f433f4c7f9101de.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2c4e256fa512cb7e7f433f4c7f9101de/2c4e256fa512cb7e7f433f4c7f9101de_ben2-background-removal.jpg
ADDED
![]() |
Git LFS Details
|
examples/examples/2c4e256fa512cb7e7f433f4c7f9101de/2c4e256fa512cb7e7f433f4c7f9101de_canny_100_200_512.jpg
ADDED
![]() |
Git LFS Details
|