|
import os
|
|
import shutil
|
|
import gc
|
|
import json
|
|
import pickle
|
|
import cv2
|
|
import numpy as np
|
|
from tqdm import tqdm
|
|
import threading
|
|
from concurrent.futures import ProcessPoolExecutor
|
|
|
|
from multi_fractal_db import ifs
|
|
from multi_fractal_db import serach_ifs_systems
|
|
from multi_fractal_db.multi_fractal_dataset import MultiFractalDataset
|
|
from multi_fractal_db.multi_fractal_generator import MultiGenerator
|
|
|
|
from PIL import Image
|
|
|
|
class Generator():
|
|
@classmethod
|
|
def get_params(cls, params_path):
|
|
|
|
cls.debug = True
|
|
|
|
|
|
with open(os.path.join(params_path, 'multi_fractal_ifs_params.json')) as f:
|
|
cls.ifs_params = json.load(f)
|
|
|
|
|
|
kwargs = dict(
|
|
|
|
num_systems=cls.ifs_params["num_systems"],
|
|
|
|
n=(2, 4),
|
|
bval=1,
|
|
beta=None,
|
|
sample_fn=None,
|
|
)
|
|
|
|
sys = serach_ifs_systems.random_systems(**kwargs)
|
|
cls.ifs_systems = {'params': sys, 'hparams': kwargs}
|
|
print(f"ifs_systems length {len(cls.ifs_systems['params'])}")
|
|
|
|
|
|
cls.debug = True
|
|
|
|
return True
|
|
|
|
@classmethod
|
|
def generate(cls, out_path, start_index : int = None, end_index : int = None, jpeg_quality : int = 95):
|
|
if cls.debug:
|
|
print(out_path)
|
|
|
|
|
|
base_path = out_path.replace("pretrain", "base")
|
|
|
|
|
|
num_classes = cls.ifs_params['num_classes']
|
|
|
|
num_image_per_class = cls.ifs_params['num_image_per_class']
|
|
|
|
if start_index is None:
|
|
start_index = 0
|
|
if end_index is None:
|
|
end_index = num_classes
|
|
|
|
|
|
for iclass in range(start_index, end_index):
|
|
print(f"iclass = {iclass:05}")
|
|
class_dir = os.path.join(out_path, f"{iclass:05}")
|
|
if os.path.exists(class_dir):
|
|
files = os.listdir(class_dir)
|
|
files = [f for f in files if f.endswith(".jpg")]
|
|
if len(files) == num_image_per_class:
|
|
print(f"this iclass already processed = {iclass:05}")
|
|
once_load_failed = False
|
|
for f in files:
|
|
path = os.path.join(class_dir, f)
|
|
try:
|
|
img = Image.open(path)
|
|
except:
|
|
once_load_failed = True
|
|
break
|
|
if not once_load_failed:
|
|
continue
|
|
else:
|
|
print(f"[RE] this iclass already processed = {iclass:05}, but file corrupted. ")
|
|
for f in files:
|
|
os.remove(os.path.join(class_dir, f))
|
|
else:
|
|
for f in files:
|
|
os.remove(os.path.join(class_dir, f))
|
|
|
|
base_images = []
|
|
|
|
for ib, ibase in enumerate([iclass*2, iclass*2+1]):
|
|
|
|
|
|
|
|
num_systems_per_calss = cls.ifs_params['num_systems_per_calss']
|
|
|
|
st = ibase * num_systems_per_calss
|
|
en = (ibase+1)*num_systems_per_calss
|
|
|
|
ifs_syss = {'params':cls.ifs_systems['params'][st:en],
|
|
'hparams': cls.ifs_systems['hparams']}
|
|
|
|
|
|
|
|
cache_size = min(500, num_image_per_class*num_systems_per_calss)
|
|
|
|
|
|
future = make_multi_fractal_images(
|
|
ifs_syss, cls.ifs_params, num_systems_per_calss,
|
|
num_image_per_class, cache_size, cls.debug, out_path, ibase)
|
|
base_images.append(future)
|
|
|
|
|
|
|
|
class_dir = os.path.join(out_path, f"{iclass:05}")
|
|
if os.path.exists(class_dir)==False:
|
|
os.makedirs(class_dir, exist_ok=True)
|
|
|
|
|
|
for idx in tqdm(range(num_image_per_class)):
|
|
|
|
image_base1 = base_images[0][idx]
|
|
image_base2 = base_images[1][idx]
|
|
|
|
alpha = 1.0
|
|
lam = np.clip(np.random.beta(alpha, alpha), 0.4, 0.6)
|
|
image_mixup = lam * image_base1 + (1 - lam) * image_base2
|
|
image_mixup = image_mixup.astype(np.uint8)
|
|
|
|
image_file = os.path.join(class_dir, f"{idx:05}.jpg")
|
|
cv2.imwrite(image_file, image_mixup, [cv2.IMWRITE_JPEG_QUALITY, jpeg_quality])
|
|
|
|
|
|
base_images = None
|
|
del base_images
|
|
futures = None
|
|
del futures
|
|
gc.collect()
|
|
|
|
|
|
def make_multi_fractal_images(ifs_systems, ifs_params,
|
|
num_systems_per_calss, num_image_per_class, cache_size,
|
|
debug, out_path, ibase):
|
|
|
|
multi_fractal_dataset = MultiFractalDataset(
|
|
ifs_params=ifs_systems,
|
|
num_systems=num_systems_per_calss,
|
|
num_class=1,
|
|
per_class=num_image_per_class,
|
|
generator=MultiGenerator(
|
|
color=ifs_params["color"],
|
|
background=ifs_params["background"],
|
|
niter=ifs_params["niter"],
|
|
patch=ifs_params["patch"],
|
|
n_objects=ifs_params["n_objects"],
|
|
size_range=ifs_params["size_range"],
|
|
jitter_params=ifs_params["jitter_params"],
|
|
cache_size=cache_size,
|
|
size=ifs_params["image_size"]
|
|
),
|
|
period=2)
|
|
|
|
if debug:
|
|
|
|
check_dir = out_path.replace("pretrain", "check")
|
|
if os.path.exists(check_dir)==False:
|
|
os.makedirs(check_dir, exist_ok=True)
|
|
|
|
for i, sys in enumerate(ifs_systems['params']):
|
|
image_gray = multi_fractal_dataset.generator.render(sys['system'])
|
|
image_gray = (image_gray * 255).astype(np.uint8)
|
|
|
|
image_file = os.path.join(check_dir, f"{ibase:05}_{i:02}.jpg")
|
|
cv2.imwrite(image_file, image_gray)
|
|
|
|
|
|
base_images = []
|
|
num_fractal_images = len(multi_fractal_dataset)
|
|
class_dir = os.path.join(check_dir, f"{ibase:05}")
|
|
os.makedirs(class_dir, exist_ok=True)
|
|
for idx in range(num_fractal_images):
|
|
|
|
image, labels = multi_fractal_dataset[idx]
|
|
|
|
image_file = os.path.join(class_dir, f"{idx:05}.png")
|
|
cv2.imwrite(image_file, image)
|
|
base_images.append(image)
|
|
|
|
|
|
multi_fractal_dataset = None
|
|
del multi_fractal_dataset
|
|
gc.collect()
|
|
|
|
return base_images
|
|
|
|
def multifractal_main(outputdir, start_index, end_index, jpeg_quality):
|
|
Generator.get_params('../params')
|
|
Generator.generate(outputdir, start_index, end_index, jpeg_quality)
|
|
|
|
if __name__ == "__main__":
|
|
import argparse
|
|
from tqdm import tqdm
|
|
from copy import deepcopy
|
|
import concurrent.futures
|
|
import time
|
|
from typing import List
|
|
import multiprocessing
|
|
worker_num=multiprocessing.cpu_count()
|
|
print("workers : ", worker_num)
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--fpath', type=str, default="../output/pretrain")
|
|
parser.add_argument('--total', type=int, default=1000)
|
|
parser.add_argument('--step', type=int, default=1000//worker_num+1)
|
|
parser.add_argument('--offset', type=int, default=0)
|
|
parser.add_argument('--jpeg_quality', type=int, default=95)
|
|
|
|
args = parser.parse_args()
|
|
|
|
os.makedirs(args.fpath, exist_ok=True)
|
|
|
|
executor = concurrent.futures.ProcessPoolExecutor(max_workers=worker_num)
|
|
futures : List[concurrent.futures.Future] = []
|
|
|
|
for i in range(args.offset, args.total, args.step):
|
|
start_index = i
|
|
end_index = i + args.step
|
|
futures.append(executor.submit(multifractal_main, args.fpath, start_index, end_index, args.jpeg_quality))
|
|
|
|
for future in tqdm(concurrent.futures.as_completed(futures)):
|
|
try:
|
|
rr = future.result()
|
|
except Exception as exc:
|
|
print('generated an exception: %s' % (exc))
|
|
|
|
print("All done!") |