Datasets:
Upload 15 files
Browse files- LICENSE.txt +21 -0
- LICENSE_FYSignate1009.txt +21 -0
- LICENSE_fractal-pretraining.txt +21 -0
- params/multi_fractal_ifs_params.json +14 -0
- params/multi_fractal_ifs_params_no_mixup.json +14 -0
- params/settings.json +19 -0
- requirements.txt +1 -0
- src/generator.py +240 -0
- src/generator_no_mixup.py +195 -0
- src/multi_fractal_db/diamondsquare.py +89 -0
- src/multi_fractal_db/ifs.py +373 -0
- src/multi_fractal_db/multi_fractal_dataset.py +72 -0
- src/multi_fractal_db/multi_fractal_generator.py +492 -0
- src/multi_fractal_db/serach_ifs_systems.py +179 -0
- src/validator.py +158 -0
LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2024 ELAN MITSUA Project / Abstract Engine
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
LICENSE_FYSignate1009.txt
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2024 FYSignate1009
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
LICENSE_fractal-pretraining.txt
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 Connor Anderson
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
params/multi_fractal_ifs_params.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"num_classes":1000,
|
3 |
+
"num_image_per_class":1000,
|
4 |
+
"num_systems_per_calss":3,
|
5 |
+
"num_systems": 6000,
|
6 |
+
"niter": 100000,
|
7 |
+
"color": true,
|
8 |
+
"background": true,
|
9 |
+
"patch": true,
|
10 |
+
"n_objects": [4, 6],
|
11 |
+
"size_range":[0.4, 0.6],
|
12 |
+
"jitter_params":true,
|
13 |
+
"image_size":256
|
14 |
+
}
|
params/multi_fractal_ifs_params_no_mixup.json
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"num_classes":1000,
|
3 |
+
"num_image_per_class":1000,
|
4 |
+
"num_systems_per_calss":3,
|
5 |
+
"num_systems": 3000,
|
6 |
+
"niter": 100000,
|
7 |
+
"color": true,
|
8 |
+
"background": true,
|
9 |
+
"patch": true,
|
10 |
+
"n_objects": [3, 6],
|
11 |
+
"size_range":[0.5, 0.8],
|
12 |
+
"jitter_params":true,
|
13 |
+
"image_size":256
|
14 |
+
}
|
params/settings.json
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"numof_thread": 10,
|
3 |
+
"numof_classes": 1000,
|
4 |
+
"numof_instances": 1000,
|
5 |
+
"vertex_num_min": 200,
|
6 |
+
"vertex_num_max": 1000,
|
7 |
+
"perlin_min": 0,
|
8 |
+
"line_num_min": 1,
|
9 |
+
"line_num_max": 200,
|
10 |
+
"line_width": 0.1,
|
11 |
+
"radius_min": 10,
|
12 |
+
"oval_rate": 2,
|
13 |
+
"image_size": 256,
|
14 |
+
"start_pos": 256,
|
15 |
+
"nami_1_min": 0,
|
16 |
+
"nami_2_min": 0,
|
17 |
+
"nami_1_max": 20,
|
18 |
+
"nami_2_max": 20
|
19 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
numba
|
src/generator.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
import gc
|
4 |
+
import json
|
5 |
+
import pickle
|
6 |
+
import cv2
|
7 |
+
import numpy as np
|
8 |
+
from tqdm import tqdm
|
9 |
+
import threading
|
10 |
+
from concurrent.futures import ProcessPoolExecutor
|
11 |
+
|
12 |
+
from multi_fractal_db import ifs
|
13 |
+
from multi_fractal_db import serach_ifs_systems
|
14 |
+
from multi_fractal_db.multi_fractal_dataset import MultiFractalDataset
|
15 |
+
from multi_fractal_db.multi_fractal_generator import MultiGenerator
|
16 |
+
|
17 |
+
from PIL import Image
|
18 |
+
|
19 |
+
class Generator():
|
20 |
+
@classmethod
|
21 |
+
def get_params(cls, params_path):
|
22 |
+
# デバッグ表示
|
23 |
+
cls.debug = True
|
24 |
+
|
25 |
+
# Conner's FractalDBのパラメータ
|
26 |
+
with open(os.path.join(params_path, 'multi_fractal_ifs_params.json')) as f:
|
27 |
+
cls.ifs_params = json.load(f)
|
28 |
+
|
29 |
+
# IFSシステムの探索パラメータ
|
30 |
+
kwargs = dict(
|
31 |
+
# IFSシステム数
|
32 |
+
num_systems=cls.ifs_params["num_systems"],
|
33 |
+
# 連立方程式の数
|
34 |
+
n=(2, 4),
|
35 |
+
bval=1,
|
36 |
+
beta=None,
|
37 |
+
sample_fn=None,
|
38 |
+
)
|
39 |
+
# 全IFSシステムのパラメータ作成
|
40 |
+
sys = serach_ifs_systems.random_systems(**kwargs)
|
41 |
+
cls.ifs_systems = {'params': sys, 'hparams': kwargs}
|
42 |
+
print(f"ifs_systems length {len(cls.ifs_systems['params'])}")
|
43 |
+
|
44 |
+
# デバッグモード
|
45 |
+
cls.debug = True
|
46 |
+
|
47 |
+
return True
|
48 |
+
|
49 |
+
@classmethod
|
50 |
+
def generate(cls, out_path, start_index : int = None, end_index : int = None, jpeg_quality : int = 95):
|
51 |
+
if cls.debug:
|
52 |
+
print(out_path)
|
53 |
+
|
54 |
+
# MixUp元フォルダ作成
|
55 |
+
base_path = out_path.replace("pretrain", "base")
|
56 |
+
|
57 |
+
# クラス数
|
58 |
+
num_classes = cls.ifs_params['num_classes']
|
59 |
+
# 1クラスあたりの画像枚数
|
60 |
+
num_image_per_class = cls.ifs_params['num_image_per_class']
|
61 |
+
|
62 |
+
if start_index is None:
|
63 |
+
start_index = 0
|
64 |
+
if end_index is None:
|
65 |
+
end_index = num_classes
|
66 |
+
|
67 |
+
# 全クラス分の画像作成
|
68 |
+
for iclass in range(start_index, end_index):
|
69 |
+
print(f"iclass = {iclass:05}")
|
70 |
+
class_dir = os.path.join(out_path, f"{iclass:05}")
|
71 |
+
if os.path.exists(class_dir):
|
72 |
+
files = os.listdir(class_dir)
|
73 |
+
files = [f for f in files if f.endswith(".jpg")]
|
74 |
+
if len(files) == num_image_per_class:
|
75 |
+
print(f"this iclass already processed = {iclass:05}")
|
76 |
+
once_load_failed = False
|
77 |
+
for f in files:
|
78 |
+
path = os.path.join(class_dir, f)
|
79 |
+
try:
|
80 |
+
img = Image.open(path)
|
81 |
+
except:
|
82 |
+
once_load_failed = True
|
83 |
+
break
|
84 |
+
if not once_load_failed:
|
85 |
+
continue
|
86 |
+
else:
|
87 |
+
print(f"[RE] this iclass already processed = {iclass:05}, but file corrupted. ")
|
88 |
+
for f in files:
|
89 |
+
os.remove(os.path.join(class_dir, f))
|
90 |
+
else:
|
91 |
+
for f in files:
|
92 |
+
os.remove(os.path.join(class_dir, f))
|
93 |
+
|
94 |
+
base_images = []
|
95 |
+
# MixUp元ベースクラス作成
|
96 |
+
for ib, ibase in enumerate([iclass*2, iclass*2+1]):
|
97 |
+
# クラスフォルダ
|
98 |
+
|
99 |
+
# 1クラスあたりのIFSシステム数
|
100 |
+
num_systems_per_calss = cls.ifs_params['num_systems_per_calss']
|
101 |
+
# 使用するIFSシステムパラメータ
|
102 |
+
st = ibase * num_systems_per_calss
|
103 |
+
en = (ibase+1)*num_systems_per_calss
|
104 |
+
# print(f"ib={ib}, ibase={ibase}, st={st}, en={en}")
|
105 |
+
ifs_syss = {'params':cls.ifs_systems['params'][st:en],
|
106 |
+
'hparams': cls.ifs_systems['hparams']}
|
107 |
+
|
108 |
+
# chaceサイズ
|
109 |
+
#cache_size = num_systems_per_calss * num_image_per_class
|
110 |
+
cache_size = min(500, num_image_per_class*num_systems_per_calss)
|
111 |
+
|
112 |
+
# 別スレッドで実行
|
113 |
+
future = make_multi_fractal_images(
|
114 |
+
ifs_syss, cls.ifs_params, num_systems_per_calss,
|
115 |
+
num_image_per_class, cache_size, cls.debug, out_path, ibase)
|
116 |
+
base_images.append(future)
|
117 |
+
|
118 |
+
# MixUp画像作成
|
119 |
+
# クラスフォルダ
|
120 |
+
class_dir = os.path.join(out_path, f"{iclass:05}")
|
121 |
+
if os.path.exists(class_dir)==False:
|
122 |
+
os.makedirs(class_dir, exist_ok=True)
|
123 |
+
|
124 |
+
# 全画像作成
|
125 |
+
for idx in tqdm(range(num_image_per_class)):
|
126 |
+
# MixUp元画像の読み込み
|
127 |
+
image_base1 = base_images[0][idx]
|
128 |
+
image_base2 = base_images[1][idx]
|
129 |
+
# MixUp
|
130 |
+
alpha = 1.0
|
131 |
+
lam = np.clip(np.random.beta(alpha, alpha), 0.4, 0.6)
|
132 |
+
image_mixup = lam * image_base1 + (1 - lam) * image_base2
|
133 |
+
image_mixup = image_mixup.astype(np.uint8)
|
134 |
+
# 画像書き出し
|
135 |
+
image_file = os.path.join(class_dir, f"{idx:05}.jpg")
|
136 |
+
cv2.imwrite(image_file, image_mixup, [cv2.IMWRITE_JPEG_QUALITY, jpeg_quality])
|
137 |
+
|
138 |
+
# MixUp元フォルダの削除
|
139 |
+
base_images = None
|
140 |
+
del base_images
|
141 |
+
futures = None
|
142 |
+
del futures
|
143 |
+
gc.collect()
|
144 |
+
|
145 |
+
|
146 |
+
def make_multi_fractal_images(ifs_systems, ifs_params,
|
147 |
+
num_systems_per_calss, num_image_per_class, cache_size,
|
148 |
+
debug, out_path, ibase):
|
149 |
+
# Conner's Multi-FractalDB
|
150 |
+
multi_fractal_dataset = MultiFractalDataset(
|
151 |
+
ifs_params=ifs_systems,
|
152 |
+
num_systems=num_systems_per_calss,
|
153 |
+
num_class=1,
|
154 |
+
per_class=num_image_per_class,
|
155 |
+
generator=MultiGenerator(
|
156 |
+
color=ifs_params["color"],
|
157 |
+
background=ifs_params["background"],
|
158 |
+
niter=ifs_params["niter"],
|
159 |
+
patch=ifs_params["patch"],
|
160 |
+
n_objects=ifs_params["n_objects"],
|
161 |
+
size_range=ifs_params["size_range"],
|
162 |
+
jitter_params=ifs_params["jitter_params"],
|
163 |
+
cache_size=cache_size,
|
164 |
+
size=ifs_params["image_size"]
|
165 |
+
),
|
166 |
+
period=2)
|
167 |
+
|
168 |
+
if debug:
|
169 |
+
# 確認用フォルダ
|
170 |
+
check_dir = out_path.replace("pretrain", "check")
|
171 |
+
if os.path.exists(check_dir)==False:
|
172 |
+
os.makedirs(check_dir, exist_ok=True)
|
173 |
+
# 使用するIFSフラクタルを描画
|
174 |
+
for i, sys in enumerate(ifs_systems['params']):
|
175 |
+
image_gray = multi_fractal_dataset.generator.render(sys['system'])
|
176 |
+
image_gray = (image_gray * 255).astype(np.uint8)
|
177 |
+
#image_gray = cv2.applyColorMap(image_gray, cv2.COLORMAP_BONE)
|
178 |
+
image_file = os.path.join(check_dir, f"{ibase:05}_{i:02}.jpg")
|
179 |
+
cv2.imwrite(image_file, image_gray)
|
180 |
+
|
181 |
+
# 全画像数
|
182 |
+
base_images = []
|
183 |
+
num_fractal_images = len(multi_fractal_dataset)
|
184 |
+
class_dir = os.path.join(check_dir, f"{ibase:05}")
|
185 |
+
os.makedirs(class_dir, exist_ok=True)
|
186 |
+
for idx in range(num_fractal_images):
|
187 |
+
# 画像とラベルの取得
|
188 |
+
image, labels = multi_fractal_dataset[idx]
|
189 |
+
# 画像書き出し
|
190 |
+
image_file = os.path.join(class_dir, f"{idx:05}.png")
|
191 |
+
cv2.imwrite(image_file, image)
|
192 |
+
base_images.append(image)
|
193 |
+
|
194 |
+
# メモリ解放
|
195 |
+
multi_fractal_dataset = None
|
196 |
+
del multi_fractal_dataset
|
197 |
+
gc.collect()
|
198 |
+
|
199 |
+
return base_images
|
200 |
+
|
201 |
+
def multifractal_main(outputdir, start_index, end_index, jpeg_quality):
|
202 |
+
Generator.get_params('../params')
|
203 |
+
Generator.generate(outputdir, start_index, end_index, jpeg_quality)
|
204 |
+
|
205 |
+
if __name__ == "__main__":
|
206 |
+
import argparse
|
207 |
+
from tqdm import tqdm
|
208 |
+
from copy import deepcopy
|
209 |
+
import concurrent.futures
|
210 |
+
import time
|
211 |
+
from typing import List
|
212 |
+
import multiprocessing
|
213 |
+
worker_num=multiprocessing.cpu_count()
|
214 |
+
print("workers : ", worker_num)
|
215 |
+
parser = argparse.ArgumentParser()
|
216 |
+
parser.add_argument('--fpath', type=str, default="../output/pretrain")
|
217 |
+
parser.add_argument('--total', type=int, default=1000)
|
218 |
+
parser.add_argument('--step', type=int, default=1000//worker_num+1)
|
219 |
+
parser.add_argument('--offset', type=int, default=0)
|
220 |
+
parser.add_argument('--jpeg_quality', type=int, default=95)
|
221 |
+
|
222 |
+
args = parser.parse_args()
|
223 |
+
|
224 |
+
os.makedirs(args.fpath, exist_ok=True)
|
225 |
+
|
226 |
+
executor = concurrent.futures.ProcessPoolExecutor(max_workers=worker_num)
|
227 |
+
futures : List[concurrent.futures.Future] = []
|
228 |
+
|
229 |
+
for i in range(args.offset, args.total, args.step):
|
230 |
+
start_index = i
|
231 |
+
end_index = i + args.step
|
232 |
+
futures.append(executor.submit(multifractal_main, args.fpath, start_index, end_index, args.jpeg_quality))
|
233 |
+
|
234 |
+
for future in tqdm(concurrent.futures.as_completed(futures)):
|
235 |
+
try:
|
236 |
+
rr = future.result()
|
237 |
+
except Exception as exc:
|
238 |
+
print('generated an exception: %s' % (exc))
|
239 |
+
|
240 |
+
print("All done!")
|
src/generator_no_mixup.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
import gc
|
4 |
+
import json
|
5 |
+
import pickle
|
6 |
+
import cv2
|
7 |
+
import numpy as np
|
8 |
+
from tqdm import tqdm
|
9 |
+
import threading
|
10 |
+
from concurrent.futures import ProcessPoolExecutor
|
11 |
+
|
12 |
+
from multi_fractal_db import ifs
|
13 |
+
from multi_fractal_db import serach_ifs_systems
|
14 |
+
from multi_fractal_db.multi_fractal_dataset import MultiFractalDataset
|
15 |
+
from multi_fractal_db.multi_fractal_generator import MultiGenerator
|
16 |
+
|
17 |
+
from PIL import Image
|
18 |
+
|
19 |
+
class Generator():
|
20 |
+
@classmethod
|
21 |
+
def get_params(cls, params_path):
|
22 |
+
# デバッグ表示
|
23 |
+
cls.debug = True
|
24 |
+
|
25 |
+
# Conner's FractalDBのパラメータ
|
26 |
+
with open(os.path.join(params_path, 'multi_fractal_ifs_params_no_mixup.json')) as f:
|
27 |
+
cls.ifs_params = json.load(f)
|
28 |
+
|
29 |
+
# IFSシステムの探索パラメータ
|
30 |
+
kwargs = dict(
|
31 |
+
# IFSシステム数
|
32 |
+
num_systems=cls.ifs_params["num_systems"],
|
33 |
+
# 連立方程式の数
|
34 |
+
n=(2, 4),
|
35 |
+
bval=1,
|
36 |
+
beta=None,
|
37 |
+
sample_fn=None,
|
38 |
+
)
|
39 |
+
# 全IFSシステムのパラメータ作成
|
40 |
+
sys = serach_ifs_systems.random_systems(**kwargs)
|
41 |
+
cls.ifs_systems = {'params': sys, 'hparams': kwargs}
|
42 |
+
# print(f"ifs_systems length {len(cls.ifs_systems['params'])}")
|
43 |
+
|
44 |
+
# デバッグモード
|
45 |
+
cls.debug = True
|
46 |
+
|
47 |
+
return True
|
48 |
+
|
49 |
+
@classmethod
|
50 |
+
def generate(cls, out_path, start_index : int = None, end_index : int = None, jpeg_quality : int = 95):
|
51 |
+
# if cls.debug:
|
52 |
+
# print(out_path)
|
53 |
+
|
54 |
+
try:
|
55 |
+
|
56 |
+
# クラス数
|
57 |
+
num_classes = cls.ifs_params['num_classes']
|
58 |
+
# 1クラスあたりの画像枚数
|
59 |
+
num_image_per_class = cls.ifs_params['num_image_per_class']
|
60 |
+
|
61 |
+
if start_index is None:
|
62 |
+
start_index = 0
|
63 |
+
if end_index is None:
|
64 |
+
end_index = num_classes
|
65 |
+
|
66 |
+
# 全クラス分の画像作成
|
67 |
+
for iclass in tqdm(range(start_index, end_index), total=end_index-start_index):
|
68 |
+
# 1クラスあたりのIFSシステム数
|
69 |
+
num_systems_per_calss = cls.ifs_params['num_systems_per_calss']
|
70 |
+
# 使用するIFSシステムパラメータ
|
71 |
+
st = iclass * num_systems_per_calss
|
72 |
+
en = (iclass+1)*num_systems_per_calss
|
73 |
+
# print(f"ib={ib}, ibase={ibase}, st={st}, en={en}")
|
74 |
+
ifs_syss = {'params':cls.ifs_systems['params'][st:en],
|
75 |
+
'hparams': cls.ifs_systems['hparams']}
|
76 |
+
|
77 |
+
# chaceサイズ
|
78 |
+
# cache_size = num_systems_per_calss * num_image_per_class
|
79 |
+
cache_size = min(500, num_image_per_class)
|
80 |
+
|
81 |
+
make_multi_fractal_images(
|
82 |
+
ifs_syss, cls.ifs_params, num_systems_per_calss,
|
83 |
+
num_image_per_class, cache_size, cls.debug, out_path, iclass, jpeg_quality)
|
84 |
+
gc.collect()
|
85 |
+
except Exception as e:
|
86 |
+
print(e)
|
87 |
+
import traceback
|
88 |
+
print(traceback.format_exc())
|
89 |
+
|
90 |
+
|
91 |
+
return True
|
92 |
+
|
93 |
+
|
94 |
+
def make_multi_fractal_images(ifs_systems, ifs_params,
|
95 |
+
num_systems_per_calss, num_image_per_class, cache_size,
|
96 |
+
debug, out_path, ibase, jpeg_quality):
|
97 |
+
# Conner's Multi-FractalDB
|
98 |
+
multi_fractal_dataset = MultiFractalDataset(
|
99 |
+
ifs_params=ifs_systems,
|
100 |
+
num_systems=num_systems_per_calss,
|
101 |
+
num_class=1,
|
102 |
+
per_class=num_image_per_class,
|
103 |
+
generator=MultiGenerator(
|
104 |
+
color=ifs_params["color"],
|
105 |
+
background=ifs_params["background"],
|
106 |
+
niter=ifs_params["niter"],
|
107 |
+
patch=ifs_params["patch"],
|
108 |
+
n_objects=ifs_params["n_objects"],
|
109 |
+
size_range=ifs_params["size_range"],
|
110 |
+
jitter_params=ifs_params["jitter_params"],
|
111 |
+
cache_size=cache_size,
|
112 |
+
size=ifs_params["image_size"],
|
113 |
+
seed=ibase,
|
114 |
+
n_instance_types=num_systems_per_calss,
|
115 |
+
),
|
116 |
+
period=2)
|
117 |
+
|
118 |
+
print(f"jitter success {multi_fractal_dataset.generator.jitter_success}")
|
119 |
+
print(f"jitter failed {multi_fractal_dataset.generator.jitter_failed}")
|
120 |
+
|
121 |
+
if debug:
|
122 |
+
# 確認用フォルダ
|
123 |
+
check_dir = out_path.replace("pretrain", "check")
|
124 |
+
if os.path.exists(check_dir)==False:
|
125 |
+
os.makedirs(check_dir, exist_ok=True)
|
126 |
+
# 使用するIFSフラクタルを描画
|
127 |
+
for i, sys in enumerate(ifs_systems['params']):
|
128 |
+
image_gray = multi_fractal_dataset.generator.render(sys['system'])
|
129 |
+
image_gray = (image_gray * 255).astype(np.uint8)
|
130 |
+
#image_gray = cv2.applyColorMap(image_gray, cv2.COLORMAP_BONE)
|
131 |
+
image_file = os.path.join(check_dir, f"{ibase:05}_{i:02}.jpg")
|
132 |
+
cv2.imwrite(image_file, image_gray)
|
133 |
+
|
134 |
+
# 全画像数
|
135 |
+
base_images = []
|
136 |
+
num_fractal_images = len(multi_fractal_dataset)
|
137 |
+
class_dir = os.path.join(out_path, f"{ibase:05}")
|
138 |
+
os.makedirs(class_dir, exist_ok=True)
|
139 |
+
for idx in range(num_fractal_images):
|
140 |
+
# 画像とラベルの取得
|
141 |
+
image, labels = multi_fractal_dataset[idx]
|
142 |
+
# 画像書き出し
|
143 |
+
image_file = os.path.join(class_dir, f"fractal_{ibase:05}_instance_{idx:04}.jpg")
|
144 |
+
cv2.imwrite(image_file, image, [cv2.IMWRITE_JPEG_QUALITY, jpeg_quality])
|
145 |
+
base_images.append(image)
|
146 |
+
|
147 |
+
# メモリ解放
|
148 |
+
multi_fractal_dataset = None
|
149 |
+
del multi_fractal_dataset
|
150 |
+
gc.collect()
|
151 |
+
|
152 |
+
return base_images
|
153 |
+
|
154 |
+
def multifractal_main(outputdir, start_index, end_index, jpeg_quality):
|
155 |
+
Generator.get_params('../params')
|
156 |
+
Generator.generate(outputdir, start_index, end_index, jpeg_quality)
|
157 |
+
|
158 |
+
if __name__ == "__main__":
|
159 |
+
import argparse
|
160 |
+
from tqdm import tqdm
|
161 |
+
from copy import deepcopy
|
162 |
+
import concurrent.futures
|
163 |
+
import time
|
164 |
+
from typing import List
|
165 |
+
import multiprocessing
|
166 |
+
worker_num=multiprocessing.cpu_count()
|
167 |
+
print("workers : ", worker_num)
|
168 |
+
parser = argparse.ArgumentParser()
|
169 |
+
total_default = 1000
|
170 |
+
parser.add_argument('--fpath', type=str, default="../output/pretrain")
|
171 |
+
parser.add_argument('--total', type=int, default=total_default)
|
172 |
+
parser.add_argument('--step', type=int, default=total_default//worker_num+1)
|
173 |
+
parser.add_argument('--offset', type=int, default=0)
|
174 |
+
parser.add_argument('--jpeg_quality', type=int, default=85)
|
175 |
+
|
176 |
+
args = parser.parse_args()
|
177 |
+
|
178 |
+
os.makedirs(args.fpath, exist_ok=True)
|
179 |
+
|
180 |
+
executor = concurrent.futures.ProcessPoolExecutor(max_workers=worker_num)
|
181 |
+
futures : List[concurrent.futures.Future] = []
|
182 |
+
|
183 |
+
for i in range(args.offset, args.total, args.step):
|
184 |
+
start_index = i
|
185 |
+
end_index = min(args.total, i + args.step)
|
186 |
+
futures.append(executor.submit(multifractal_main, args.fpath, start_index, end_index, args.jpeg_quality))
|
187 |
+
|
188 |
+
for future in tqdm(concurrent.futures.as_completed(futures)):
|
189 |
+
try:
|
190 |
+
rr = future.result()
|
191 |
+
except Exception as exc:
|
192 |
+
print('generated an exception: %s' % (exc))
|
193 |
+
|
194 |
+
executor.shutdown()
|
195 |
+
print("All done!")
|
src/multi_fractal_db/diamondsquare.py
ADDED
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from cv2 import cvtColor, COLOR_HSV2RGB
|
2 |
+
import numba
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
|
6 |
+
@numba.njit(cache=True)
|
7 |
+
def diamond_square(n, decay=0.5, fixed_corners=True):
|
8 |
+
s = 2**n + 1
|
9 |
+
a = np.zeros((s, s))
|
10 |
+
if fixed_corners:
|
11 |
+
a[0, 0] = a[0, s-1] = a[s-1, 0] = a[s-1, s-1] = 0.5
|
12 |
+
else:
|
13 |
+
a[0, 0] = np.random.rand()
|
14 |
+
a[0, s-1] = np.random.rand()
|
15 |
+
a[s-1, 0] = np.random.rand()
|
16 |
+
a[s-1, s-1] = np.random.rand()
|
17 |
+
|
18 |
+
for k in range(1, n+1):
|
19 |
+
m = 0.5 * np.exp(decay * (1-k))
|
20 |
+
ss = s // (2**k)
|
21 |
+
|
22 |
+
# diamond
|
23 |
+
ni = 2**k
|
24 |
+
for i in range(0, ni, 2):
|
25 |
+
# s / 2**k
|
26 |
+
ru = i * ss
|
27 |
+
r = ru + ss
|
28 |
+
rd = r + ss
|
29 |
+
for j in range(0, ni, 2):
|
30 |
+
cl = j * ss
|
31 |
+
c = cl + ss
|
32 |
+
cr = c + ss
|
33 |
+
a[r, c] = 0.25 * (a[ru, cl] + a[ru, cr] + a[rd, cl] + a[rd, cr])
|
34 |
+
a[r, c] += np.random.uniform(-m, m)
|
35 |
+
|
36 |
+
# square
|
37 |
+
ni = 2**k + 1
|
38 |
+
for i in range(ni):
|
39 |
+
r = i * ss
|
40 |
+
if r > 0: ru = r - ss
|
41 |
+
else: ru = s - ss - 1
|
42 |
+
if r < s-1: rd = r + ss
|
43 |
+
else: rd = ss
|
44 |
+
sj = 1 if i % 2 == 0 else 0
|
45 |
+
for j in range(sj, ni, 2):
|
46 |
+
c = j * ss
|
47 |
+
if c > 0: cl = c - ss
|
48 |
+
else: cl = s - ss - 1
|
49 |
+
if c < s-1: cr = c + ss
|
50 |
+
else: cr = ss
|
51 |
+
a[r, c] = 0.25 * (a[ru, c] + a[r, cl] + a[r, cr] + a[rd, c])
|
52 |
+
a[r, c] += np.random.uniform(-m, m)
|
53 |
+
return a
|
54 |
+
|
55 |
+
|
56 |
+
@numba.njit(cache=True)
|
57 |
+
def _colorize(ds):
|
58 |
+
img = np.empty((ds.shape[0], ds.shape[1], 3), dtype=np.uint8)
|
59 |
+
|
60 |
+
hue_scale = np.random.uniform(0.15, 1) * 179
|
61 |
+
hue_shift = np.random.rand() * 179
|
62 |
+
|
63 |
+
sat_scale = np.random.uniform(0.1, 0.3) * 255
|
64 |
+
sat_shift = np.random.uniform(0.0, 0.3) * 255
|
65 |
+
|
66 |
+
val_scale = np.random.uniform(0.1, 0.3) * 255
|
67 |
+
val_shift = np.random.uniform(0.1, 0.3) * 255
|
68 |
+
|
69 |
+
for i in range(ds.shape[0]):
|
70 |
+
for j in range(ds.shape[1]):
|
71 |
+
x = ds[i, j]
|
72 |
+
img[i, j, 0] = np.uint8(min((x * hue_scale + hue_shift) % 179, 179))
|
73 |
+
img[i, j, 1] = np.uint8(min(x * sat_scale + sat_shift, 255))
|
74 |
+
img[i, j, 2] = np.uint8(min(x * val_scale + val_shift, 255))
|
75 |
+
|
76 |
+
return img
|
77 |
+
|
78 |
+
|
79 |
+
def colorized_ds(size=256):
|
80 |
+
# 画像サイズ256=2の8乗
|
81 |
+
n = int(np.ceil(np.log2(size)))
|
82 |
+
# 乱数生成器
|
83 |
+
rng = np.random.default_rng()
|
84 |
+
# 背景作成
|
85 |
+
r = diamond_square(n, rng.uniform(0.4, 0.8), fixed_corners=False)[:size, :size]
|
86 |
+
# HSVで色付け、HSV->RGB変換
|
87 |
+
img = _colorize(r)
|
88 |
+
img = cvtColor(img, COLOR_HSV2RGB, dst=img)
|
89 |
+
return img
|
src/multi_fractal_db/ifs.py
ADDED
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import partial
|
2 |
+
|
3 |
+
from cv2 import cvtColor, COLOR_HSV2RGB
|
4 |
+
import numba
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
|
8 |
+
# IFSフラクタル座標計算
|
9 |
+
@numba.njit(cache=True)
|
10 |
+
def iterate(sys, n_iter, ps=None):
|
11 |
+
'''Compute points in the fractal defined by the system `sys` by random iteration. `n_iter` iterations
|
12 |
+
are performed, and a transform is sampled at each iteration according to the probabilites defined by
|
13 |
+
`ps`.
|
14 |
+
|
15 |
+
Args:
|
16 |
+
sys (np.ndarray): array of shape (n, 2, 3), containing the affine transform parameters.
|
17 |
+
n_iter (int): number of iterations/points to calculate.
|
18 |
+
ps (Optional[array-like]): length-n array of probabilites. If None (default), the probabilites are
|
19 |
+
calculated to be proportional to the determinants of the affine transformation matrices.
|
20 |
+
|
21 |
+
Returns:
|
22 |
+
ndarray of shape (n_iter, 2) containing the (x, y) coordinates of the generated points.
|
23 |
+
'''
|
24 |
+
det = sys[:, 0, 0] * sys[:, 1, 1] - sys[:, 0, 1] * sys[:, 1, 0]
|
25 |
+
# 確率が指定されていない場合、detから計算
|
26 |
+
if ps is None:
|
27 |
+
# パラメータセット毎の確率
|
28 |
+
ps = np.abs(det)
|
29 |
+
# 全体で1になるように正規化
|
30 |
+
ps = ps / ps.sum()
|
31 |
+
# 累積確率、0-1の乱数でどのパラメータセットを使うか決めるため
|
32 |
+
ps = np.cumsum(ps)
|
33 |
+
|
34 |
+
# 全フラクタル点の座標
|
35 |
+
coords = np.empty((n_iter, 2))
|
36 |
+
|
37 |
+
# starting point is $v = (I-A_1)^(-1) b$ since this point is gaurenteed to be in the set
|
38 |
+
# (assuming that A_1 is contractive) (A_1 = sys[0])
|
39 |
+
s = 1 / (1 + det[0] - sys[0, 0, 0] - sys[0, 1, 1])
|
40 |
+
x = s * ((1 - sys[0, 1, 1]) * sys[0, 0, 2] + sys[0, 0, 1] * sys[0, 1, 2])
|
41 |
+
y = s * ((1 - sys[0, 0, 0]) * sys[0, 1, 2] + sys[0, 1, 0] * sys[0, 0, 2])
|
42 |
+
|
43 |
+
for i in range(n_iter):
|
44 |
+
# 0-1の一様乱数の生成
|
45 |
+
r = np.random.rand()
|
46 |
+
# 使用するパラメータセットの特定
|
47 |
+
for k in range(len(ps)):
|
48 |
+
if r < ps[k]: break
|
49 |
+
# パラメータセット
|
50 |
+
a, b, e, c, d, f = sys[k].ravel()
|
51 |
+
# 次座標の計算
|
52 |
+
xt = x
|
53 |
+
x = a * xt + b * y + e
|
54 |
+
y = c * xt + d * y + f
|
55 |
+
coords[i] = x, y
|
56 |
+
|
57 |
+
# 発散した場合はブレイク
|
58 |
+
if not np.isfinite(x) or not np.isfinite(y): break # if contractivity is satisfied, can remove this check
|
59 |
+
return coords
|
60 |
+
|
61 |
+
|
62 |
+
@numba.njit(cache=True)
|
63 |
+
def minmax(coords):
|
64 |
+
'''Returns both the minimum and maximum values along the 0 axis of an array with shape (n, 2). This only
|
65 |
+
requires a single pass through the array, and is faster than calling np.min and np.max seperately.
|
66 |
+
|
67 |
+
Args:
|
68 |
+
coords (np.ndarray): an array of shape (n, 2)
|
69 |
+
|
70 |
+
Returns:
|
71 |
+
Two ndarrays of shape (2,), the first containing the minimum values and the second containing the maximums
|
72 |
+
'''
|
73 |
+
# x,y座標の最大、最小値
|
74 |
+
mins = np.full(2, np.inf)
|
75 |
+
maxs = np.full(2, -np.inf)
|
76 |
+
for i in range(len(coords)):
|
77 |
+
x, y = coords[i]
|
78 |
+
if x < mins[0]: mins[0] = x
|
79 |
+
if y < mins[1]: mins[1] = y
|
80 |
+
if x > maxs[0]: maxs[0] = x
|
81 |
+
if y > maxs[1]: maxs[1] = y
|
82 |
+
return mins, maxs
|
83 |
+
|
84 |
+
|
85 |
+
@numba.njit(cache=True)
|
86 |
+
def _extent(region):
|
87 |
+
x1, y1, x2, y2 = region
|
88 |
+
xspan = x2 - x1
|
89 |
+
xspan = xspan if xspan > 0 else 1
|
90 |
+
yspan = y2 - y1
|
91 |
+
yspan = yspan if yspan > 0 else 1
|
92 |
+
return xspan, yspan
|
93 |
+
|
94 |
+
|
95 |
+
|
96 |
+
@numba.njit(cache=True)
|
97 |
+
def _render_binary(coords, s, region):
|
98 |
+
'''Renders a square, binary image from coordinate points and a given region.
|
99 |
+
|
100 |
+
Args:
|
101 |
+
coords (np.ndarray): coordinate array of shape (n, 2).
|
102 |
+
s (int): side length of the rendered image. The image will have width = height = s.
|
103 |
+
region (np.ndarray): array of shape (4,), containing [minx, miny, maxx, maxy]. These four values
|
104 |
+
define the region in coordinate space that will be rendered to the image. Coordinate points
|
105 |
+
that fall outside the bounds of the region will be ignored.
|
106 |
+
|
107 |
+
Returns:
|
108 |
+
A binary image as an ndarray of shape (s, s).
|
109 |
+
'''
|
110 |
+
imgb = np.zeros((s, s), dtype=np.uint8)
|
111 |
+
xspan, yspan = _extent(region)
|
112 |
+
xscale = (s-1) / xspan
|
113 |
+
yscale = (s-1) / yspan
|
114 |
+
xmin, ymin = region[0], region[1]
|
115 |
+
for i in range(len(coords)):
|
116 |
+
r = int((coords[i,0] - xmin) * xscale)
|
117 |
+
c = int((coords[i,1] - ymin) * yscale)
|
118 |
+
if r >= 0 and r < s and c >= 0 and c < s:
|
119 |
+
imgb[r, c] = 1
|
120 |
+
return imgb
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
@numba.njit(cache=True)
|
125 |
+
def _render_binary_patch(coords, s, region, patch):
|
126 |
+
'''Renders a square, binary image from coordinate points and a given region. Instead of rendering a
|
127 |
+
single point for each coordinate, a 3x3 patch is rendered, centered on the coordinate.
|
128 |
+
|
129 |
+
Args:
|
130 |
+
coords (np.ndarray): coordinate array of shape (n, 2).
|
131 |
+
s (int): side length of the rendered image. The image will have width = height = s.
|
132 |
+
region (np.ndarray): array of shape (4,), containing [minx, miny, maxx, maxy]. These four values
|
133 |
+
define the region in coordinate space that will be rendered to the image. Coordinate points
|
134 |
+
that fall outside the bounds of the region will be ignored.
|
135 |
+
patch (np.ndarray): array of shape (3, 3), where each value is either 0 or 1 (binary).
|
136 |
+
|
137 |
+
Returns:
|
138 |
+
A grayscale image as an ndarray of shape (s, s).
|
139 |
+
'''
|
140 |
+
# ブランク画像作成
|
141 |
+
imgb = np.zeros((s, s), dtype=np.uint8)
|
142 |
+
# x幅、y幅
|
143 |
+
xspan, yspan = _extent(region)
|
144 |
+
# xy軸方向の拡大係数
|
145 |
+
xscale = (s-1) / xspan
|
146 |
+
yscale = (s-1) / yspan
|
147 |
+
# xy軸最小値
|
148 |
+
xmin, ymin = region[0], region[1]
|
149 |
+
for i in range(len(coords)):
|
150 |
+
# ピクセル座標の計算
|
151 |
+
rr = int((coords[i,0] - xmin) * xscale)
|
152 |
+
cc = int((coords[i,1] - ymin) * yscale)
|
153 |
+
# patch処理
|
154 |
+
for j in range(len(patch)):
|
155 |
+
# マスクが1ならそのまま、0or2なら左右に書き込みでそのピクセルはブランク
|
156 |
+
r = rr + patch[j, 0] - 1
|
157 |
+
c = cc + patch[j, 1] - 1
|
158 |
+
if r >= 0 and r < s and c >= 0 and c < s:
|
159 |
+
imgb[r, c] = 1
|
160 |
+
return imgb
|
161 |
+
|
162 |
+
|
163 |
+
@numba.njit(cache=True)
|
164 |
+
def _render_graded(coords, s, region):
|
165 |
+
'''Renders a square, grayscale image from coordinate points and a given region. The grayscale values for
|
166 |
+
a given pixel is proportional to the number of coordinate points that land on that pixel.
|
167 |
+
|
168 |
+
See _render_binary for an explanation of the arguments.
|
169 |
+
'''
|
170 |
+
# ブランク画像、0-1の小数点になるので、floatで
|
171 |
+
imgf = np.zeros((s, s), dtype=np.float64)
|
172 |
+
# x,yの幅
|
173 |
+
xspan, yspan = _extent(region)
|
174 |
+
# ピクセル位置スケーリング
|
175 |
+
xscale = (s-1) / xspan
|
176 |
+
yscale = (s-1) / yspan
|
177 |
+
xmin, ymin = region[0], region[1]
|
178 |
+
for i in range(len(coords)):
|
179 |
+
# ピクセル座標計算
|
180 |
+
r = int((coords[i,0] - xmin) * xscale)
|
181 |
+
c = int((coords[i,1] - ymin) * yscale)
|
182 |
+
if r >= 0 and r < s and c >= 0 and c < s:
|
183 |
+
# 明暗つけるため加算する
|
184 |
+
imgf[r, c] += 1
|
185 |
+
# 正規化
|
186 |
+
mval = imgf.max()
|
187 |
+
if mval > 0:
|
188 |
+
imgf /= mval
|
189 |
+
return imgf
|
190 |
+
|
191 |
+
|
192 |
+
@numba.njit(cache=True)
|
193 |
+
def _render_graded_patch(coords, s, region, patch):
|
194 |
+
'''Renders a square, grayscale image from coordinate points and a given region. The grayscale values for
|
195 |
+
a given pixel is proportional to the number of coordinate points that land on that pixel. Instead of rendering
|
196 |
+
a single point for each coordinate, a 3x3 patch is rendered, centered on the coordinate.
|
197 |
+
|
198 |
+
See _render_binary_patch for an explanation of the arguments.
|
199 |
+
'''
|
200 |
+
imgf = np.zeros((s, s), dtype=np.float64)
|
201 |
+
xspan, yspan = _extent(region)
|
202 |
+
xscale = (s-1) / xspan
|
203 |
+
yscale = (s-1) / yspan
|
204 |
+
xmin, ymin = region[0], region[1]
|
205 |
+
for i in range(len(coords)):
|
206 |
+
rr = int((coords[i,0] - xmin) * xscale)
|
207 |
+
cc = int((coords[i,1] - ymin) * yscale)
|
208 |
+
for j in range(len(patch)):
|
209 |
+
r = rr + patch[j, 0] - 1
|
210 |
+
c = cc + patch[j, 1] - 1
|
211 |
+
if r >= 0 and r < s and c >= 0 and c < s:
|
212 |
+
imgf[r, c] += 1
|
213 |
+
mval = imgf.max()
|
214 |
+
if mval > 0:
|
215 |
+
imgf /= mval
|
216 |
+
return imgf
|
217 |
+
|
218 |
+
|
219 |
+
# フラクタル描画
|
220 |
+
def render(coords, s=256, binary=True, region=None, patch=False):
|
221 |
+
'''Render an image from a set of coordinates and an optionally specified region.
|
222 |
+
|
223 |
+
Args:
|
224 |
+
coords (np.ndarray): coordinate array of shape (n, 2).
|
225 |
+
s (int): side length of the rendered image. The image will have width = height = s.
|
226 |
+
binary (bool): if True, render a binary image; otherwise, render a grayscale image, where the grayscale
|
227 |
+
value is proportional to the number of coordinates that map to the pixel.
|
228 |
+
region (Optional[np.ndarray]): array of shape (4,), containing [minx, miny, maxx, maxy]. These four
|
229 |
+
values define the region in coordinate space that will be rendered to the image. Coordinate points
|
230 |
+
that fall outside the bounds of the region will be ignored. If None (default), the minimum and
|
231 |
+
maximum coordinate values are used.
|
232 |
+
patch (bool): if False, render each coordinate as a single point. If True, renders a 3x3 patch centered
|
233 |
+
at each coordinate. The patch is randomly sampled (each value is chosen uniformly from [0, 1]).
|
234 |
+
|
235 |
+
Returns:
|
236 |
+
An image (either grayscale or binary, depending) as an ndarray of shape (s, s).
|
237 |
+
'''
|
238 |
+
|
239 |
+
# 範囲指定がない場合
|
240 |
+
if region is None:
|
241 |
+
# フラクタル点座標の最大、最小範囲で切り出し
|
242 |
+
region = np.concatenate(minmax(coords))
|
243 |
+
else:
|
244 |
+
region = np.asarray(region)
|
245 |
+
|
246 |
+
# パッチ処理有りの場��
|
247 |
+
if patch:
|
248 |
+
# 3x3のマスク、だがどうも2もあるような
|
249 |
+
p = np.stack(np.divmod(np.arange(9)[np.random.randint(0, 2, (9,), dtype=bool)], 3), 1)
|
250 |
+
|
251 |
+
if binary:
|
252 |
+
if patch:
|
253 |
+
# patch処理ありの白黒画像
|
254 |
+
return _render_binary_patch(coords, s, region, p)
|
255 |
+
else:
|
256 |
+
# patch処理なし白黒画像
|
257 |
+
return _render_binary(coords, s, region)
|
258 |
+
else:
|
259 |
+
# カラー指定の場合、とりあえず輝度値のみ計算
|
260 |
+
if patch:
|
261 |
+
# patc処理ありカラー画像
|
262 |
+
return _render_graded_patch(coords, s, region, p)
|
263 |
+
else:
|
264 |
+
# patc処理なしカラー画像
|
265 |
+
return _render_graded(coords, s, region)
|
266 |
+
|
267 |
+
|
268 |
+
# HSV空間で色付け関数
|
269 |
+
@numba.njit(cache=True)
|
270 |
+
def _hsv_colorize(rendered, min_sat=0.3, min_val=0.5):
|
271 |
+
'''Creates a 3-channel HSV image from a 1-channel gray image.
|
272 |
+
'''
|
273 |
+
h, w = rendered.shape[:2]
|
274 |
+
img = np.empty((h, w, 3), dtype=np.uint8)
|
275 |
+
|
276 |
+
# 基準Hue
|
277 |
+
hue_shift = np.random.rand() * 179
|
278 |
+
# 彩度
|
279 |
+
sat = np.uint8(np.random.uniform(min_sat, 1) * 255)
|
280 |
+
# 明度
|
281 |
+
val = np.uint8(np.random.uniform(min_val, 1) * 255)
|
282 |
+
|
283 |
+
for i in range(h):
|
284 |
+
for j in range(w):
|
285 |
+
x = rendered[i, j]
|
286 |
+
if x > 0:
|
287 |
+
img[i, j, 0] = np.uint8(min((x * 179 + hue_shift) % 179, 179)) # implicit MOD(256)
|
288 |
+
img[i, j, 1] = sat
|
289 |
+
img[i, j, 2] = val
|
290 |
+
else:
|
291 |
+
img[i, j, 0] = 0
|
292 |
+
img[i, j, 1] = 0
|
293 |
+
img[i, j, 2] = 0
|
294 |
+
return img
|
295 |
+
|
296 |
+
|
297 |
+
@numba.njit(cache=True)
|
298 |
+
def _hsv_colorize2(rendered, min_sat=0.3, min_val=0.5, hue_base=0, hue_range=179, max_sat=1.0):
|
299 |
+
h, w = rendered.shape[:2]
|
300 |
+
img = np.empty((h, w, 3), dtype=np.uint8)
|
301 |
+
|
302 |
+
# 基準Hue
|
303 |
+
hue_shift = np.random.rand() * hue_range + hue_base
|
304 |
+
hue_scale = np.random.uniform(-0.5, 0.5) * hue_range
|
305 |
+
# 彩度
|
306 |
+
sat = np.uint8(np.random.uniform(min_sat, max_sat) * 255)
|
307 |
+
# 明度
|
308 |
+
val = np.uint8(np.random.uniform(min_val, 1) * 255)
|
309 |
+
|
310 |
+
for i in range(h):
|
311 |
+
for j in range(w):
|
312 |
+
x = rendered[i, j]
|
313 |
+
if x > 0:
|
314 |
+
img[i, j, 0] = np.uint8(min((x * hue_scale + hue_shift) % 179, 179)) # implicit MOD(256)
|
315 |
+
img[i, j, 1] = sat
|
316 |
+
img[i, j, 2] = min(max(x * 1024, val), 255)
|
317 |
+
else:
|
318 |
+
img[i, j, 0] = 0
|
319 |
+
img[i, j, 1] = 0
|
320 |
+
img[i, j, 2] = 0
|
321 |
+
return img
|
322 |
+
|
323 |
+
|
324 |
+
# 前景画像埋め込み
|
325 |
+
@numba.njit(cache=True)
|
326 |
+
def composite(fg, bg):
|
327 |
+
'''Copy nonzero pixels from fg into bg. Modifies bg in-place.'''
|
328 |
+
for i in range(fg.shape[0]):
|
329 |
+
for j in range(fg.shape[1]):
|
330 |
+
if fg[i, j, 0] != 0 or fg[i, j, 1] != 0 or fg[i, j, 2] != 0:
|
331 |
+
bg[i, j] = fg[i, j]
|
332 |
+
return bg
|
333 |
+
|
334 |
+
# 前景画像埋め込み
|
335 |
+
@numba.njit(cache=True)
|
336 |
+
def composite_v2(fg, bg, fg_mask):
|
337 |
+
'''Copy nonzero pixels from fg into bg. Modifies bg in-place.'''
|
338 |
+
for i in range(fg.shape[0]):
|
339 |
+
for j in range(fg.shape[1]):
|
340 |
+
if fg[i, j, 0] != 0 or fg[i, j, 1] != 0 or fg[i, j, 2] != 0:
|
341 |
+
factor = np.power(fg_mask[i, j], 0.3)
|
342 |
+
for k in range(3):
|
343 |
+
bg[i, j, k] = np.uint8(min(fg[i, j, k] * factor +
|
344 |
+
bg[i, j, k] * (1.0 - factor), 255))
|
345 |
+
# bg[i, j, k] = np.uint8(fg_mask[i, j] * 255)
|
346 |
+
# bg[i, j] = (fg[i, j] * fg_mask[i, j] + bg[i, j] * (255 - fg_mask[i, j])) / 255
|
347 |
+
return bg
|
348 |
+
|
349 |
+
|
350 |
+
# カラー画像化
|
351 |
+
def colorize(rendered, min_sat=0.3, min_val=0.5, hue_base=0, hue_range=179, max_sat=1.0):
|
352 |
+
'''Turns a grayscale image into a color image, where the colors are randomly chosen as explained below.
|
353 |
+
|
354 |
+
First, the grayscale values are converted to the range [0, 255]. A reference hue value h is chosen
|
355 |
+
uniformly from [0, 255], and the hue for each pixel p becomes (p + h) mod 256. Then global saturation
|
356 |
+
and value scales are chosen uniformly from the ranges [min_sat, 1] and [min_val, 1]. Finally, the image
|
357 |
+
is converted to RGB.
|
358 |
+
|
359 |
+
Args:
|
360 |
+
rendered (np.ndarray): grayscale image of shape (w, h), with values in the range [0, 1].
|
361 |
+
min_sat (float): minimum "saturation" value, defining the range of possible saturation values to draw from.
|
362 |
+
min_val (float): minimum "value" value, defining the range of possible "value" (as in light/dark) values to
|
363 |
+
draw from.
|
364 |
+
|
365 |
+
Returns:
|
366 |
+
A color image as an ndarray of shape (w, h, 3).
|
367 |
+
'''
|
368 |
+
# HSV空間で色付け
|
369 |
+
# img = _hsv_colorize(rendered, min_sat, min_val)
|
370 |
+
img = _hsv_colorize2(rendered, min_sat, min_val, hue_base, hue_range, max_sat)
|
371 |
+
# HSV->RGB変換
|
372 |
+
cvtColor(img, COLOR_HSV2RGB, dst=img)
|
373 |
+
return img
|
src/multi_fractal_db/multi_fractal_dataset.py
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import partial
|
2 |
+
import pickle
|
3 |
+
from typing import Callable, Optional, Tuple, Union
|
4 |
+
import warnings
|
5 |
+
|
6 |
+
from cv2 import GaussianBlur
|
7 |
+
import numpy as np
|
8 |
+
import torch
|
9 |
+
import torchvision
|
10 |
+
|
11 |
+
from multi_fractal_db import diamondsquare, ifs
|
12 |
+
from multi_fractal_db.multi_fractal_generator import MultiGenerator
|
13 |
+
|
14 |
+
|
15 |
+
class MultiFractalDataset(object):
|
16 |
+
def __init__(
|
17 |
+
self,
|
18 |
+
ifs_params: object,
|
19 |
+
num_systems: int = 100,
|
20 |
+
num_class: int = 100,
|
21 |
+
per_class: int = 100,
|
22 |
+
generator: Optional[MultiGenerator] = None,
|
23 |
+
period: int = 2,
|
24 |
+
):
|
25 |
+
# IFSシステム数
|
26 |
+
self.num_systems = num_systems
|
27 |
+
# クラス数
|
28 |
+
self.num_class = num_class
|
29 |
+
# クラスあたりの画像枚数
|
30 |
+
self.per_class = per_class
|
31 |
+
# クラスあたりのIFSシステム数
|
32 |
+
self.per_system = num_class * per_class / num_systems
|
33 |
+
# IFSシステムパラメータ
|
34 |
+
self.params = ifs_params['params'][:num_systems]
|
35 |
+
|
36 |
+
# なぜかここMultiGeneratorが生成されてしまうのでコメントアウト
|
37 |
+
self.generator : MultiGenerator = generator #or MultiGenerator()
|
38 |
+
|
39 |
+
# キャッシュ画像をすべて作成
|
40 |
+
while len(self.generator.cache['fg']) < self.generator.cache_size:
|
41 |
+
for isys in range(num_systems):
|
42 |
+
# 代表クラス番号
|
43 |
+
# k = np.random.default_rng().integers(0, num_class)
|
44 |
+
self.generator.add_sample(self.params[isys]['system'], label=isys) # change to instance label
|
45 |
+
|
46 |
+
self.steps = 0
|
47 |
+
self.period = period
|
48 |
+
|
49 |
+
def __len__(self):
|
50 |
+
return self.num_class * self.per_class
|
51 |
+
|
52 |
+
def get_label(self, idx):
|
53 |
+
return int(idx // self.num_class)
|
54 |
+
|
55 |
+
def get_system(self, idx):
|
56 |
+
return int(idx // self.per_system)
|
57 |
+
|
58 |
+
def __getitem__(self, idx):
|
59 |
+
# whether it's time to render a new fractal or not
|
60 |
+
self.steps = (self.steps + 1) % self.period
|
61 |
+
sample = self.steps == 0
|
62 |
+
# IFSシステム番号
|
63 |
+
sysidx = self.get_system(idx)
|
64 |
+
# ラベル取得
|
65 |
+
label = self.get_label(idx)
|
66 |
+
# IFSパラメータ取得
|
67 |
+
params = self.params[sysidx]['system']
|
68 |
+
# 混合画像と混合ラベル
|
69 |
+
img, labels = self.generator(params, label=label, new_sample=sample)
|
70 |
+
#img = torch.from_numpy(img).float().mul_(1/255.).permute(2,0,1)
|
71 |
+
|
72 |
+
return img, labels
|
src/multi_fractal_db/multi_fractal_generator.py
ADDED
@@ -0,0 +1,492 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from functools import partial
|
2 |
+
from typing import Callable, Optional, Tuple, Union
|
3 |
+
|
4 |
+
from cv2 import GaussianBlur, resize, INTER_LINEAR, INTER_CUBIC, getRotationMatrix2D, warpAffine
|
5 |
+
import numpy as np
|
6 |
+
|
7 |
+
from multi_fractal_db import diamondsquare, ifs
|
8 |
+
|
9 |
+
|
10 |
+
class _GeneratorBase(object):
|
11 |
+
def __init__(
|
12 |
+
self,
|
13 |
+
# 画像サイズ
|
14 |
+
size: int = 224,
|
15 |
+
# jit方法、Trueもしくは文字列を受け入れる
|
16 |
+
jitter_params: Union[bool, str] = True,
|
17 |
+
flips: bool = True,
|
18 |
+
# ボケの標準偏差
|
19 |
+
sigma: Optional[Tuple[float, float]] = (0.5, 1.0),
|
20 |
+
blur_p: Optional[float] = 0.5,
|
21 |
+
# フラクタル座標点数
|
22 |
+
niter = 100000,
|
23 |
+
# patch処理有無
|
24 |
+
patch = True,
|
25 |
+
):
|
26 |
+
self.size = size
|
27 |
+
self.jitter_params = jitter_params
|
28 |
+
self.flips = flips
|
29 |
+
self.sigma = sigma
|
30 |
+
self.blur_p = blur_p
|
31 |
+
self.niter = niter
|
32 |
+
self.patch = patch
|
33 |
+
|
34 |
+
self.jitter_success = 0
|
35 |
+
self.jitter_failed = 0
|
36 |
+
|
37 |
+
self.hue_base = np.random.default_rng().integers(0, 179)
|
38 |
+
self.min_sat = np.random.default_rng().uniform(0.0, 0.75)
|
39 |
+
self.hue_range = max(0, 179 * (0.7 - self.min_sat))
|
40 |
+
|
41 |
+
self.rng = np.random.default_rng()
|
42 |
+
self.cache = {'fg': [], 'bg': []}
|
43 |
+
# jit関数定義
|
44 |
+
self._set_jitter()
|
45 |
+
|
46 |
+
# jit関数
|
47 |
+
def _set_jitter(self):
|
48 |
+
# jit指定が文字列の場合
|
49 |
+
if isinstance(self.jitter_params, str):
|
50 |
+
if self.jitter_params.startswith('fractaldb'):
|
51 |
+
k = int(self.jitter_params.split('-')[1]) / 10
|
52 |
+
choices = np.linspace(1-2*k, 1+2*k, 5, endpoint=True)
|
53 |
+
self.jitter_fnc = partial(self._fractaldb_jitter, choices=choices)
|
54 |
+
if self.jitter_params.startswith('svd'):
|
55 |
+
self.jitter_fnc = self._svd_jitter
|
56 |
+
if self.jitter_params.startswith('sval'):
|
57 |
+
self.jitter_fnc = self._sval_jitter
|
58 |
+
elif self.jitter_params:
|
59 |
+
# defualt
|
60 |
+
self.jitter_fnc = self._basic_jitter
|
61 |
+
else:
|
62 |
+
# そのまま返す
|
63 |
+
self.jitter_fnc = lambda x: x
|
64 |
+
|
65 |
+
def _fractaldb_jitter(self, sys, prange=(0.5, 2.0), choices=[]):
|
66 |
+
n = len(sys)
|
67 |
+
y, x = np.divmod(self.rng.integers(0, 6, (n,)), 3)
|
68 |
+
scaling_factors = self.rng.uniform(*prange, n)
|
69 |
+
sys[range(n), y, x] *= scaling_factors
|
70 |
+
return sys
|
71 |
+
|
72 |
+
# def _fractaldb_jitter(self, sys, choices=(.8,.9,1,1.1,1.2)):
|
73 |
+
# n = len(sys)
|
74 |
+
# y, x = np.divmod(self.rng.integers(0, 6, (n,)), 3)
|
75 |
+
# sys[range(n), y, x] *= self.rng.choice(choices)
|
76 |
+
# return sys
|
77 |
+
|
78 |
+
|
79 |
+
# デフォルトのJitter関数
|
80 |
+
def _basic_jitter(self, sys, prange=(0.8, 1.1)):
|
81 |
+
# tweak system parameters--randomly choose one transform and scale it
|
82 |
+
# this actually amounts to scaling the singular values by a random factor
|
83 |
+
# IFSパラメータの全要素数
|
84 |
+
n = len(sys)
|
85 |
+
# どれか1要素を係数かけて微笑変動させる
|
86 |
+
sys[self.rng.integers(0, n)] *= self.rng.uniform(*prange)
|
87 |
+
return sys
|
88 |
+
|
89 |
+
|
90 |
+
def _svd_jitter(self, sys):
|
91 |
+
'''Jitter the parameters of one of the systems functions, in SVD space.'''
|
92 |
+
k = self.rng.integers(0, len(sys) * 3)
|
93 |
+
sidx, pidx = divmod(k, 3)
|
94 |
+
if pidx < 2:
|
95 |
+
q = self.rng.uniform(-0.5, 0.5)
|
96 |
+
u, s, v = np.linalg.svd(sys[sidx, :, :2])
|
97 |
+
cq, sq = np.cos(q), np.sin(q)
|
98 |
+
r = np.array([[cq, -sq], [sq, cq]])
|
99 |
+
if pidx == 0:
|
100 |
+
u = r @ u
|
101 |
+
else:
|
102 |
+
v = r @ v
|
103 |
+
sys[sidx, :, :2] = (u * s[None,:]) @ v
|
104 |
+
else:
|
105 |
+
x, y = self.rng.uniform(-0.5, 0.5, (2,))
|
106 |
+
sys[sidx, :, 2] += [x, y]
|
107 |
+
return sys
|
108 |
+
|
109 |
+
|
110 |
+
def _sval_jitter(self, sys):
|
111 |
+
k = self.rng.integers(0, sys.shape[0])
|
112 |
+
svs = np.linalg.svd(sys[...,:2], compute_uv=False)
|
113 |
+
fac = (svs * [1, 2]).sum()
|
114 |
+
minf = 0.5 * (5 + sys.shape[0])
|
115 |
+
maxf = minf + 0.5
|
116 |
+
ss = svs[k, 0] + 2 * svs[k, 1]
|
117 |
+
smin = (minf - fac + ss) / ss
|
118 |
+
smax = (maxf - fac + ss) / ss
|
119 |
+
m = self.rng.uniform(smin, smax)
|
120 |
+
u, s, v = np.linalg.svd(sys[k, :, :2])
|
121 |
+
s = s * m
|
122 |
+
sys[k, :, :2] = (u * s[None]) @ v
|
123 |
+
return sys
|
124 |
+
|
125 |
+
|
126 |
+
# IFSパラメータ微小変動
|
127 |
+
def jitter(self, sys):
|
128 |
+
# 4回、微小変動を起こす
|
129 |
+
attempts = 4 if self.jitter_params else 0
|
130 |
+
for i in range(attempts):
|
131 |
+
# jitter system parameters
|
132 |
+
sysc = sys.copy()
|
133 |
+
sysc = self.jitter_fnc(sysc)
|
134 |
+
# 特異値分解、対角行列の特異値のみ計算
|
135 |
+
# occasionally the modified parameters cause the system to explode
|
136 |
+
svd = np.linalg.svd(sysc[:,:,:2], compute_uv=False)
|
137 |
+
# 1を超えている場合発散するので再度jitする
|
138 |
+
if svd.max() > 1: continue
|
139 |
+
|
140 |
+
self.jitter_success += 1
|
141 |
+
break
|
142 |
+
else:
|
143 |
+
# fall back on not jittering the parameters
|
144 |
+
self.jitter_failed += 1
|
145 |
+
sysc = sys
|
146 |
+
return sysc
|
147 |
+
|
148 |
+
|
149 |
+
# IFSフラクタル座標と範囲の計算
|
150 |
+
def _iterate(self, sys):
|
151 |
+
rng = self.rng
|
152 |
+
|
153 |
+
# 全フラクタル点の座標を計算
|
154 |
+
coords = ifs.iterate(sys, self.niter)
|
155 |
+
|
156 |
+
# フラクタル点の座標範囲、[xmin, ymin, xmax, ymax]
|
157 |
+
region = np.concatenate(ifs.minmax(coords))
|
158 |
+
|
159 |
+
return coords, region
|
160 |
+
|
161 |
+
|
162 |
+
def render(self, sys):
|
163 |
+
raise NotImplementedError()
|
164 |
+
|
165 |
+
|
166 |
+
# データ拡張(RandomFlip)
|
167 |
+
def random_flips(self, img):
|
168 |
+
# random flips/rotations
|
169 |
+
if self.rng.random() > 0.5:
|
170 |
+
# 縦横転置
|
171 |
+
img = img.transpose(1, 0)
|
172 |
+
if self.rng.random() > 0.5:
|
173 |
+
# 上下反転
|
174 |
+
img = img[::-1]
|
175 |
+
if self.rng.random() > 0.5:
|
176 |
+
# 左右反転
|
177 |
+
img = img[:, ::-1]
|
178 |
+
# 配列のメモリ連続性を確保するため
|
179 |
+
img = np.ascontiguousarray(img)
|
180 |
+
return img
|
181 |
+
|
182 |
+
|
183 |
+
# フラクタル画像のカラー化
|
184 |
+
def to_color(self, img):
|
185 |
+
# カラー画像化
|
186 |
+
return ifs.colorize(img, min_sat=self.min_sat, hue_base=self.hue_base, hue_range=self.hue_range)
|
187 |
+
|
188 |
+
|
189 |
+
# 白黒画像
|
190 |
+
def to_gray(self, img):
|
191 |
+
# バイナリ画像なので中間の127の灰色画像で、3チャンネルにしておく
|
192 |
+
return (img * 1024).clip(0, 255).astype(np.uint8)[..., None].repeat(3, axis=2)
|
193 |
+
|
194 |
+
|
195 |
+
# 背景画像を作成
|
196 |
+
def render_background(self):
|
197 |
+
# 幾何模様のカラー背景作成
|
198 |
+
bg = diamondsquare.colorized_ds(self.size)
|
199 |
+
# 背景を暗くする
|
200 |
+
#bg = bg * 0.5
|
201 |
+
return bg
|
202 |
+
|
203 |
+
|
204 |
+
# 背景に前景を埋め込み
|
205 |
+
def composite(self, foreground, base, idx=None):
|
206 |
+
return ifs.composite(foreground, base)
|
207 |
+
|
208 |
+
# 背景に前景を埋め込み
|
209 |
+
def composite_v2(self, foreground, base, mask, idx=None):
|
210 |
+
return ifs.composite_v2(foreground, base, mask)
|
211 |
+
|
212 |
+
# データ拡張(ボカし)
|
213 |
+
def random_blur(self, img):
|
214 |
+
# 標準偏差取得
|
215 |
+
sigma = self.rng.uniform(*self.sigma)
|
216 |
+
# 画像平坦化
|
217 |
+
img = GaussianBlur(img, (3, 3), sigma, dst=img)
|
218 |
+
return img
|
219 |
+
|
220 |
+
|
221 |
+
def generate(self, sys):
|
222 |
+
raise NotImplementedError()
|
223 |
+
|
224 |
+
|
225 |
+
def __call__(self, sys, *args, **kwargs):
|
226 |
+
return self.generate(sys, *args, **kwargs)
|
227 |
+
|
228 |
+
|
229 |
+
|
230 |
+
class MultiGenerator(_GeneratorBase):
|
231 |
+
def __init__(
|
232 |
+
self,
|
233 |
+
# 画像サイズ
|
234 |
+
size: int = 224,
|
235 |
+
# キャッシュサイズ
|
236 |
+
cache_size: int = 100,
|
237 |
+
# 混合数
|
238 |
+
n_objects: Tuple[int, int] = (1, 5),
|
239 |
+
# 埋め込み画像サイズ
|
240 |
+
size_range: Tuple[float, float] = (0.2, 0.6),
|
241 |
+
# jitパラメータ、デフォルトではなし
|
242 |
+
jitter_params: Union[bool, str] = False,
|
243 |
+
# データ拡張(縦横、左右、上下反転)フラグ
|
244 |
+
flips: bool = True,
|
245 |
+
# ボカしの標準偏差
|
246 |
+
sigma: Optional[Tuple[float, float]] = (0.5, 1.0),
|
247 |
+
# データ拡張(ボケ実施確率)
|
248 |
+
blur_p: Optional[float] = 0.5,
|
249 |
+
# カラー画像フラグ
|
250 |
+
color = True,
|
251 |
+
# 背景画像の付与の有無
|
252 |
+
background = True,
|
253 |
+
# フラクタル点数
|
254 |
+
niter = 100000,
|
255 |
+
# patch処理実施有無
|
256 |
+
patch = True,
|
257 |
+
# 混合画像の採用確率?
|
258 |
+
nobj_p = None,
|
259 |
+
|
260 |
+
seed = 0,
|
261 |
+
n_instance_types = 1,
|
262 |
+
):
|
263 |
+
self.size = size
|
264 |
+
self.n_objects = n_objects
|
265 |
+
self.size_range = size_range
|
266 |
+
self.jitter_params = jitter_params
|
267 |
+
self.flips = flips
|
268 |
+
self.sigma = sigma
|
269 |
+
self.blur_p = blur_p
|
270 |
+
self.color = color
|
271 |
+
self.background = background
|
272 |
+
self.niter = niter
|
273 |
+
self.patch = patch
|
274 |
+
|
275 |
+
self.bg_sel_cache_idx = 0
|
276 |
+
self.sel_cache_idx = 0
|
277 |
+
|
278 |
+
self.jitter_success = 0
|
279 |
+
self.jitter_failed = 0
|
280 |
+
|
281 |
+
np.random.seed(seed)
|
282 |
+
self.hue_bases = [np.random.uniform(0, 179) for _ in range(n_instance_types)]
|
283 |
+
self.min_sats = [np.random.uniform(0.0, 0.50) for _ in range(n_instance_types)]
|
284 |
+
self.max_sats = [min(1, self.min_sats[i] * 2 + 0.2) for i in range(n_instance_types)]
|
285 |
+
self.hue_ranges = [max(0, 179 * (0.8 - self.min_sats[i]) / 0.8) for i in range(n_instance_types)]
|
286 |
+
|
287 |
+
# 乱数生成器
|
288 |
+
self.rng = np.random.default_rng(seed=0)
|
289 |
+
|
290 |
+
|
291 |
+
|
292 |
+
# キャッシュサイズ
|
293 |
+
self.cache_size = cache_size
|
294 |
+
# 前景と背景のキャッシュ
|
295 |
+
self.cache = {'fg': [], 'bg': [], 'label': []}
|
296 |
+
self.idx = 0
|
297 |
+
|
298 |
+
# 混合確率
|
299 |
+
if nobj_p is None:
|
300 |
+
# 等確率
|
301 |
+
self.nobj_p = np.ones(n_objects[1] - n_objects[0] + 1)
|
302 |
+
else:
|
303 |
+
self.nobj_p = np.array(nobj_p, dtype=np.float64)
|
304 |
+
self.nobj_p /= self.nobj_p.sum()
|
305 |
+
|
306 |
+
# jit関数設定
|
307 |
+
self._set_jitter()
|
308 |
+
|
309 |
+
|
310 |
+
# フラクタル画像のカラー化
|
311 |
+
def to_color(self, img, instance_label):
|
312 |
+
# カラー画像化
|
313 |
+
return ifs.colorize(img,
|
314 |
+
min_sat=self.min_sats[instance_label],
|
315 |
+
hue_base=self.hue_bases[instance_label],
|
316 |
+
hue_range=self.hue_ranges[instance_label],
|
317 |
+
max_sat=self.max_sats[instance_label])
|
318 |
+
|
319 |
+
|
320 |
+
def __len__(self):
|
321 |
+
# 前景キャッシュ数を返す
|
322 |
+
return len(self.cache['fg'])
|
323 |
+
|
324 |
+
|
325 |
+
def _update_cache(self, fg, bg, label):
|
326 |
+
if len(self) < self.cache_size:
|
327 |
+
# キャッシュサイズ以下であれば追記
|
328 |
+
self.cache['fg'].append(fg)
|
329 |
+
self.cache['bg'].append(bg)
|
330 |
+
self.cache['label'].append(label)
|
331 |
+
else:
|
332 |
+
# idx番目に追加
|
333 |
+
self.cache['fg'][self.idx] = fg
|
334 |
+
self.cache['bg'][self.idx] = bg
|
335 |
+
self.cache['label'][self.idx] = label
|
336 |
+
# キャッシュ番号
|
337 |
+
self.idx = (self.idx + 1) % self.cache_size
|
338 |
+
|
339 |
+
|
340 |
+
# 前景のフラクタル画像作成
|
341 |
+
def render(self, sys):
|
342 |
+
# 乱数生成器コピー
|
343 |
+
rng = self.rng
|
344 |
+
# フラクタル座標と範囲
|
345 |
+
coords, region = self._iterate(sys)
|
346 |
+
# render the fractal at half resolution--it will be resized during generation phase
|
347 |
+
img = ifs.render(coords, self.size, binary=False, region=region, patch=self.patch)
|
348 |
+
return img
|
349 |
+
|
350 |
+
|
351 |
+
# キャッシュに前景と背景画像を追加
|
352 |
+
def add_sample(self, sys, label=-1):
|
353 |
+
# IFSパラメータの微少変動
|
354 |
+
sysc = self.jitter(sys)
|
355 |
+
# フラクタル画像生成
|
356 |
+
frac = self.render(sysc)
|
357 |
+
# 背景画像の生成
|
358 |
+
bg = self.render_background()
|
359 |
+
# MixUPとかできないのでラベルは使わない
|
360 |
+
# キャッシュに追加
|
361 |
+
self._update_cache(frac, bg, label)
|
362 |
+
|
363 |
+
|
364 |
+
# Multi-Fractal画像を作成
|
365 |
+
def generate(self, sys, label=-1, new_sample=True):
|
366 |
+
# 乱数生成器コピー
|
367 |
+
rng = self.rng
|
368 |
+
|
369 |
+
# 新規追加しない、
|
370 |
+
# インスタンス時に全キャッシュ作成済みでそこからとってくる
|
371 |
+
#if new_sample:
|
372 |
+
# self.add_sample(sys, label)
|
373 |
+
|
374 |
+
# 背景画像をキャッシュ内からランダムに選択
|
375 |
+
idx = self.bg_sel_cache_idx % len(self)#rng.integers(0, len(self))
|
376 |
+
self.bg_sel_cache_idx += 1
|
377 |
+
img = self.cache['bg'][idx].copy()
|
378 |
+
# 背景なしの場合はブランク画像
|
379 |
+
if self.background==False:
|
380 |
+
img = np.zeros(img.shape, np.uint8)
|
381 |
+
|
382 |
+
# ラベルは使わない
|
383 |
+
labels = []
|
384 |
+
|
385 |
+
# 混合数を乱数選択
|
386 |
+
n = rng.choice(range(self.n_objects[0], self.n_objects[1]+1), p=self.nobj_p)
|
387 |
+
# キャッシュサイズでキャップ
|
388 |
+
n = min(n, len(self))
|
389 |
+
|
390 |
+
# 混合数回分繰り返し
|
391 |
+
for i in range(n):
|
392 |
+
# キャッシュ番号選択
|
393 |
+
idx = self.sel_cache_idx % len(self) # rng.integers(0, len(self))#
|
394 |
+
self.sel_cache_idx += 1
|
395 |
+
|
396 |
+
# ラベルリストに追加
|
397 |
+
labels.append(self.cache['label'][idx])
|
398 |
+
|
399 |
+
# 前景画像取得
|
400 |
+
fg = self.cache['fg'][idx]
|
401 |
+
label = self.cache['label'][idx]
|
402 |
+
|
403 |
+
if True:
|
404 |
+
# データ拡張(転置、水平、上下反転)
|
405 |
+
# random flips
|
406 |
+
if self.flips:
|
407 |
+
fg = self.random_flips(fg)
|
408 |
+
|
409 |
+
# colorize
|
410 |
+
if self.color:
|
411 |
+
# カラー画像化
|
412 |
+
fg = self.to_color(fg, label)
|
413 |
+
else:
|
414 |
+
# 白黒画像化
|
415 |
+
fg = self.to_gray(fg)
|
416 |
+
|
417 |
+
# 0.2-0.6倍でリサイズ
|
418 |
+
# リサイズ倍率
|
419 |
+
f = rng.uniform(*self.size_range)
|
420 |
+
# リサイズ
|
421 |
+
s = int(f * self.size)
|
422 |
+
fg = resize(fg, (s, s), interpolation=INTER_CUBIC)
|
423 |
+
|
424 |
+
# データ拡張(回転)
|
425 |
+
if self.blur_p and rng.random() > self.blur_p:
|
426 |
+
# 回転角度
|
427 |
+
angle = rng.integers(-45, 45, 1)[0]
|
428 |
+
# 回転中心
|
429 |
+
height, width, channel = fg.shape
|
430 |
+
center = (int(width/2), int(height/2))
|
431 |
+
# 等倍
|
432 |
+
scale = 1.0
|
433 |
+
#getRotationMatrix2D関数を使用
|
434 |
+
trans = getRotationMatrix2D(center, angle , scale)
|
435 |
+
#アフィン変換
|
436 |
+
fg = warpAffine(fg, trans, (width,height))
|
437 |
+
|
438 |
+
# ランダム埋め込み位置
|
439 |
+
# random location
|
440 |
+
x, y = rng.integers(-(s//3), self.size-s+(s//3), 2)
|
441 |
+
x1 = 0 if x >= 0 else -x
|
442 |
+
x2 = s if x < self.size - s else self.size - x
|
443 |
+
y1 = 0 if y >= 0 else -y
|
444 |
+
y2 = s if y < self.size - s else self.size - y
|
445 |
+
fg = fg[y1:y2, x1:x2]
|
446 |
+
# add object to image
|
447 |
+
y = max(y, 0)
|
448 |
+
x = max(x, 0)
|
449 |
+
self.composite(fg, img[y:y+fg.shape[0], x:x+fg.shape[1]])
|
450 |
+
else:
|
451 |
+
fg_gray = fg.copy()
|
452 |
+
fg = self.to_color(fg)
|
453 |
+
f = 0.8#rng.uniform(*self.size_range)
|
454 |
+
# リサイズ
|
455 |
+
s = int(f * self.size)
|
456 |
+
fg = resize(fg, (s, s), interpolation=INTER_CUBIC)
|
457 |
+
fg_gray = resize(fg_gray, (s, s), interpolation=INTER_CUBIC)
|
458 |
+
|
459 |
+
x, y = 0, 0
|
460 |
+
x1 = 0 if x >= 0 else -x
|
461 |
+
x2 = s if x < self.size - s else self.size - x
|
462 |
+
y1 = 0 if y >= 0 else -y
|
463 |
+
y2 = s if y < self.size - s else self.size - y
|
464 |
+
fg = fg[y1:y2, x1:x2]
|
465 |
+
fg_gray = fg_gray[y1:y2, x1:x2]
|
466 |
+
y = max(y, 0)
|
467 |
+
x = max(x, 0)
|
468 |
+
self.composite(fg, img[y:y+fg.shape[0], x:x+fg.shape[1]])
|
469 |
+
# self.composite_v2(fg, img[y:y+fg.shape[0], x:x+fg.shape[1]], fg_gray)
|
470 |
+
|
471 |
+
|
472 |
+
#x, y = rng.integers(-(s//2), self.size-(s//2), 2)
|
473 |
+
# # 見切れ防止
|
474 |
+
# x, y = rng.integers(0, self.size-s, 2)
|
475 |
+
# # 見切れ範囲除外
|
476 |
+
# x1 = 0 if x >= 0 else -x
|
477 |
+
# x2 = s if x < self.size - s else self.size - x
|
478 |
+
# y1 = 0 if y >= 0 else -y
|
479 |
+
# y2 = s if y < self.size - s else self.size - y
|
480 |
+
# fg = fg[y1:y2, x1:x2]
|
481 |
+
# # add object to image
|
482 |
+
# y = max(y, 0)
|
483 |
+
# x = max(x, 0)
|
484 |
+
# # 埋め込み範囲のみ重畳描画する、背景画像に重畳していく
|
485 |
+
# self.composite(fg, img[y:y+fg.shape[0], x:x+fg.shape[1]])
|
486 |
+
|
487 |
+
# ボカし実施
|
488 |
+
# randomly apply gaussian blur
|
489 |
+
# if self.blur_p and rng.random() > self.blur_p:
|
490 |
+
# img = self.random_blur(img)
|
491 |
+
|
492 |
+
return img, labels
|
src/multi_fractal_db/serach_ifs_systems.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import tqdm
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
# IFSシステムのパラメータ探索
|
5 |
+
def random_systems(num_systems, n=(2,5), bval=None, beta=None, sample_fn=None):
|
6 |
+
'''Sample random systems.
|
7 |
+
|
8 |
+
Args:
|
9 |
+
num_systems (int): the number of systems to sample.
|
10 |
+
n (int or Tuple[int, int]): the size or range of sizes allowable for the systems.
|
11 |
+
bval (float): allowable magnitude of translation parameters.
|
12 |
+
beta (float or Tuple[float,float]): singular values constraint. See sample_systems.
|
13 |
+
|
14 |
+
Returns:
|
15 |
+
A list of dicts {'system': np.array} containing the system parameters.
|
16 |
+
'''
|
17 |
+
# 乱数生成器
|
18 |
+
rng = np.random.default_rng(seed=0)
|
19 |
+
systems = []
|
20 |
+
for i in tqdm.trange(num_systems):
|
21 |
+
# IFSシステムパラメータ取得
|
22 |
+
s = sample_system(n, bval=bval, beta=beta, rng=rng, sample_fn=sample_fn)
|
23 |
+
systems.append({'system': s})
|
24 |
+
return systems
|
25 |
+
|
26 |
+
|
27 |
+
def sample_system(n=None, constrain=True, bval=1, rng=None, beta=None, sample_fn=None):
|
28 |
+
'''Return n random affine transforms. If constrain=True, enforce the transforms
|
29 |
+
to be strictly contractive (by forcing singular values to be less than 1).
|
30 |
+
|
31 |
+
Args:
|
32 |
+
n (Union[range,Tuple[int,int],List[int,int],None]): range of values to sample from for the number of
|
33 |
+
transforms to sample. If None (default), then sample from range(2, 8).
|
34 |
+
constrain (bool): if True, enforce contractivity of transformations. Technically, an IFS must be
|
35 |
+
contractive; however, FractalDB does not enforce it during search, so it is left as an option here.
|
36 |
+
Default: True.
|
37 |
+
bval (Union[int,float]): maximum magnitude of the translation parameters sampled for each transform.
|
38 |
+
The translation parameters don't effect contractivity, and so can be chosen arbitrarily. Ignored and set
|
39 |
+
to 1 when constrain is False. Default: 1.
|
40 |
+
rng (Optional[numpy.random._generator.Generator]): random number generator. If None (default), it defaults
|
41 |
+
to np.random.default_rng().
|
42 |
+
beta (float or Tuple[float, float]): range for weighted sum of singular values when constrain==True. Let
|
43 |
+
q ~ U(beta[0], beta[1]), then we enforce $\sum_{i=0}^{n-1} (s^i_1 + 2*s^i_2) = q$.
|
44 |
+
sample_fn (callable): function used for sampling singular values. Should accept three arguments: n, for
|
45 |
+
the size of the system; a, for the sigma-factor; and rng, the random generator. When None (default),
|
46 |
+
uses sample_svs.
|
47 |
+
|
48 |
+
Returns:
|
49 |
+
Numpy array of shape (n, 2, 3), containing n sets of 2x3 affine transformation matrices.
|
50 |
+
'''
|
51 |
+
# Numpy乱数生成
|
52 |
+
if rng is None:
|
53 |
+
rng = np.random.default_rng(seed=0)
|
54 |
+
|
55 |
+
# 重ね合わせ方程式の数
|
56 |
+
if n is None:
|
57 |
+
n = rng.integers(2, 8)
|
58 |
+
elif isinstance(n, range):
|
59 |
+
n = rng.integers(n.start, n.stop)
|
60 |
+
elif isinstance(n, (tuple, list)):
|
61 |
+
n = rng.integers(*n)
|
62 |
+
|
63 |
+
# まともなフラクタル生成範囲
|
64 |
+
if beta is None:
|
65 |
+
beta = ((5 + n) / 2, (6 + n) / 2)
|
66 |
+
|
67 |
+
# 何かの関数
|
68 |
+
if sample_fn is None:
|
69 |
+
sample_fn = sample_svs
|
70 |
+
|
71 |
+
# まともな範囲のパラメータに制限
|
72 |
+
if constrain:
|
73 |
+
# sample a matrix with singular values < 1 (a contraction)
|
74 |
+
# 1. sample the singular vectors--random orthonormal matrices--by randomly rotating the standard basis
|
75 |
+
base = np.sign(rng.random((2*n, 2, 1)) - 0.5) * np.eye(2)
|
76 |
+
# 回転角度
|
77 |
+
angle = rng.uniform(-np.pi, np.pi, 2*n)
|
78 |
+
# 回転行列
|
79 |
+
ss = np.sin(angle)
|
80 |
+
cc = np.cos(angle)
|
81 |
+
rmat = np.empty((2 * n, 2, 2))
|
82 |
+
rmat[:, 0, 0] = cc
|
83 |
+
rmat[:, 0, 1] = -ss
|
84 |
+
rmat[:, 1, 0] = ss
|
85 |
+
rmat[:, 1, 1] = cc
|
86 |
+
uv = rmat @ base
|
87 |
+
u, v = uv[:n], uv[n:]
|
88 |
+
# 2. sample the singular values
|
89 |
+
a = rng.uniform(*beta)
|
90 |
+
s = sample_fn(n, a, rng)
|
91 |
+
# 3. sample the translation parameters from Uniform(-bval, bval) and create the transformation matrix
|
92 |
+
m = np.empty((n, 2, 3))
|
93 |
+
# 回転行列
|
94 |
+
m[:, :, :2] = u * s[:, None, :] @ v
|
95 |
+
# 並進行列
|
96 |
+
m[:, :, 2] = rng.uniform(-bval, bval, (n, 2))
|
97 |
+
else:
|
98 |
+
m = rng.uniform(-1, 1, (n, 2, 3))
|
99 |
+
|
100 |
+
return m
|
101 |
+
|
102 |
+
|
103 |
+
|
104 |
+
def sample_svs(n, a, rng=None):
|
105 |
+
'''Sample singular values. 2*`n` singular values are sampled such that the following conditions
|
106 |
+
are satisfied, for singular values sv_{i} and i = 0, ..., 2n-1:
|
107 |
+
|
108 |
+
1. 0 <= sv_{i} <= 1
|
109 |
+
2. sv_{2i} >= sv_{2i+1}
|
110 |
+
3. w.T @ S = `a`, for S = [sv_{0}, ..., sv_{2n-1}] and w = [1, 2, ..., 1, 2]
|
111 |
+
|
112 |
+
Args:
|
113 |
+
n (int): number of pairs of singular values to sample.
|
114 |
+
a (float): constraint on the weighted sum of all singular values. Note that a must be in the
|
115 |
+
range (0, 3*n).
|
116 |
+
rng (Optional[numpy.random._generator.Generator]): random number generator. If None (default), it defaults
|
117 |
+
to np.random.default_rng().
|
118 |
+
|
119 |
+
Returns:
|
120 |
+
Numpy array of shape (n, 2) containing the singular values.
|
121 |
+
'''
|
122 |
+
if rng is None: rng = np.random.default_rng()
|
123 |
+
if a < 0: a == 0
|
124 |
+
elif a > 3*n: a == 3*n
|
125 |
+
s = np.empty((n, 2))
|
126 |
+
p = a
|
127 |
+
q = a - 3*n + 3
|
128 |
+
# sample the first 2*(n-1) singular values (first n-1 pairs)
|
129 |
+
for i in range(n - 1):
|
130 |
+
s1 = rng.uniform(max(0, q/3), min(1, p))
|
131 |
+
q -= s1
|
132 |
+
p -= s1
|
133 |
+
s2 = rng.uniform(max(0, q/2), min(s1, p/2))
|
134 |
+
q = q - 2 * s2 + 3
|
135 |
+
p -= 2 * s2
|
136 |
+
s[i, :] = s1, s2
|
137 |
+
# sample the last pair of singular values
|
138 |
+
s2 = rng.uniform(max(0, (p-1)/2), p/3)
|
139 |
+
s1 = p - 2*s2
|
140 |
+
s[-1, :] = s1, s2
|
141 |
+
|
142 |
+
return s
|
143 |
+
|
144 |
+
def sample_svs_rej(n, a, rng=None):
|
145 |
+
'''Sample singular values uniformly from the joint distribution over the n-dimensional surface
|
146 |
+
defined by the constraints (see sample_svs). Uniform sampling is achieved by means of rejection
|
147 |
+
sampling.
|
148 |
+
|
149 |
+
Args:
|
150 |
+
n (int): number of pairs of singular values to sample.
|
151 |
+
a (float): constraint on the weighted sum of all singular values. Note that a must be in the
|
152 |
+
range (0, 3*n).
|
153 |
+
rng (Optional[numpy.random._generator.Generator]): random number generator. If None (default), it defaults
|
154 |
+
to np.random.default_rng().
|
155 |
+
|
156 |
+
Returns:
|
157 |
+
Numpy array of shape (n, 2) containing the singular values.
|
158 |
+
'''
|
159 |
+
if rng is None:
|
160 |
+
rng = np.random.default_rng()
|
161 |
+
if a < 0: a = 0
|
162 |
+
elif a > 3 * n: a = 3 * n
|
163 |
+
|
164 |
+
w = np.ones(2 * n - 1)
|
165 |
+
w[1::2] = 2
|
166 |
+
s = np.zeros((n, 2))
|
167 |
+
for i in range(1000):
|
168 |
+
s.ravel()[:-1] = rng.random(2 * n - 1)
|
169 |
+
# restrict to below the y=x line
|
170 |
+
r = s[:, 1] > s[:, 0]
|
171 |
+
s[r, :] = s[r][:, ::-1]
|
172 |
+
# check if valid or reject
|
173 |
+
b = (a - w @ s.ravel()[:-1]) / 2
|
174 |
+
if b <= s[-1, 0] and b >= 0:
|
175 |
+
s[-1, 1] = b
|
176 |
+
break
|
177 |
+
else:
|
178 |
+
print('Rejection sampling failed')
|
179 |
+
return s
|
src/validator.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from PIL import Image
|
3 |
+
from tqdm import tqdm
|
4 |
+
|
5 |
+
class Validator():
|
6 |
+
def __init__(self, data_format: dict, verbose=False) -> None:
|
7 |
+
assert isinstance(data_format, dict)
|
8 |
+
self.data_format = data_format
|
9 |
+
if verbose:
|
10 |
+
print('\nValidation details:')
|
11 |
+
for k, v in self.data_format.items():
|
12 |
+
print(' {}: {}'.format(k, v))
|
13 |
+
self.data = None
|
14 |
+
print('\nValidation:')
|
15 |
+
|
16 |
+
|
17 |
+
def check_data(self, result) -> None:
|
18 |
+
raise NotImplementedError
|
19 |
+
|
20 |
+
|
21 |
+
def check_samples(self, result) -> None:
|
22 |
+
raise NotImplementedError
|
23 |
+
|
24 |
+
|
25 |
+
def check_dtype(self, result) -> None:
|
26 |
+
raise NotImplementedError
|
27 |
+
|
28 |
+
|
29 |
+
def check_keys(self, result) -> None:
|
30 |
+
raise NotImplementedError
|
31 |
+
|
32 |
+
|
33 |
+
def check_details(self, result) -> None:
|
34 |
+
raise NotImplementedError
|
35 |
+
|
36 |
+
|
37 |
+
def validate(self, result) -> None:
|
38 |
+
self.check_data(result)
|
39 |
+
self.check_samples(result)
|
40 |
+
self.check_dtype(result)
|
41 |
+
self.check_keys(result)
|
42 |
+
self.check_details(result)
|
43 |
+
|
44 |
+
|
45 |
+
def get_data(self) -> None:
|
46 |
+
return self.data
|
47 |
+
|
48 |
+
|
49 |
+
class ImageFolderValidator(Validator):
|
50 |
+
def check_data(self, result) -> None:
|
51 |
+
msg = ' Checking data...'
|
52 |
+
print(msg, end='\r')
|
53 |
+
for category in tqdm(os.listdir(result)):
|
54 |
+
if not os.path.isdir(os.path.join(result, category)):
|
55 |
+
raise NotADirectoryError('Not a directory.')
|
56 |
+
if len(os.listdir(os.path.join(result, category))) == 0:
|
57 |
+
raise NullError('No data in {}'.format(category))
|
58 |
+
print(msg+' Done')
|
59 |
+
|
60 |
+
|
61 |
+
def check_samples(self, result) -> None:
|
62 |
+
msg = ' Checking samples...'
|
63 |
+
print(msg, end='\r')
|
64 |
+
for category in tqdm(os.listdir(result)):
|
65 |
+
for image_path in os.listdir(os.path.join(result, category)):
|
66 |
+
try:
|
67 |
+
img = Image.open(os.path.join(result, category, image_path))
|
68 |
+
except:
|
69 |
+
raise SampleError('Missing samples or invalid samples found.')
|
70 |
+
print(msg+' Done')
|
71 |
+
|
72 |
+
|
73 |
+
def check_dtype(self, result) -> None:
|
74 |
+
msg = ' Checking dtype...'
|
75 |
+
print(msg, end='\r')
|
76 |
+
num_channels = None
|
77 |
+
size = None
|
78 |
+
count = 0
|
79 |
+
for category in tqdm(os.listdir(result)):
|
80 |
+
for image_path in os.listdir(os.path.join(result, category)):
|
81 |
+
img = Image.open(os.path.join(result, category, image_path))
|
82 |
+
c = len(img.getbands())
|
83 |
+
if num_channels != c or size != img.size:
|
84 |
+
count += 1
|
85 |
+
num_channels = c
|
86 |
+
size = img.size
|
87 |
+
if count >= 2:
|
88 |
+
raise DimError('Dim mismatch found.')
|
89 |
+
print(msg+' Done')
|
90 |
+
|
91 |
+
|
92 |
+
def check_keys(self, result) -> None:
|
93 |
+
pass
|
94 |
+
|
95 |
+
|
96 |
+
def check_details(self, result) -> None:
|
97 |
+
msg = ' Checking details...'
|
98 |
+
num_categories = self.data_format['num_categories']
|
99 |
+
num_images = self.data_format['num_images']
|
100 |
+
if len(os.listdir(result))!=num_categories:
|
101 |
+
raise NumCategoryError('Number of categories is not {}'.format(num_categories))
|
102 |
+
for category in tqdm(os.listdir(result)):
|
103 |
+
image_paths = os.listdir(os.path.join(result, category))
|
104 |
+
if len(image_paths)!=num_images:
|
105 |
+
raise NumImageError('Number of images is not {} in {}'.format(num_images, category))
|
106 |
+
print(msg+' Done')
|
107 |
+
|
108 |
+
|
109 |
+
class NotADirectoryError(Exception):
|
110 |
+
pass
|
111 |
+
|
112 |
+
|
113 |
+
class SampleError(Exception):
|
114 |
+
pass
|
115 |
+
|
116 |
+
|
117 |
+
class DimError(Exception):
|
118 |
+
pass
|
119 |
+
|
120 |
+
|
121 |
+
class DtypeError(Exception):
|
122 |
+
pass
|
123 |
+
|
124 |
+
|
125 |
+
class ExtentionError(Exception):
|
126 |
+
pass
|
127 |
+
|
128 |
+
|
129 |
+
class DelimiterError(Exception):
|
130 |
+
pass
|
131 |
+
|
132 |
+
|
133 |
+
class NumColumnsError(Exception):
|
134 |
+
pass
|
135 |
+
|
136 |
+
|
137 |
+
class NullError(Exception):
|
138 |
+
pass
|
139 |
+
|
140 |
+
|
141 |
+
class DiscreteDataError(Exception):
|
142 |
+
pass
|
143 |
+
|
144 |
+
|
145 |
+
class MaximumExceedError(Exception):
|
146 |
+
pass
|
147 |
+
|
148 |
+
|
149 |
+
class InstanceError(Exception):
|
150 |
+
pass
|
151 |
+
|
152 |
+
|
153 |
+
class NumCategoryError(Exception):
|
154 |
+
pass
|
155 |
+
|
156 |
+
|
157 |
+
class NumImageError(Exception):
|
158 |
+
pass
|