File size: 15,815 Bytes
5ab6d2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""transforms.py - the transformations of the benchmark, each in a RANDOM mode (strength drawn uniformly from its range) and a WORST
mode (the most severe value of the range), in the six groups of the SynthID-Image paper's robustness evaluation (Gowal et al.,
"SynthID-Image: Image watermarking at internet scale", arXiv:2510.09263, 2025, Figure 3 and Section 8.2). PROTOCOL 'paper30' (2026-10-28):
the paper's 29 transformations besides Identity, in its six groups (Color 7, Combination 4, Noise 4, Overlay 3, Quality 3, Spatial 8),
plus one extra row ('jpeg', group 'extra') that is reported on its own and never enters an aggregate. The paper names its
transformations but publishes no strength ranges and no images, so the ranges below are this benchmark's own choice, stated per
transformation. "Worst" follows one rule for every method: the end of the range farthest from no change (on a log scale for
multiplicative factors: brightness, contrast and saturation 0.5, sharpness 0 = smoothed; for a symmetric range, the end that clips:
exposure +1 EV); spatial strengths are given for the paper's 512 px and scaled to the image side. Revised 2026-10-28 07:10 after critic
round 2, BEFORE any held-out run: the text overlay uses Pillow's BASIC layout (no OS library), denoise is a median filter (integer
arithmetic), sharpness runs 0-4 with worst 0.

  out, params = apply(name, mode, Image.open(src).convert('RGB'), seed_of(photo, name, mode))

seed_of(photo, name, mode) = int(sha256(f'{photo}:{name}:{mode}').hexdigest()[:8], 16): the same seed for a sealed photo and for its
unmarked twin, so both receive exactly the same transformation. A random draw that would leave the image (almost) unchanged - a factor
within 0.02 of 1, a noise level under 1 code value, a crop or zoom above 0.98, ... - is drawn again from the same stream (NO-OP REDRAW),
so no copy counts as "attacked" without being changed. `params` holds every value the transformation drew or used; label(name, params) is
the short form used in file names. S is the image side (512 or 1024): set transforms.S before applying. Pixels are reproduced exactly
with the versions in requirements.txt (the JPEG / WebP encoders and FreeType bundled in Pillow, and numpy's random streams, can differ
between versions)."""
import hashlib, io, math, os
import numpy as np
from PIL import Image, ImageEnhance, ImageOps, ImageDraw, ImageFont, ImageFilter

PROTOCOL = 'paper30'
S = int(os.environ.get('BENCH_S', '1024'))  # the benchmark's image side (prep.py): every photo is S x S
FONT = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'fonts', 'DejaVuSans-Bold.ttf')
P = {}  # the parameters of the transformation being applied (apply() clears it); every operation is Pillow / numpy, no OS library
def rec(**kw): P.update(kw)
def seed_of(photo, name, mode): return int(hashlib.sha256(f'{photo}:{name}:{mode}'.encode()).hexdigest()[:8], 16)
def u(r, a, b): return a + (b - a) * r.random()
def ud(r, a, b, ident, eps):
  """u(r, a, b) drawn again (same stream, at most 64 times) while it lies within eps of the identity value: no no-op copies"""
  for _ in range(64):
    x = u(r, a, b)
    if abs(x - ident) >= eps: return x
  return x
def jpeg(im, q): rec(jpeg_quality=int(q)); b = io.BytesIO(); im.save(b, 'JPEG', quality=int(q)); b.seek(0); return Image.open(b).convert('RGB')
def webp(im, q): rec(webp_quality=int(q)); b = io.BytesIO(); im.save(b, 'WEBP', quality=int(q)); b.seek(0); return Image.open(b).convert('RGB')
def arr(im): return np.asarray(im, np.float32)
def img(a): return Image.fromarray(np.clip(a, 0, 255).round().astype(np.uint8))
def enhance(kind, im, f):
  rec(**{kind: f}); return {'brightness': ImageEnhance.Brightness, 'contrast': ImageEnhance.Contrast, 'saturation': ImageEnhance.Color, 'sharpness': ImageEnhance.Sharpness}[kind](im).enhance(f)
def crop_resize(im, area, r):
  s = math.sqrt(area); w = int(S * s); x = int(r.random() * (S - w)); y = int(r.random() * (S - w)); rec(crop_area=area, crop_box=[x, y, x + w, y + w])
  return im.crop((x, y, x + w, y + w)).resize((S, S), Image.BICUBIC)
def rotate(im, deg): rec(rotate_deg=deg); return im.rotate(deg, Image.BICUBIC, fillcolor=(0, 0, 0))
def zoom_out(im, s, r):
  w = int(S * s); c = Image.new('RGB', (S, S), (0, 0, 0)); x = int(r.random() * (S - w)); y = int(r.random() * (S - w)); rec(zoom_scale=s, zoom_box=[x, y, x + w, y + w])
  c.paste(im.resize((w, w), Image.BICUBIC), (x, y)); return c
def exposure(im, ev):
  rec(exposure_ev=ev); a = arr(im) / 255; lin = np.where(a <= 0.04045, a / 12.92, ((a + 0.055) / 1.055) ** 2.4) * 2 ** ev; lin = np.clip(lin, 0, 1)
  return img(255 * np.where(lin <= 0.0031308, 12.92 * lin, 1.055 * lin ** (1 / 2.4) - 0.055))
def hue(im, h): rec(hue_shift=h); H, Sx, V = im.convert('HSV').split(); H = H.point(lambda v: int(v + h * 255) % 256); return Image.merge('HSV', (H, Sx, V)).convert('RGB')
def grayscale(im): rec(grayscale='ITU-R 601-2 luma (PIL ImageOps.grayscale)'); return ImageOps.grayscale(im).convert('RGB')
def flip(im, how): rec(flip=how); return ImageOps.mirror(im) if how == 'left-right' else ImageOps.flip(im)
def noise_gauss(im, sd, r): rec(gaussian_sd=sd); return img(arr(im) + r.normal(0, sd, (S, S, 3)))
def noise_impulse(im, p, r): rec(impulse_p=p); a = arr(im); m = r.random((S, S)); a[m < p / 2] = 0; a[(m >= p / 2) & (m < p)] = 255; return img(a)
def noise_shot(im, k, r): rec(shot_k=k); a = arr(im) / 255; return img(255 * r.poisson(a * k) / k)
def noise_speckle(im, sd, r): rec(speckle_sd=sd); a = arr(im); return img(a + a * r.normal(0, sd, (S, S, 3)))
def emoji(im, area, r):
  """an emoji-like overlay (a filled smiley: the paper's emoji overlay), covering `area` of the image at a random place"""
  d = int(S * math.sqrt(area)); x = int(r.random() * (S - d)); y = int(r.random() * (S - d)); rec(emoji_area=area, emoji_box=[x, y, x + d, y + d])
  c = im.copy(); g = ImageDraw.Draw(c)
  g.ellipse((x, y, x + d, y + d), fill=(255, 205, 40), outline=(60, 40, 0), width=max(2, d // 30)); e = d // 9
  g.ellipse((x + d * 0.3 - e, y + d * 0.35 - e, x + d * 0.3 + e, y + d * 0.35 + e), fill=(60, 40, 0)); g.ellipse((x + d * 0.7 - e, y + d * 0.35 - e, x + d * 0.7 + e, y + d * 0.35 + e), fill=(60, 40, 0))
  g.arc((x + d * 0.25, y + d * 0.35, x + d * 0.75, y + d * 0.8), 20, 160, fill=(60, 40, 0), width=max(2, d // 20)); return c
def text(im, size, alpha, r):
  """three semi-transparent white text lines at random places; the size is given for a 512 px image and scales with S"""
  # BASIC layout (critic round 2): Pillow's RAQM layout needs the OS's libfribidi, so the text drew differently on Windows / macOS /
  # slim containers; the basic layout uses only the FreeType bundled in the wheel -> the same pixels everywhere
  c = im.convert('RGBA'); L = Image.new('RGBA', c.size, (0, 0, 0, 0)); g = ImageDraw.Draw(L); px = int(size * S / 512); f = ImageFont.truetype(FONT, px, layout_engine=ImageFont.Layout.BASIC); at = []
  for k in range(3):
    xy = (int(r.random() * S * 0.6), int(r.random() * S * 0.85)); at.append(list(xy)); g.text(xy, ['WATERMARK', 'sample text', 'hello world'][k], font=f, fill=(255, 255, 255, int(alpha)))
  rec(text_px=px, text_alpha=int(alpha), text_at=at, text=['WATERMARK', 'sample text', 'hello world']); return Image.alpha_composite(c, L).convert('RGB')
def tint(im, rgb, k): a = arr(im); return img(a * (1 - k) + np.array(rgb, np.float32) * k)
INSTA = {  # five classic filter looks (approximations of Instagram's, as the paper's overlay group names "Instagram filters")
  'clarendon': lambda im: tint(ImageEnhance.Color(ImageEnhance.Contrast(im).enhance(1.2)).enhance(1.35), (127, 187, 227), 0.08),
  'gingham': lambda im: tint(ImageEnhance.Contrast(ImageEnhance.Brightness(im).enhance(1.05)).enhance(0.9), (230, 230, 250), 0.12),
  'juno': lambda im: tint(ImageEnhance.Color(ImageEnhance.Contrast(im).enhance(1.15)).enhance(1.35), (255, 220, 160), 0.07),
  'lark': lambda im: tint(ImageEnhance.Color(ImageEnhance.Brightness(im).enhance(1.08)).enhance(0.9), (200, 230, 255), 0.08),
  'reyes': lambda im: tint(ImageEnhance.Color(ImageEnhance.Contrast(ImageEnhance.Brightness(im).enhance(1.1)).enhance(0.85)).enhance(0.75), (239, 205, 173), 0.18)}
def insta(im, name): rec(filter=name); return INSTA[name](im)
def file_format(im, which): rec(file_format=which); return {'jpeg95': lambda x: jpeg(x, 95), 'webp90': lambda x: webp(x, 90), 'webp75': lambda x: webp(x, 75), 'webp50': lambda x: webp(x, 50)}[which](im)
def gblur(im, sigma): rec(blur_sigma=sigma); return im.filter(ImageFilter.GaussianBlur(radius=sigma))
def denoise(im, k):
  """a median-filter denoiser of window k x k (Pillow, integer arithmetic: the same pixels on every platform; critic round 2 - OpenCV's
  non-local means uses platform-dependent SIMD floating point), k scaled to the image side like the other spatial strengths"""
  k = max(3, int(round(k * S / 512)) | 1); rec(median_k=k); return im.filter(ImageFilter.MedianFilter(k))
def resize(im, f): w = max(16, int(round(S * f))); rec(resize_factor=f, resize_px=w); return im.resize((w, w), Image.BICUBIC)
def combined(im, r, crop, rot, worst):
  if crop: im = crop_resize(im, 0.5 if worst else u(r, 0.5, 1.0), r)
  if rot: im = rotate(im, 10 if worst else u(r, -10, 10))
  im = enhance('brightness', im, 0.7 if worst else u(r, 0.7, 1.3)); im = enhance('contrast', im, 0.7 if worst else u(r, 0.7, 1.3))
  return jpeg(im, 50 if worst else u(r, 50, 90))
SP = lambda sigma: sigma * S / 512  # a spatial strength given for the paper's 512 px, scaled to the image side
# name -> (group, random(im, r), worst(im, r)); ranges chosen by this benchmark (the paper gives none)
T = {
  'brightness': ('color', lambda im, r: enhance('brightness', im, ud(r, 0.5, 1.5, 1, 0.02)), lambda im, r: enhance('brightness', im, 0.5)),
  'contrast': ('color', lambda im, r: enhance('contrast', im, ud(r, 0.5, 1.5, 1, 0.02)), lambda im, r: enhance('contrast', im, 0.5)),
  'exposure': ('color', lambda im, r: exposure(im, ud(r, -1, 1, 0, 0.03)), lambda im, r: exposure(im, 1)),
  'grayscale': ('color', lambda im, r: grayscale(im), lambda im, r: grayscale(im)),
  'hue': ('color', lambda im, r: hue(im, ud(r, -0.1, 0.1, 0, 0.005)), lambda im, r: hue(im, 0.1)),
  'saturation': ('color', lambda im, r: enhance('saturation', im, ud(r, 0.5, 1.5, 1, 0.02)), lambda im, r: enhance('saturation', im, 0.5)),
  'sharpness': ('color', lambda im, r: enhance('sharpness', im, ud(r, 0, 4, 1, 0.05)), lambda im, r: enhance('sharpness', im, 0)),
  'combined': ('combination', lambda im, r: combined(im, r, True, False, False), lambda im, r: combined(im, r, True, False, True)),
  'combined_norotate_nocrop': ('combination', lambda im, r: combined(im, r, False, False, False), lambda im, r: combined(im, r, False, False, True)),
  'combined_nocrop_rotate': ('combination', lambda im, r: combined(im, r, False, True, False), lambda im, r: combined(im, r, False, True, True)),
  'combined_rotate': ('combination', lambda im, r: combined(im, r, True, True, False), lambda im, r: combined(im, r, True, True, True)),
  'gaussian_noise': ('noise', lambda im, r: noise_gauss(im, ud(r, 0, 20, 0, 1), r), lambda im, r: noise_gauss(im, 20, r)),
  'impulse_noise': ('noise', lambda im, r: noise_impulse(im, ud(r, 0, 0.05, 0, 0.001), r), lambda im, r: noise_impulse(im, 0.05, r)),
  'shot_noise': ('noise', lambda im, r: noise_shot(im, u(r, 60, 500), r), lambda im, r: noise_shot(im, 60, r)),
  'speckle_noise': ('noise', lambda im, r: noise_speckle(im, ud(r, 0, 0.2, 0, 0.005), r), lambda im, r: noise_speckle(im, 0.2, r)),
  'emoji_overlay': ('overlay', lambda im, r: emoji(im, u(r, 0.02, 0.15), r), lambda im, r: emoji(im, 0.15, r)),
  'instagram': ('overlay', lambda im, r: insta(im, sorted(INSTA)[int(r.random() * 5)]), lambda im, r: insta(im, 'reyes')),
  'light_text': ('overlay', lambda im, r: text(im, u(r, 20, 60), u(r, 60, 160), r), lambda im, r: text(im, 60, 160, r)),
  'file_format': ('quality', lambda im, r: file_format(im, ['jpeg95', 'webp90', 'webp75'][int(r.random() * 3)]), lambda im, r: file_format(im, 'webp50')),
  'gaussian_blur': ('quality', lambda im, r: gblur(im, SP(u(r, 0.5, 3.0))), lambda im, r: gblur(im, SP(3.0))),
  'denoise': ('quality', lambda im, r: denoise(im, u(r, 3, 7)), lambda im, r: denoise(im, 7)),
  'crop_resize': ('spatial', lambda im, r: crop_resize(im, ud(r, 0.25, 1, 1, 0.02), r), lambda im, r: crop_resize(im, 0.25, r)),
  'flip_lr': ('spatial', lambda im, r: flip(im, 'left-right'), lambda im, r: flip(im, 'left-right')),
  'flip_ud': ('spatial', lambda im, r: flip(im, 'top-bottom'), lambda im, r: flip(im, 'top-bottom')),
  'rotation': ('spatial', lambda im, r: rotate(im, ud(r, -45, 45, 0, 0.5)), lambda im, r: rotate(im, 45)),
  'small_rotation': ('spatial', lambda im, r: rotate(im, ud(r, -5, 5, 0, 0.25)), lambda im, r: rotate(im, 5)),
  'zoom_out': ('spatial', lambda im, r: zoom_out(im, ud(r, 0.5, 1, 1, 0.02), r), lambda im, r: zoom_out(im, 0.5, r)),
  'resize': ('spatial', lambda im, r: resize(im, ud(r, 0.25, 1, 1, 0.02)), lambda im, r: resize(im, 0.25)),
  'all_rotations': ('spatial', lambda im, r: rotate(im, ud(r, -180, 180, 0, 0.5)), lambda im, r: rotate(im, 135)),
  'jpeg': ('extra', lambda im, r: jpeg(im, u(r, 30, 95)), lambda im, r: jpeg(im, 30)),
}
GROUPS = ('color', 'combination', 'noise', 'overlay', 'quality', 'spatial')  # the paper's six; 'extra' is reported apart

def apply(name, mode, im, seed):
  """the transformation `name` in `mode` ('random' | 'worst') of an RGB image, with the seed of seed_of(): (image, parameters)"""
  P.clear(); fn = T[name][1] if mode == 'random' else T[name][2]
  out = fn(im, np.random.default_rng(seed)).convert('RGB'); return out, dict(P)

def _n(v, d):  # a number for a file name: d decimals, trailing zeros dropped ('-0.42', '63', '0.5')
  s = f'{v:.{d}f}'.rstrip('0').rstrip('.') if isinstance(v, float) else str(v); return '0' if s in ('-0', '') else s
def label(name, p):
  """the parameters in a file name (photo__transformation__mode__LABEL.png): what was applied, as precisely as a name can say it"""
  comb = '-'.join(x for x in [f'crop{_n(p["crop_area"], 3)}' if 'crop_area' in p else '', f'rot{_n(p["rotate_deg"], 2)}deg' if 'rotate_deg' in p else '',
                              f'bright{_n(p.get("brightness", 0.0), 3)}', f'contrast{_n(p.get("contrast", 0.0), 3)}', f'jpegq{p.get("jpeg_quality", "")}'] if x)
  f = {'brightness': lambda: f'factor{_n(p["brightness"], 3)}', 'contrast': lambda: f'factor{_n(p["contrast"], 3)}', 'saturation': lambda: f'factor{_n(p["saturation"], 3)}',
       'sharpness': lambda: f'factor{_n(p["sharpness"], 3)}', 'exposure': lambda: f'ev{_n(p["exposure_ev"], 3)}', 'grayscale': lambda: 'luma601',
       'hue': lambda: f'shift{_n(p["hue_shift"], 4)}', 'gaussian_noise': lambda: f'sd{_n(p["gaussian_sd"], 2)}', 'impulse_noise': lambda: f'p{_n(p["impulse_p"], 4)}',
       'shot_noise': lambda: f'k{_n(p["shot_k"], 1)}', 'speckle_noise': lambda: f'sd{_n(p["speckle_sd"], 3)}', 'emoji_overlay': lambda: f'area{_n(p["emoji_area"], 3)}',
       'instagram': lambda: p['filter'], 'light_text': lambda: f'size{p["text_px"]}px-alpha{p["text_alpha"]}', 'file_format': lambda: p['file_format'],
       'gaussian_blur': lambda: f'sigma{_n(p["blur_sigma"], 3)}px', 'denoise': lambda: f'median{p["median_k"]}px',
       'jpeg': lambda: f'q{p["jpeg_quality"]}', 'crop_resize': lambda: f'area{_n(p["crop_area"], 3)}', 'flip_lr': lambda: 'mirror', 'flip_ud': lambda: 'upside-down',
       'rotation': lambda: f'{_n(p["rotate_deg"], 2)}deg', 'small_rotation': lambda: f'{_n(p["rotate_deg"], 2)}deg', 'zoom_out': lambda: f'scale{_n(p["zoom_scale"], 3)}',
       'resize': lambda: f'factor{_n(p["resize_factor"], 3)}-{p["resize_px"]}px', 'all_rotations': lambda: f'{_n(p["rotate_deg"], 2)}deg'}
  return comb if name.startswith('combined') else f[name]()