ForNet / ForNet.py
TNauen's picture
print -> logger.info
01ce0b4 verified
raw
history blame
28.8 kB
import gzip
import itertools
import json
import multiprocessing
import os
import pickle
import queue
import re
import urllib
import zipfile
from math import floor
from typing import Optional
import datasets
import numpy as np
from datasets import config
from datasets.arrow_dataset import Dataset
from datasets.arrow_reader import ArrowReader
from datasets.features.image import image_to_bytes
from datasets.fingerprint import Hasher
from PIL import Image, ImageFilter
from torchvision import transforms as T
from tqdm import tqdm
from classes import IMAGENET2012_CLASSES
logger = datasets.logging.get_logger(__name__)
_CITATION = """\
@misc{nauen2025foraug,
title={ForAug: Recombining Foregrounds and Backgrounds to Improve Vision Transformer Training with Bias Mitigation},
author={Tobias Christian Nauen and Brian Moser and Federico Raue and Stanislav Frolov and Andreas Dengel},
year={2025},
eprint={2503.09399},
archivePrefix={arXiv},
primaryClass={cs.CV},
}
"""
_DESCRIPTION = """\
ForNet is a dataset of foreground objects and backgrounds extracted (and infilled) from ImageNet. \
It's the output of the segmentation phase of the ForAug data augmentation. \
ForNet recombines these foregrounds and backgrounds on the fly to create new samples for training vision transformers.
"""
_GIT = "https://github.com/tobna/ForAug"
_HOMEPAGE = "Coming Soon"
_DATASET_URL = "https://huggingface.co/datasets/TNauen/ForNet/resolve/main/"
_CONST_URLS = (
[_DATASET_URL + "settings.txt"]
+ [_DATASET_URL + f"fg_bg_ratios_{part}.json" for part in ["train", "val"]]
+ [_DATASET_URL + f"hf_{part}_indices.json" for part in ["train", "val"]]
)
_PATCH_URLS = [_DATASET_URL + f"train_{i}.zip" for i in range(20)] + [_DATASET_URL + "val.zip"]
class RecombineDataset(Dataset):
"""Wrapper for ForNet dataset that recombines foregrounds and backgrounds on the fly."""
def __init__(
self,
*args,
background_combination,
fg_scale_jitter,
pruning_ratio,
fg_size_mode,
fg_bates_n,
mask_smoothing_sigma,
rel_jut_out,
orig_img_prob,
**kwargs,
):
"""Create the ForNet recombination dataset.
Args:
background_combination (str): Which backgrounds to combine with foregrounds. Options: "orig", "same", "all".
fg_scale_jitter (tuple[float]): How much should the size of the foreground be changed (random ratio). Example: (0.1, 0.8).
pruning_ratio (float): For pruning backgrounds, with (foreground size/background size) >= <pruning_ratio>. Backgrounds from images that contain very large foreground objects are mostly computer generated and therefore relatively unnatural. Full dataset: 1.1 .
fg_size_mode (str): How to determine the size of the foreground, based on the foreground sizes of the foreground and background images. Options: "range", "min", "max", "mean".
fg_bates_n (int): Bates parameter for the distribution of the object position in the foreground. Uniform Distribution: 1. The higher the value, the more likely the object is in the center. For fg_bates_n = 0, the object is always in the center.
mask_smoothing_sigma (float): Sigma for the Gaussian blur of the mask edge.
rel_jut_out (float): How much is the foreground allowed to stand/jut out of the background (and then cut off).
orig_img_prob (float | str): Probability to use the original image, instead of the fg-bg recombinations. Options: 0.0-1.0, "linear", "revlinear", "cos".
"""
super().__init__(*args, **kwargs)
assert (isinstance(orig_img_prob, float) and 0.0 <= orig_img_prob <= 1.0) or orig_img_prob in [
"linear",
"revlinear",
"cos",
], f"Invalid orig_img_prob {orig_img_prob}"
assert background_combination in [
"all",
"same",
"orig",
], f"Invalid background_combination {background_combination}"
assert fg_size_mode in [
"range",
"min",
"max",
"mean",
], f"Invalid fg_size_mode {fg_size_mode}"
self.background_combination = background_combination
self.fg_scale_jitter = fg_scale_jitter
self.pruning_ratio = pruning_ratio
self.fg_size_mode = fg_size_mode
self.fg_bates_n = fg_bates_n
self.mask_smoothing_sigma = mask_smoothing_sigma
self.rel_jut_out = rel_jut_out
self.orig_img_prob = orig_img_prob
self.epochs = 0
self._epoch = 0
self.cls_to_idx = {}
bg_rat_indices = super()._getitem(0)["bg_rat_idx_file"]
self.train = "train" in bg_rat_indices.split("/")[-1]
with open(bg_rat_indices, "r") as f:
bg_rat_indices = json.load(f)
for in_cls in bg_rat_indices:
if in_cls not in self.cls_to_idx:
self.cls_to_idx[in_cls] = []
for idx, rat in bg_rat_indices[in_cls]:
if rat < self.pruning_ratio:
self.cls_to_idx[in_cls].append(idx)
if self.background_combination == "all":
self.cls_to_idx["all"] = list(itertools.chain(*self.cls_to_idx.values()))
@property
def total_epochs(self):
return self.epochs
@total_epochs.setter
def total_epochs(self, value):
self.epochs = value
@property
def epoch(self):
return self._epoch
@epoch.setter
def epoch(self, value):
assert 0 <= value < self.epochs, f"Epoch {value} is out of bounds for range [0, {self.epochs})"
self._epoch = value
def _getitem(self, key):
fg_item = super()._getitem(key)
out_dict = {"label": fg_item["label"]}
in_cls = fg_item["path"].split("/")[0]
if (
(self.orig_img_prob == "linear" and np.random.rand() < self._epoch / self.epochs)
or (self.orig_img_prob == "revlinear" and np.random.rand() < (self._epoch - self.epochs) / self.epochs)
or (self.orig_img_prob == "cos" and np.random.rand() > np.cos(np.pi * self._epoch / (2 * self.epochs)))
or (
isinstance(self.orig_img_prob, float)
and self.orig_img_prob > 0.0
and np.random.rand() < self.orig_img_prob
)
):
# return original image
out_dict["image"] = fg_item["in"]
return out_dict
if self.background_combination == "orig":
bg_item = fg_item
elif self.background_combination == "same":
rand_idx = np.random.randint(len(self.cls_to_idx[in_cls]))
rand_idx = self.cls_to_idx[in_cls][rand_idx]
bg_item = super()._getitem(rand_idx)
else:
# all
rand_idx = np.random.randint(len(self.cls_to_idx["all"]))
rand_idx = self.cls_to_idx["all"][rand_idx]
bg_item = super()._getitem(rand_idx)
fg_img = fg_item["fg"].convert("RGBA")
bg_img = bg_item["bg"].convert("RGB")
bg_size = bg_img.size
bg_area = bg_size[0] * bg_size[1]
orig_fg_ratio = fg_item["fg/bg_area"]
bg_fg_ratio = bg_item["fg/bg_area"]
if self.fg_size_mode == "max":
goal_fg_ratio_lower = goal_fg_ratio_upper = max(orig_fg_ratio, bg_fg_ratio)
elif self.fg_size_mode == "min":
goal_fg_ratio_lower = goal_fg_ratio_upper = min(orig_fg_ratio, bg_fg_ratio)
elif self.fg_size_mode == "mean":
goal_fg_ratio_lower = goal_fg_ratio_upper = (orig_fg_ratio + bg_fg_ratio) / 2
else:
# range
goal_fg_ratio_lower = min(orig_fg_ratio, bg_fg_ratio)
goal_fg_ratio_upper = max(orig_fg_ratio, bg_fg_ratio)
fg_size_factor = T.ToTensor()(fg_img.split()[-1]).mean().item()
fg_scale = (
np.random.uniform(
goal_fg_ratio_lower * (1 - self.fg_scale_jitter),
goal_fg_ratio_upper * (1 + self.fg_scale_jitter),
)
/ fg_size_factor
)
goal_shape_y = round(np.sqrt(bg_area * fg_scale * fg_img.size[1] / fg_img.size[0]))
goal_shape_x = round(np.sqrt(bg_area * fg_scale * fg_img.size[0] / fg_img.size[1]))
fg_img = fg_img.resize((goal_shape_x, goal_shape_y))
if fg_img.size[0] > bg_size[0] or fg_img.size[1] > bg_size[1]:
# random crop to fit
goal_w, goal_h = (
min(fg_img.size[0], bg_size[0]),
min(fg_img.size[1], bg_size[1]),
)
fg_img = T.RandomCrop((goal_h, goal_w))(fg_img) if self.train else T.CenterCrop((goal_h, goal_w))(fg_img)
# paste fg on bg
z1, z2 = (
(
np.random.uniform(0, 1, abs(self.fg_bates_n)).mean(), # bates distribution n=1 => uniform
np.random.uniform(0, 1, abs(self.fg_bates_n)).mean(),
)
if self.fg_bates_n != 0
else (0.5, 0.5)
)
if self.fg_bates_n < 0:
z1 = z1 + 0.5 - floor(z1 + 0.5)
z2 = z2 + 0.5 - floor(z2 + 0.5)
x_min = -self.rel_jut_out * fg_img.size[0]
x_max = bg_size[0] - fg_img.size[0] * (1 - self.rel_jut_out)
y_min = -self.rel_jut_out * fg_img.size[1]
y_max = bg_size[1] - fg_img.size[1] * (1 - self.rel_jut_out)
if x_min > x_max:
x_min = x_max = (x_min + x_max) / 2
if y_min > y_max:
y_min = y_max = (y_min + y_max) / 2
offs_x = round(z1 * (x_max - x_min) + x_min)
offs_y = round(z2 * (y_max - y_min) + y_min)
paste_mask = fg_img.split()[-1]
if self.mask_smoothing_sigma > 0.0:
sigma = (np.random.rand() * 0.9 + 0.1) * self.mask_smoothing_sigma
paste_mask = paste_mask.filter(ImageFilter.GaussianBlur(radius=sigma))
paste_mask = paste_mask.point(lambda p: 2 * p - 255 if p > 128 else 0)
bg_img.paste(fg_img.convert("RGB"), (offs_x, offs_y), paste_mask)
bg_img = bg_img.convert("RGB")
out_dict["image"] = bg_img
return out_dict
def __str__(self):
return f"{self.__class__}(\n\t features: ['image', 'label'],\n\t num_rows: {len(self)},\n\tbackground_combination: {self.background_combination},\n\t pruning_ratio: {self.pruning_ratio},\n\t fg_size_mode: {self.fg_size_mode},\n\t mask_smoothing_sigma: {self.mask_smoothing_sigma},\n\t orig_img_prob: {self.orig_img_prob}\n)"
_CONFIG_HASH_IGNORE_KWARGS = [
"background_combination",
"fg_scale_jitter",
"pruning_ratio",
"fg_size_mode",
"fg_bates_n",
"mask_smoothing_sigma",
"rel_jut_out",
"orig_img_prob",
]
class ForNetConfig(datasets.BuilderConfig):
"""BuilderConfig for ForNet."""
def __init__(
self,
background_combination,
fg_scale_jitter,
pruning_ratio,
fg_size_mode,
fg_bates_n,
mask_smoothing_sigma,
rel_jut_out,
orig_img_prob,
**kwargs,
):
"""BuilderConfig for ForNet.
Args:
**kwargs: keyword arguments forwarded to super.
"""
super(ForNetConfig, self).__init__(**kwargs)
self.background_combination = background_combination
self.fg_scale_jitter = fg_scale_jitter
self.pruning_ratio = pruning_ratio
self.fg_size_mode = fg_size_mode
self.fg_bates_n = fg_bates_n
self.mask_smoothing_sigma = mask_smoothing_sigma
self.rel_jut_out = rel_jut_out
self.orig_img_prob = orig_img_prob
def __str__(self):
return f"ForNetConfig(name={self.name}, version={self.version}, data_dir={self.data_dir}, data_files={self.data_files}, description={self.description}, background_combination={self.background_combination}, fg_scale_jitter={self.fg_scale_jitter}, pruning_ratio={self.pruning_ratio}, fg_size_mode={self.fg_size_mode}, fg_bates_n={self.fg_bates_n}, mask_smoothing_sigma={self.mask_smoothing_sigma}, rel_jut_out={self.rel_jut_out}, orig_img_prob={self.orig_img_prob})"
def create_config_id(
self,
config_kwargs: dict,
custom_features=None,
) -> str:
"""The config id is used to build the cache directory.
By default it is equal to the config name.
However the name of a config is not sufficient to have a unique identifier for the dataset being generated
since it doesn't take into account:
- the config kwargs that can be used to overwrite attributes
- the custom features used to write the dataset
- the data_files for json/text/csv/pandas datasets.
Therefore the config id is just the config name with an optional suffix based on these.
"""
# Possibly add a suffix to the name to handle custom features/data_files/config_kwargs
suffix: Optional[str] = None
config_kwargs_to_add_to_suffix = config_kwargs.copy()
# name and version are already used to build the cache directory
config_kwargs_to_add_to_suffix.pop("name", None)
config_kwargs_to_add_to_suffix.pop("version", None)
# remove only recombination-relevant values
for k in _CONFIG_HASH_IGNORE_KWARGS:
config_kwargs_to_add_to_suffix.pop(k, None)
# data dir handling (when specified it points to the manually downloaded data):
# it was previously ignored before the introduction of config id because we didn't want
# to change the config name. Now it's fine to take it into account for the config id.
# config_kwargs_to_add_to_suffix.pop("data_dir", None)
if "data_dir" in config_kwargs_to_add_to_suffix:
if config_kwargs_to_add_to_suffix["data_dir"] is None:
config_kwargs_to_add_to_suffix.pop("data_dir", None)
else:
# canonicalize the data dir to avoid two paths to the same location having different
# hashes
data_dir = config_kwargs_to_add_to_suffix["data_dir"]
data_dir = os.path.normpath(data_dir)
config_kwargs_to_add_to_suffix["data_dir"] = data_dir
if config_kwargs_to_add_to_suffix:
# we don't care about the order of the kwargs
config_kwargs_to_add_to_suffix = {
k: config_kwargs_to_add_to_suffix[k] for k in sorted(config_kwargs_to_add_to_suffix)
}
if all(isinstance(v, (str, bool, int, float)) for v in config_kwargs_to_add_to_suffix.values()):
suffix = ",".join(
str(k) + "=" + urllib.parse.quote_plus(str(v)) for k, v in config_kwargs_to_add_to_suffix.items()
)
if len(suffix) > 32: # hash if too long
suffix = Hasher.hash(config_kwargs_to_add_to_suffix)
else:
suffix = Hasher.hash(config_kwargs_to_add_to_suffix)
if custom_features is not None:
m = Hasher()
if suffix:
m.update(suffix)
m.update(custom_features)
suffix = m.hexdigest()
if suffix:
config_id = self.name + "-" + suffix
if len(config_id) > config.MAX_DATASET_CONFIG_ID_READABLE_LENGTH:
config_id = self.name + "-" + Hasher.hash(suffix)
return config_id
return self.name
class ForNet(datasets.GeneratorBasedBuilder):
"""ForNet dataset."""
def __init__(self, *args, **kwargs):
"""Initialize the ForNet Builder."""
super().__init__(*args, **kwargs)
self.cls_to_idx_locs = {}
BUILDER_CONFIGS = [
ForNetConfig(
name="fornet",
version=datasets.Version("1.0.0", ""),
description="ForNet dataset",
background_combination="all",
fg_scale_jitter=0.3,
pruning_ratio=0.8,
fg_size_mode="range",
fg_bates_n=1,
mask_smoothing_sigma=4.0,
rel_jut_out=0.0,
orig_img_prob=0.0,
)
]
DEFAULT_WRITER_BATCH_SIZE = 1000
def _info(self):
return datasets.DatasetInfo(
description=_DESCRIPTION,
features=datasets.Features(
{
"path": datasets.Value("string"),
"bg": datasets.features.Image(),
"fg": datasets.features.Image(),
"in": datasets.features.Image(),
"label": datasets.features.ClassLabel(names=list(IMAGENET2012_CLASSES.values())),
"fg/bg_area": datasets.Value("float"),
"bg_rat_idx_file": datasets.Value("string"),
}
),
supervised_keys=("image", "label"),
homepage=_HOMEPAGE,
citation=_CITATION,
)
def _split_generators(self, dl_manager: datasets.DownloadManager):
urls_to_download = _CONST_URLS + _PATCH_URLS
dl_paths = dl_manager.download(urls_to_download)
train_re = re.compile(r".*/train_(\d+)\.zip$")
val_re = re.compile(r".*/val\.zip$")
train_patches = [f for f in dl_paths if train_re.match(f)]
val_patches = [f for f in dl_paths if val_re.match(f)]
hf_train_indices = [f for f in dl_paths if f.endswith("hf_train_indices.json")][0]
hf_val_indices = [f for f in dl_paths if f.endswith("hf_val_indices.json")][0]
cls_to_idx_locs = {
"train": hf_train_indices.replace("hf_train_indices", "train_cls_to_idx"),
"val": hf_val_indices.replace("hf_val_indices", "val_cls_to_idx"),
}
fg_bg_ratios = [
[f for f in dl_paths if f.endswith(f"fg_bg_ratios_{part}.json")][0] for part in ["train", "val"]
]
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={
"patch_files": train_patches,
"split": "train",
"hf_indices": hf_train_indices,
"cls_to_idx_loc": cls_to_idx_locs["train"],
"fg_bg_ratios": fg_bg_ratios[0],
},
),
datasets.SplitGenerator(
name=datasets.Split.VALIDATION,
gen_kwargs={
"patch_files": val_patches,
"split": "val",
"hf_indices": hf_val_indices,
"cls_to_idx_loc": cls_to_idx_locs["val"],
"fg_bg_ratios": fg_bg_ratios[1],
},
),
]
def _generate_examples(self, patch_files, split, hf_indices, cls_to_idx_loc, fg_bg_ratios):
logger.info(f"Generating examples from {len(patch_files)} patch files")
logger.info("Opening files")
class_to_zipfile = {}
for f in patch_files:
with zipfile.ZipFile(f, "r") as zf:
for name in zf.namelist():
if name.endswith(".pkl") or name.endswith(".pkl.gz"):
class_to_zipfile[name.split("/")[-2]] = f
file_ending = "pkl" if name.endswith(".pkl") else "pkl.gz"
name_start = "/".join(name.split("/")[:-2])
if len(name_start) > 0:
name_start += "/"
logger.info(f"Loading extra information: {hf_indices}, {fg_bg_ratios}")
with open(hf_indices, "r") as f:
path_to_in_idx = json.load(f)
idx_to_path = {v: k for k, v in path_to_in_idx.items()}
# print("idx_to_path", list(idx_to_path.items())[:5])
with open(fg_bg_ratios, "r") as f:
fg_bg_ratios = json.load(f)
fg_bg_ratios = {"/".join(k.split("/")[-2:]).split(".")[0]: v for k, v in fg_bg_ratios.items()}
# print("fg_bg_ratios", list(fg_bg_ratios.items())[:5])
logger.info("Starting extraction with ImageNet")
foraug_idx = 0
manager = multiprocessing.Manager()
num_workers = multiprocessing.cpu_count()
if os.environ.get("MAX_WORKERS", None):
num_workers = int(os.environ["MAX_WORKERS"])
in_queue = manager.Queue(maxsize=4 * num_workers)
ret_queue = manager.Queue(maxsize=4 * num_workers)
comm_dict = manager.dict()
comm_dict["running"] = True
running = True
comm_dict["n_errors"] = 0
if num_workers > 8:
num_workers -= 2 # leave some cores for the main process and imagenet iterator
in_proc = multiprocessing.Process(target=_in_iterator, args=(in_queue, split))
in_proc.start()
zip_procs = [
multiprocessing.Process(
target=_zip_loader,
args=(
in_queue,
ret_queue,
comm_dict,
patch_files,
class_to_zipfile,
name_start,
file_ending,
idx_to_path,
fg_bg_ratios,
),
)
for _ in range(num_workers)
]
for proc in zip_procs:
proc.start()
last_errors = 0
cls_to_idx = {}
while running:
if not ret_queue.empty():
data = ret_queue.get()
in_cls = data["path"].split("/")[0]
if in_cls not in cls_to_idx:
cls_to_idx[in_cls] = []
cls_to_idx[in_cls].append((foraug_idx, data["fg/bg_area"]))
if foraug_idx == 0:
data["bg_rat_idx_file"] = cls_to_idx_loc
yield foraug_idx, data
foraug_idx += 1
else:
if in_queue.empty() and not in_proc.is_alive():
comm_dict["running"] = False
running = False
tqdm.write("Finished imagenet iteration; waiting for zip loaders to finish")
if foraug_idx % 10_000 == 0:
errors = comm_dict["n_errors"]
if errors > last_errors:
last_errors = errors
tqdm.write(
f"@step {foraug_idx}: errors {errors}; error rate {errors / foraug_idx:.2%} (expected {6_610 / 1_274_227:.2%})"
)
in_proc.join()
for proc in zip_procs:
proc.join()
# tqdm.write("Finished all processes")
while not ret_queue.empty():
data = ret_queue.get()
in_cls = data["path"].split("/")[0]
if in_cls not in cls_to_idx:
cls_to_idx[in_cls] = []
cls_to_idx[in_cls].append(foraug_idx)
yield foraug_idx, data
foraug_idx += 1
tqdm.write("Done")
with open(cls_to_idx_loc, "w") as f:
json.dump(cls_to_idx, f)
def _as_streaming_dataset_single(self, *args, **kwargs):
raise NotImplementedError("ForNet does not support streaming datasets")
def _as_dataset(self, split=datasets.Split.TRAIN, in_memory=False):
"""Constructs a `Dataset`.
This is the internal implementation to overwrite called when user calls
`as_dataset`. It should read the pre-processed datasets files and generate
the `Dataset` object.
Args:
split (`datasets.Split`):
which subset of the data to read.
in_memory (`bool`, defaults to `False`):
Whether to copy the data in-memory.
Returns:
`Dataset`
"""
cache_dir = self._fs._strip_protocol(self._output_dir)
dataset_name = self.dataset_name
if self._check_legacy_cache():
dataset_name = self.name
dataset_kwargs = ArrowReader(cache_dir, self.info).read(
name=dataset_name,
instructions=split,
split_infos=self.info.splits.values(),
in_memory=in_memory,
)
fingerprint = self._get_dataset_fingerprint(split)
# print("config", self.config)
# print("rel data dir", self._relative_data_dir())
# print("split", str(split))
# print("fingerprint", fingerprint)
splitname = str(split)
if splitname == "validation":
splitname = "val"
return RecombineDataset(
fingerprint=fingerprint,
background_combination=self.config.background_combination,
fg_scale_jitter=self.config.fg_scale_jitter,
pruning_ratio=self.config.pruning_ratio,
fg_size_mode=self.config.fg_size_mode,
fg_bates_n=self.config.fg_bates_n,
mask_smoothing_sigma=self.config.mask_smoothing_sigma,
rel_jut_out=self.config.rel_jut_out,
orig_img_prob=self.config.orig_img_prob,
**dataset_kwargs,
)
def _create_builder_config(self, config_name=None, custom_features=None, **config_kwargs):
config_hash_kwargs = {k: v for k, v in config_kwargs.items() if k not in _CONFIG_HASH_IGNORE_KWARGS}
builder_config, config_id = super()._create_builder_config(config_name, custom_features, **config_hash_kwargs)
for k in _CONFIG_HASH_IGNORE_KWARGS:
if k in config_kwargs:
setattr(builder_config, k, config_kwargs[k])
return builder_config, config_id
def _in_iterator(in_queue, split):
if split == "val":
split = "validation"
imagenet = datasets.load_dataset("ILSVRC/imagenet-1k", split=split)
for idx, ex in enumerate(imagenet):
in_queue.put((idx, ex["image"]))
def _zip_loader(
in_queue,
ret_queue,
comm_dict,
patch_files,
class_to_zipfile,
name_start,
file_ending,
idx_to_path,
fg_bg_ratios,
):
while comm_dict["running"]:
if not in_queue.empty():
try:
in_idx, in_img = in_queue.get(block=False)
except queue.Empty:
continue
patch_name = idx_to_path[in_idx]
in_class, in_file_name = patch_name.split("/")
try:
with zipfile.ZipFile(class_to_zipfile[in_class], "r") as zf, (
zf.open(f"{name_start}{patch_name}.{file_ending}", "r")
if file_ending == "pkl"
else gzip.GzipFile(
fileobj=zf.open(f"{name_start}{patch_name}.{file_ending}", "r"),
mode="r",
)
) as pklf:
patch_data = pickle.load(pklf)
except KeyError:
comm_dict["n_errors"] += 1
continue
in_img = in_img.convert("RGB")
if "bg_diff" in patch_data:
if in_img.size != (
patch_data["bg_diff"].shape[1],
patch_data["bg_diff"].shape[0],
):
in_img = in_img.resize((patch_data["bg_diff"].shape[1], patch_data["bg_diff"].shape[0]))
else:
max_size = max(in_img.size)
if max_size > 512:
goal_size = (
round(in_img.size[0] * 512 / max_size),
round(in_img.size[1] * 512 / max_size),
)
in_img = in_img.resize(goal_size)
in_arr = np.array(in_img)
if "bg_diff" in patch_data:
bg_diff = patch_data["bg_diff"]
bg_img = in_arr.astype(np.int64) + bg_diff
bg_img = bg_img.clip(0, 255).astype(np.uint8)
bg_img = Image.fromarray(bg_img)
bg_img = image_to_bytes(bg_img)
else:
bg_img = None
if "fg_mask" in patch_data:
x_offs, y_offs = patch_data["fg_off"]
fg_mask = patch_data["fg_mask"]
fg_crop = in_arr[
y_offs : y_offs + fg_mask.shape[0],
x_offs : x_offs + fg_mask.shape[1],
]
fg_img = np.concatenate([fg_crop, fg_mask * 255], axis=-1).clip(0, 255).astype(np.uint8)
fg_img = Image.fromarray(fg_img)
fg_img = image_to_bytes(fg_img)
else:
fg_img = None
in_img = image_to_bytes(in_img)
ret_queue.put(
{
"path": patch_name,
"bg": bg_img,
"fg": fg_img,
"label": IMAGENET2012_CLASSES[in_class],
"in": in_img,
"fg/bg_area": fg_bg_ratios[patch_name],
}
)