File size: 8,340 Bytes
85805ad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | """Training-time augmentation. Deliverable for teammate A.
Applied ONLINE in Dataset.__getitem__. Nothing here is ever written to disk -- the on-disk
crops stay clean, and the eval sets (src/build_eval_sets.py) are the only degraded pixels
that get persisted.
Two rules this module exists to enforce:
1. COMPOSE. Each sample stacks 2-3 ops in random order. Real redistribution is a chain
(resize -> JPEG -> screenshot -> JPEG again), never one operation. A model trained on
single transforms fails under composed degradation.
2. TRAINING RANGES ARE CONTINUOUS, EVAL LEVELS ARE DISCRETE. Evaluation uses
JPEG q in {90, 70, 50, 30}. If training sampled those exact integers, the reported
robustness would be measuring memorization rather than generalization. The ranges below
span the eval points but the four exact values are skipped.
Note on resizing: `random_crop` and `rescale` do resample the image. That is deliberate and
is NOT in tension with the crop-not-resize rule in build_sid.py. There, resizing would have
destroyed the artifact signal before the model ever saw it. Here, resampling IS the
distortion we are teaching the model to survive.
"""
from __future__ import annotations
import io
import sys
from pathlib import Path
import numpy as np
from PIL import Image, ImageEnhance, ImageFilter
sys.path.insert(0, str(Path(__file__).resolve().parent))
import common as C # noqa: E402
# --------------------------------------------------------------------------------------
# individual ops: (PIL.Image, rng, params) -> PIL.Image, size preserved
# --------------------------------------------------------------------------------------
def _uniform(rng, lo, hi) -> float:
return float(rng.uniform(float(lo), float(hi)))
def op_jpeg(img: Image.Image, rng, p: dict, forbidden=()) -> Image.Image:
lo, hi = p["quality"]
q = int(round(_uniform(rng, lo, hi)))
# PIL needs an integer quality, so a continuous draw has to be rounded. Nudge off the
# discrete eval levels; the +1 bias on four integers out of ~66 is negligible.
while q in forbidden:
q += 1
q = int(np.clip(q, 1, 100))
buf = io.BytesIO()
img.save(buf, "JPEG", quality=q)
buf.seek(0)
out = Image.open(buf)
out.load()
return out.convert("RGB")
def op_blur(img: Image.Image, rng, p: dict, **_) -> Image.Image:
sigma = _uniform(rng, *p["sigma"])
return img.filter(ImageFilter.GaussianBlur(radius=sigma))
def op_noise(img: Image.Image, rng, p: dict, **_) -> Image.Image:
sigma = _uniform(rng, *p["sigma"]) # sigma is in [0, 1] image units
a = np.asarray(img, dtype=np.float32) / 255.0
a = a + rng.normal(0.0, sigma, a.shape).astype(np.float32)
return Image.fromarray((np.clip(a, 0.0, 1.0) * 255.0 + 0.5).astype(np.uint8), "RGB")
def op_jitter(img: Image.Image, rng, p: dict, **_) -> Image.Image:
for key, enh in (("brightness", ImageEnhance.Brightness),
("contrast", ImageEnhance.Contrast),
("saturation", ImageEnhance.Color)):
amt = float(p.get(key, 0.0))
if amt > 0:
img = enh(img).enhance(1.0 + _uniform(rng, -amt, amt))
return img
def op_random_crop(img: Image.Image, rng, p: dict, **_) -> Image.Image:
w, h = img.size
s = _uniform(rng, *p["scale"])
cw, ch = max(1, int(round(w * s))), max(1, int(round(h * s)))
x = int(rng.integers(0, w - cw + 1))
y = int(rng.integers(0, h - ch + 1))
return img.crop((x, y, x + cw, y + ch)).resize((w, h), Image.Resampling.BICUBIC)
def op_rescale(img: Image.Image, rng, p: dict, **_) -> Image.Image:
"""Downscale then upscale back: the classic 'someone reposted a screenshot' artifact."""
w, h = img.size
f = _uniform(rng, *p["factor"])
sw, sh = max(8, int(round(w * f))), max(8, int(round(h * f)))
small = img.resize((sw, sh), Image.Resampling.BILINEAR)
return small.resize((w, h), Image.Resampling.BILINEAR)
OPS = {
"jpeg": op_jpeg,
"blur": op_blur,
"noise": op_noise,
"jitter": op_jitter,
"random_crop": op_random_crop,
"rescale": op_rescale,
}
# --------------------------------------------------------------------------------------
class TrainAugment:
"""Randomly stacks `n_ops_min`..`n_ops_max` distinct ops, in random order.
aug = TrainAugment(load_config())
img = aug(img) # PIL RGB in, PIL RGB out, same size
"""
def __init__(self, cfg: dict, rng=None):
a = cfg["augment"]
self.cfg = a
self.n_min = int(a["n_ops_min"])
self.n_max = int(a["n_ops_max"])
self.names = [n for n in a["ops"] if n in OPS]
self.params = a["ops"]
self.weights = np.array([float(a["ops"][n].get("p", 1.0)) for n in self.names])
self.weights = self.weights / self.weights.sum()
self.forbidden = tuple(int(q) for q in a.get("forbidden_jpeg_qualities", ()))
self.rng = rng if rng is not None else np.random.default_rng()
self._check_eval_overlap(cfg)
def _check_eval_overlap(self, cfg: dict) -> None:
"""Fail loudly if the training JPEG range ever lands on an eval level."""
eval_qs = {int(c["quality"]) for c in cfg["eval_sets"]["conditions"].values()
if c.get("op") == "jpeg"}
missing = eval_qs - set(self.forbidden)
if missing:
raise ValueError(
"eval JPEG levels %s are not listed in augment.forbidden_jpeg_qualities; "
"training would sample the exact values it is evaluated on, and the "
"robustness numbers would measure memorization" % sorted(missing))
def seeded(self, *key):
"""A copy whose randomness is derived from `key` -- for reproducible spot checks.
Training itself should NOT use this: augmentation must differ every epoch.
"""
new = object.__new__(TrainAugment)
new.__dict__.update(self.__dict__)
new.rng = C.md5_rng(*key)
return new
def plan(self, rng=None):
"""The ops chosen for one sample, without applying them (used by the self-test)."""
rng = rng or self.rng
k = int(rng.integers(self.n_min, self.n_max + 1))
k = min(k, len(self.names))
idx = rng.choice(len(self.names), size=k, replace=False, p=self.weights)
return [self.names[i] for i in idx]
def __call__(self, img: Image.Image, rng=None) -> Image.Image:
rng = rng if rng is not None else self.rng
for name in self.plan(rng):
img = OPS[name](img, rng, self.params[name], forbidden=self.forbidden)
return img.convert("RGB")
# --------------------------------------------------------------------------------------
def _self_test() -> int:
"""python src/transforms.py -- checks the two rules actually hold."""
import collections
cfg = C.load_config()
aug = TrainAugment(cfg, rng=np.random.default_rng(0))
counts = collections.Counter()
for _ in range(20000):
counts[len(aug.plan())] += 1
print("ops per sample:", dict(sorted(counts.items())))
assert set(counts) <= {2, 3}, "composition rule violated"
rng = np.random.default_rng(1)
qs = []
for _ in range(20000):
lo, hi = cfg["augment"]["ops"]["jpeg"]["quality"]
q = int(round(rng.uniform(lo, hi)))
while q in aug.forbidden:
q += 1
qs.append(q)
hit = {q: qs.count(q) for q in cfg["augment"]["forbidden_jpeg_qualities"]}
print("draws landing on eval levels:", hit)
assert sum(hit.values()) == 0, "training sampled an eval JPEG level"
print("q range actually used: %d..%d over %d distinct values"
% (min(qs), max(qs), len(set(qs))))
img = Image.fromarray(
np.random.default_rng(2).integers(0, 255, (256, 256, 3), dtype=np.uint8), "RGB")
for name, fn in OPS.items():
out = fn(img, np.random.default_rng(3), cfg["augment"]["ops"][name],
forbidden=aug.forbidden)
assert out.size == img.size and out.mode == "RGB", name
print(" %-12s ok size=%s mode=%s" % (name, out.size, out.mode))
out = aug(img)
print("composed ok:", out.size, out.mode)
print("ALL CHECKS PASSED")
return 0
if __name__ == "__main__":
raise SystemExit(_self_test())
|