API Reference
120 classes and 29 functions across 33 modules, generated by static AST analysis of the source tree. Private helpers and non-exported internals are omitted.
Quick start
Four complete recipes cover almost everything the library is used for: evaluating a watermark you wrote, evaluating an attack you wrote, and benchmarking the built-in post-generation and in-generation watermark families. All four end in the same wl.evaluate() call.
1. Evaluate your watermark model
Subclass BaseWatermarkModel, implement embed, extract and recover, then hand the instance to wl.evaluate() together with a dataset and the default attacker set.
from numpy import ndarray
import watermarklab as wl
from typing import List, Any
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_IMAGES
from watermarklab.utils.basemodel import BaseWatermarkModel, Result
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
class YourWatermark(BaseWatermarkModel):
"""Skeleton for a custom watermark model. Implement `embed`, `extract`, `recover`."""
def __init__(self, bits_len: int, img_size: int, modelname: str):
super().__init__(bits_len, img_size, modelname)
def embed(self, cover_list: List[Any], secrets: List[Any]) -> Result:
"""Embed watermark into cover data."""
pass # Replace with your logic
def extract(self, stego_list: List[ndarray]) -> Result:
"""Extract watermark from stego data."""
pass # Replace with your logic
def recover(self, stego_list: List[ndarray]) -> Result:
"""Recover original cover data (for reversible watermarking)."""
pass # Replace with your logic or handle if not applicable
# --- Set Up Evaluation ---
default_attackers = AttackersWithFactorsModel() # Default set of attackers
# Instantiate your model (replace `your_payload` and `your_img_size`)
your_payload = 100
your_img_size = 400
stegastamp = YourWatermark(bits_len=your_payload, img_size=your_img_size, modelname="YourModelName")
# Load dataset: MS COCO 2017 validation images
kodak24_400_100 = MS_COCO_2017_VAL_IMAGES(im_size=your_img_size, bit_len=your_payload, image_num=500)
# Create DataLoader for batched processing
dataloader_400_100 = DataLoader(kodak24_400_100, batch_size=64)
# --- Run Evaluation ---
# Evaluate your model
wl.evaluate("save_results/PGWs", stegastamp, default_attackers, dataloader_400_100)
# --- Visualize Results (Optional) ---
# Plot robustness results
wl.draw.plot_model_robustness_under_single_attack([f"save_results/PGWs/{stegastamp.modelname}"], "save_draw")What the three methods must return
embed(cover_list, secrets)
Receives the cover images (for PGW) or prompts (for IGW) and the secret bit sequences. Returns a Result carrying the watermarked data and the embedded bits.
extract(stego_list)
Receives watermarked (and possibly attacked) images and returns a Result with the recovered bit sequences, which are compared against the ground-truth secret.
recover(stego_list)
Optional. Only meaningful for reversible watermarking; raise NotImplementedError if your method cannot restore the cover.
bits_len and img_size, and the dataset must match them (MS_COCO_2017_VAL_IMAGES(im_size=..., bit_len=...)). Most reference models constrain the payload — for example rivaGAN and DctDwtSvd require exactly 32 bits.Next: evaluate your own attacker →
2. Evaluate your attacker
Subclass BaseTestAttackModel, implement attack, wrap it in AttackerWithFactors and pass it to AttackersWithFactorsModel so the evaluation sweeps it across the intensity factors you choose.
from typing import List
from numpy import ndarray
import watermarklab as wl
from watermarklab.utils.data import DataLoader
from watermarklab.watermarks.PGWs import StegaStamp # Example watermark model
from watermarklab.datasets import MS_COCO_2017_VAL_IMAGES # Example dataset
from watermarklab.utils.basemodel import BaseTestAttackModel, AttackerWithFactors
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
# --- Define Your Custom Attacker ---
class YourAttacker(BaseTestAttackModel):
"""
Example class for a user-defined attacker.
You need to inherit from BaseTestAttackModel and implement the attack method.
"""
def __init__(self, noisename: str, factor_inversely_related: bool):
"""
Initializes the custom attacker.
Args:
noisename (str): Name of the attacker, used for identification and display.
factor_inversely_related (bool):
Indicates if the attack factor is inversely related to the attack strength.
E.g., JPEG quality factor: higher value means less distortion.
"""
# Call the parent class constructor
super().__init__(noisename, factor_inversely_related)
# You can add custom attributes here
def attack(self, stego_img: List[ndarray], cover_img: List[ndarray], factor: float) -> List[ndarray]:
"""
Applies the attack to the watermarked (stego) images.
Args:
stego_img (List[ndarray]): List of watermarked images (Stego images).
cover_img (List[ndarray]): List of original cover images (may be used as reference).
factor (float): Factor controlling the intensity of the attack.
Returns:
List[ndarray]: List of images after the attack has been applied.
"""
# --- Implement your attack logic here ---
return stego_img # Placeholder, replace with actual attack logic
# --- Set Up Evaluation ---
# 1. Configure watermark model parameters
your_payload = 100 # Watermark bit length
your_img_size = 400 # Image size (assumed square)
# 2. Instantiate the watermark model (using StegaStamp as an example)
stegastamp = StegaStamp(bits_len=your_payload, img_size=your_img_size)
# 3. Configure your custom attacker
your_attacker_factors = [1, 2, 3, 4, 5, 6, 7] # Define attack strength factors to test
yourattacker = YourAttacker(
noisename="YourModelName", # Your attacker's name
factor_inversely_related=False # Set based on your attack's characteristics
)
# 4. Wrap your attacker in AttackerWithFactors for the evaluation framework
# This specifies the attacker's name, factors, and symbol for display/plots
your_custom_attacker_config = AttackerWithFactors(
attacker=yourattacker,
attackername="YourAttackerName", # Name for display in results/plots
factors=your_attacker_factors, # List of attack strength factors
factorsymbol=r"$\sigma$" # Symbol for the factor (e.g., '$\sigma$')
)
# 5. Create AttackersWithFactorsModel instance, passing your custom attacker
# This ensures the evaluation uses only your defined attacker
default_attackers = AttackersWithFactorsModel(
default_attackers=[your_custom_attacker_config]
)
# 6. Load the dataset
# Using MS COCO 2017 validation set images
kodak24_400_100 = MS_COCO_2017_VAL_IMAGES(
im_size=your_img_size, # Image size
bit_len=your_payload, # Watermark bit length
image_num=500 # Number of images to use
)
# 7. Create DataLoader for batch processing
dataloader_400_100 = DataLoader(kodak24_400_100, batch_size=64)
# --- Run Evaluation ---
# Use watermarklab's evaluate function to test the watermark model
# against your custom attacker.
# Parameters:
# - save_path: Directory to save evaluation results.
# - watermark_model: Instance of the watermark model to evaluate.
# - noise_models: Instance containing attack configurations (your custom attacker).
# - dataloader: DataLoader providing data.
wl.evaluate(
"save_results/PGWs", # Path to save results
stegastamp, # Watermark model instance
default_attackers, # Attack model instance (your custom attacker)
dataloader_400_100 # DataLoader instance
)
# --- Visualize Results (Optional) ---
# Use watermarklab's plotting tool to generate an attack effectiveness ranking plot.
# Parameters:
# - result_paths: List of paths containing evaluation results.
# - save_path: Directory to save the generated plots.
wl.draw.plot_attack_effectiveness_ranking(
[f"save_results/PGWs/{stegastamp.modelname}"], # Path to evaluation results
"save_draw" # Path to save plots
)The three configuration objects
BaseTestAttackModel
Your attack. attack(stego_img, cover_img, factor) receives uint8 image arrays and the current factor, and returns the attacked images.
AttackerWithFactors
Binds an attacker instance to a display attackername, the list of factors to sweep, and a LaTeX factorsymbol used in plots.
AttackersWithFactorsModel
The collection handed to wl.evaluate(). Pass default_attackers=[your_config] to benchmark against only your attack, or omit it to use the built-in 40+ sweep.
factor_inversely_related=True when a larger factor means a weaker attack — the classic example is JPEG or VAE compression quality, where a higher quality value means less distortion. This flag is what keeps the ranking plots oriented correctly.Jump to the full API reference →
3. Benchmarking PGWs
The built-in post-generation family, each run against the default sweep of 40+ attacks with calibrated intensity factors:
import watermarklab as wl
from watermarklab.watermarks.PGWs import VINE
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_IMAGES
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
from watermarklab.watermarks.PGWs import rivaGAN, dctDwtSvd, TrustMark, StegaStamp, InvisMark
import warnings
warnings.filterwarnings('ignore')
default_attackers = AttackersWithFactorsModel()
mscoco2017_256_32 = MS_COCO_2017_VAL_IMAGES(im_size=256, bit_len=32)
dataloader_256_32 = DataLoader(mscoco2017_256_32, batch_size=32)
rivagan = rivaGAN(bits_len=32, img_size=256)
wl.evaluate("save_results/PGWs", rivagan, default_attackers, dataloader_256_32, noise_save=True)
dctdwtsvd = dctDwtSvd(bits_len=32, img_size=256)
wl.evaluate("save_results/PGWs", dctdwtsvd, default_attackers, dataloader_256_32, noise_save=True)
mscoco2017_256_100 = MS_COCO_2017_VAL_IMAGES(im_size=256, bit_len=100)
dataloader_256_100 = DataLoader(mscoco2017_256_100, batch_size=32)
invismark = InvisMark(bits_len=100, img_size=256)
wl.evaluate("save_results/PGWs", invismark, default_attackers, dataloader_256_100, noise_save=True)
trustmark = TrustMark(bits_len=100, img_size=256)
wl.evaluate("save_results/PGWs", trustmark, default_attackers, dataloader_256_100, noise_save=True)
mscoco2017_400_100 = MS_COCO_2017_VAL_IMAGES(im_size=400, bit_len=100)
dataloader_400_100 = DataLoader(mscoco2017_400_100, batch_size=16)
stegastamp = StegaStamp(bits_len=100, img_size=400)
wl.evaluate("save_results/PGWs", stegastamp, default_attackers, dataloader_400_100, noise_save=True)
mscoco2017_256_100 = MS_COCO_2017_VAL_IMAGES(im_size=256, bit_len=100)
dataloader_256_100 = DataLoader(mscoco2017_256_100, batch_size=32)
vine = VINE(bits_len=100, img_size=256)
wl.evaluate("save_results/PGWs", vine, default_attackers, dataloader_256_100, noise_save=True)4. Benchmarking IGWs
The in-generation family. These models embed during diffusion sampling, so the dataloader yields prompts instead of images and wl.evaluate() routes the run to the IGW pipeline automatically:
import watermarklab as wl
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_PROMPTS
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
from watermarklab.watermarks.IGWs import StableSignature, GaussianShading, TreeRing
import warnings
warnings.filterwarnings('ignore')
default_attackers = AttackersWithFactorsModel()
gaussianshading = GaussianShading(local_files_only=True)
mscoco_256 = MS_COCO_2017_VAL_PROMPTS(bit_len=256)
wl.evaluate("save_results/IGWs/", gaussianshading, default_attackers, DataLoader(mscoco_256, batch_size=128), noise_save=True)
treering = TreeRing(local_files_only=True)
mscoco_1 = MS_COCO_2017_VAL_PROMPTS(bit_len=1)
wl.evaluate("save_results/IGWs/", treering, default_attackers, DataLoader(mscoco_1, batch_size=32), noise_save=True)
stablesignature = StableSignature(local_files_only=True)
mscoco_48 = MS_COCO_2017_VAL_PROMPTS(bit_len=48)
wl.evaluate("save_results/IGWs/", stablesignature, default_attackers, DataLoader(mscoco_48, batch_size=32), need_cover=True, noise_save=True)Introduction
WatermarkLab is a framework for systematic benchmarking and development of blind robust image watermarking. It supports Post-Generation Watermarking (PGW) and In-Generation Watermarking (IGW), zero-bit and multi-bit payloads, and robust reversible methods that must also recover the original cover losslessly — all behind one unified evaluation pipeline.
Key features
- Unified evaluation pipeline for both PGW and IGW models
- Extensive collection of image attacks for robustness testing
- Comprehensive set of evaluation metrics
- Modular design for easy extension
- Structured result reporting with visualizations
Installation
Install WatermarkLab from PyPI:
pip install watermarklabDownload resources
Pre-trained weights and the base diffusion models used by the IGW benchmarks are hosted on Hugging Face:
huggingface-cli download chenoly/watermarklab
huggingface-cli download stabilityai/stable-diffusion-2-1-base
huggingface-cli download stabilityai/stable-diffusion-2-1Requirements
Python ≥ 3.9. The package pulls in a fairly heavy scientific and generative stack:
core
numpy, pillow, opencv-python, PyWavelets, scikit-learn, psutil, py-cpuinfo, colorama, pyfiglet, pycryptodome
metrics
clean-fid, lpips, matplotlib, seaborn
models
torch, onnxruntime-gpu, diffusers, transformers, accelerate, peft, compressai, kornia, nvidia-ml-py
cuda (fid_device="cuda"), and several IGW models run diffusion sampling. Pass fid_device="cpu" only for small smoke tests.Core Concepts
Watermark model types
PGW — Post-Generation Watermarking
The watermark is embedded into a pre-existing image after it has been generated. The evaluation dataloader therefore yields images plus the secret bit sequence.
IGW — In-Generation Watermarking
The watermark is embedded during the image generation process itself, for example while sampling a diffusion model. The dataloader yields text prompts instead of images.
Evaluation pipeline
The library provides a standardized evaluation process consisting of:
- Embedding the watermark into cover images or prompts
- Applying various attacks (noise, compression, geometric transformations)
- Extracting the watermark from the attacked images
- Computing evaluation metrics
- Generating comprehensive result reports
wl.evaluate(save_path, ...) writes one structured JSON report per model under save_path/<modelname>/, with timing, visual-quality scores, per-attack robustness and Base64-encoded sample images. Those JSON files are the input to every plotting function in wl.draw.How to visualize results
Every plotting helper reads the saved result JSON files and writes figures to a directory:
import watermarklab as wl
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
results = ['saved_all_json/result_dctDwtSvd.json',
'saved_all_json/result_rivaGAN.json',
'saved_all_json/result_TrustMark-Q.json',
'saved_all_json/result_InvisMark.json',
'saved_all_json/result_StegaStamp.json',
'saved_all_json/result_VINE-R.json',
'saved_all_json/result_GaussianShading.json',
'saved_all_json/result_StableSignature.json',
'saved_all_json/result_TreeRing-Ring.json']
default_attackers = AttackersWithFactorsModel()
wl.draw.plot_model_robustness_under_single_attack(results, "draw_ALL/MR_SA")
wl.draw.plot_model_robustness_under_all_attack(results, "draw_ALL/MR_AA")
wl.draw.plot_model_robustness_scores_under_all_attacks(results, "draw_ALL/MRS_AA")
wl.draw.plot_model_robustness_ranking_under_single_attack(results, "draw_ALL/MRK_SA")
wl.draw.test_compute_overall_robustness_scores(results)
wl.draw.plot_model_robustness_ranking_by_attacker_group(results, "draw_ALL/MRK_GA", default_attackers.attacker_groups)
wl.draw.plot_model_overall_robustness_ranking(results, "draw_ALL/MRK_MO")
wl.draw.plot_all_attack_ranking(results, "draw_ALL/ARK")
wl.draw.plot_attack_effectiveness_at_tpr_levels(results, "draw_ALL/ARK_TPR", tpr_levels=[0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1])
wl.draw.plot_visual_quality(results, "draw_ALL/VQ", show_dataset_name=False)
wl.draw.plot_stego_visualization(results, "draw_ALL/MVC")
wl.draw.plot_attack_visualization(results, "draw_ALL/MVC")Back to the quick start examples ↑
API Reference Overview
WatermarkLab provides a comprehensive set of modules and functions for the development, evaluation and comparison of robust image watermarking techniques. This reference is organised into the framework's seven core modules — watermarks, attackers, metrics, tools, datasets, laboratories and draw — with the base interfaces you extend listed alongside the evaluation platform.
watermarks
Ten reference methods for comparative studies — seven post-generation and three in-generation.
2 areas→attackers
TestAttacker for benchmarking robustness, and differentiable DiffAttacker for adversarial training and the development of new methods. The default AttackersWithFactorsModel() ships 44 attack configurations; the standard benchmark evaluates 34 of them.
metrics
Robustness metrics (BER, EA, TPR@x%FPR) and imperceptibility metrics (PSNR, SSIM, LPIPS, FID), plus a base class for custom metrics.
1 area→tools
Auxiliary utilities such as compression coding and reversible data hiding, supporting the development of robust reversible watermarking.
1 area→datasets
Mainstream benchmarks — MS-COCO 2017 images and captions, Kodak24 and USC-SIPI — with the batched loader that pairs data with watermark bits.
2 areas→laboratories
The evaluation platform for PGW and IGW methods, together with the base interfaces you implement to plug in your own model, attacker or metric.
2 areas→draw
Visualization and interactive analysis: robustness curves, model and attacker rankings, visual-quality plots and stego / attack comparisons.
1 area→steganography
iSteganoGAN, an improved SteganoGAN model that uses L-BFGS for more accurate and stable watermark extraction. It ships alongside the seven core modules and subclasses BaseWatermarkModel.
watermarks
Ten reference methods for comparative studies — seven post-generation and three in-generation.
Post-generation (PGW)
watermarklab.watermarks.PGWs.dctDwt
watermarklab/watermarks/PGWs/dctDwt.pyclassdctDwt(BaseWatermarkModel)#
The DWT-DCT watermarking algorithm.
Reference:
Example
from watermarklab.watermarks.PGWs import dctDwt
model = dctDwt(bits_len=32, img_size=256, modelname='dctDwt', scales=[0, 36, 36])Constructor(self, bits_len: int, img_size: int, modelname: str = 'dctDwt', scales = [0, 36, 36])#
Initialize the model.
Parameters
bits_lenintLength of the watermark.
img_sizeintExpected image size (not used in this method).
modelnamestrName of the model.
scalesList[float]Embedding strengths for Y, U, V channels.
embed(self, cover_list: List[Any], secrets: List[List]) -> Result#
Embed watermarks into a batch of cover images.
Parameters
cover_listList[np.ndarray]List of RGB images.
secretsList[List]List of binary watermarks.
Returns
ResultContains the list of watermarked RGB images.
Example
# method of dctDwt
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract watermarks from a batch of watermarked images.
Parameters
stego_listList[np.ndarray]List of watermarked RGB images.
Returns
ResultContains the list of extracted binary watermarks.
Example
# method of dctDwt
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover the original image from the watermarked image. Not supported in this method.
Parameters
stego_listList[np.ndarray]Watermarked images.
Returns
ResultNotImplemented.
Example
# method of dctDwt
model.recover(stego_list=stego_images)watermarklab.watermarks.PGWs.dctDwtSvd
watermarklab/watermarks/PGWs/dctDwtSvd.pyclassdctDwtSvd(BaseWatermarkModel)#
The DWT-DCT-SVD watermarking algorithm.
Reference:
Example
from watermarklab.watermarks.PGWs import dctDwtSvd
model = dctDwtSvd(bits_len=32, img_size=256, modelname='dctDwtSvd', scales=[0, 36, 36])Constructor(self, bits_len: int, img_size: int, modelname: str = 'dctDwtSvd', scales = [0, 36, 36])#
Initialize the model.
Parameters
bits_lenintLength of the watermark.
img_sizeintExpected image size (not used in this method).
modelnamestrName of the model.
scalesList[float]Embedding strengths for Y, U, V channels.
embed(self, cover_list: List[Any], secrets: List[List]) -> Result#
Embed watermarks into a batch of cover images.
Parameters
cover_listList[np.ndarray]List of RGB images.
secretsList[List]List of binary watermarks (each length = bits_len).
Returns
ResultContains the list of watermarked RGB images.
Example
# method of dctDwtSvd
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract watermarks from a batch of watermarked images.
Parameters
stego_listList[np.ndarray]List of watermarked RGB images.
Returns
ResultContains the list of extracted binary watermarks.
Example
# method of dctDwtSvd
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover the original image from the watermarked image. Not supported in this method.
Parameters
stego_listList[np.ndarray]Watermarked images.
Returns
ResultNotImplemented.
Example
# method of dctDwtSvd
model.recover(stego_list=stego_images)watermarklab.watermarks.PGWs.invismark
watermarklab/watermarks/PGWs/invismark.pyclassInvisMark(BaseWatermarkModel)#
The InvisMark watermark.
Reference:
Example
from watermarklab.watermarks.PGWs import InvisMark
model = InvisMark(img_size=256, bits_len=100, modelname='InvisMark', device='cuda', local_files_only=False)Constructor(self, img_size: int = 256, bits_len: int = 100, modelname: str = 'InvisMark', device: str = 'cuda', local_files_only = False)#
Initialize the InvisMark wrapper with ONNX models.
Parameters
img_sizeintExpected image size (assumed square, default 256).
bits_lenintLength of the watermark (must be 100).
modelnamestrModel identifier (default 'InvisMark').
devicestrSpecifies the device to use ('cuda' or 'cpu').
embed(self, cover_list: List[ndarray], secrets: List[List[int]]) -> Result#
Embed 100-bit watermarks into a batch of cover images.
Parameters
cover_listList[ndarray]A list of RGB images with shape [H, W, 3], pixel values in [0, 255].
secretsList[List[int]]A list of 100-bit binary watermarks.
Returns
ResultA Result object containing the list of watermarked images.
Example
# method of InvisMark
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract 100-bit watermarks from a batch of watermarked images.
Parameters
stego_listList[ndarray]A list of watermarked RGB images with shape [H, W, 3], pixel values in [0, 255].
Returns
ResultA Result object containing the list of extracted binary watermarks.
Example
# method of InvisMark
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover the original image from the watermarked image. This functionality is not supported by the InvisMark model.
Parameters
stego_listList[ndarray]A list of watermarked images.
Returns
ResultNotImplemented.
Example
# method of InvisMark
model.recover(stego_list=stego_images)watermarklab.watermarks.PGWs.rivaGAN
watermarklab/watermarks/PGWs/rivaGAN.pyclassrivaGAN(BaseWatermarkModel)#
Wrapper for rivaGAN ONNX models. Implements embedding and extraction of 32-bit watermarks. Does not support image recovery.
Reference:
Example
from watermarklab.watermarks.PGWs import rivaGAN
model = rivaGAN(bits_len=32, img_size=256)
embedded = model.embed(cover_images, secrets) # -> watermarked images + bits
extracted = model.extract(embedded.images) # -> recovered bits
# Benchmark it against the full attack sweep:
import watermarklab as wl
wl.evaluate("save_results/PGWs", model, attackers, dataloader)Constructor(self, img_size: int = 256, bits_len: int = 32, modelname: str = 'rivaGAN', device: str = 'cuda', local_files_only: bool = False)#
Initialize the rivaGAN model.
Parameters
img_sizeintInput image size (assumed square, default 256).
bits_lenintLength of watermark (must be 32).
modelnamestrModel identifier.
devicestrDevice to run on ('cpu' or 'cuda').
embed(self, cover_list: List[ndarray], secrets: List[List[int]]) -> Result#
Embed 32-bit watermarks into cover images.
Parameters
cover_listList[ndarray]List of RGB images [H, W, 3], uint8 [0, 255].
secretsList[List[int]]List of 32-bit binary watermarks.
Returns
ResultWatermarked images and embedded bits.
Example
# method of rivaGAN
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract 32-bit watermarks from stego images.
Parameters
stego_listList[ndarray]Watermarked images [H, W, 3], uint8.
Returns
ResultExtracted binary watermarks.
Example
# method of rivaGAN
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover original image from watermarked image. Not supported by rivaGAN.
Parameters
stego_listList[ndarray]Watermarked images.
Returns
ResultNotImplemented.
Raises
NotImplementedErrorRecovery not supported.
Example
# method of rivaGAN
model.recover(stego_list=stego_images)watermarklab.watermarks.PGWs.stegastamp
watermarklab/watermarks/PGWs/stegastamp.pyclassStegaStamp(BaseWatermarkModel)#
Wrapper for the StegaStamp ONNX model. Implements embed and extract interfaces for 100-bit watermarking. Does not support image recovery.
Reference:
Example
from watermarklab.watermarks.PGWs import StegaStamp
model = StegaStamp(img_size=400, bits_len=100, modelname='StegaStamp', device='cuda', local_files_only=False)Constructor(self, img_size: int = 400, bits_len: int = 100, modelname: str = 'StegaStamp', device: str = 'cuda', local_files_only: bool = False)#
Initialize the StegaStamp model.
Parameters
img_sizeintInput image size (assumed square, default 400).
bits_lenintLength of the watermark (must be 100).
modelnamestrModel identifier.
devicestrDevice to run on ('cpu' or 'cuda').
embed(self, cover_list: List[ndarray], secrets: List[List[int]]) -> Result#
Embed 100-bit watermarks into a batch of cover images.
Parameters
cover_listList[ndarray]List of RGB images [H, W, 3], uint8 [0, 255].
secretsList[List[int]]List of 100-bit binary watermarks.
Returns
ResultWatermarked images and embedded bits.
Example
# method of StegaStamp
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract 100-bit watermarks from a batch of watermarked images.
Parameters
stego_listList[ndarray]List of watermarked images [H, W, 3], uint8.
Returns
ResultExtracted binary watermarks.
Example
# method of StegaStamp
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover original image from watermarked image. Not supported by StegaStamp.
Parameters
stego_listList[ndarray]Watermarked images.
Returns
ResultNotImplemented.
Raises
NotImplementedErrorRecovery not supported.
Example
# method of StegaStamp
model.recover(stego_list=stego_images)watermarklab.watermarks.PGWs.trustmark
watermarklab/watermarks/PGWs/trustmark.pyclassTrustMark(BaseWatermarkModel)#
Wrapper for TrustMark ONNX models. Supports embedding, extraction, and removal of watermarks using separate ONNX models. Supports multiple model variants: C, Q, B, P.
Reference:
Example
from watermarklab.watermarks.PGWs import TrustMark
model = TrustMark(img_size=256, bits_len=100, model_type='Q', device='cuda', local_files_only=False)Constructor(self, img_size: int = 256, bits_len: int = 100, model_type: str = 'Q', device: str = 'cuda', local_files_only: bool = False)#
Initialize the TrustMark model.
Parameters
img_sizeintInput image size (ignored; model handles arbitrary resolution).
bits_lenintLength of watermark (must be 100).
model_typestrModel variant ('C', 'Q', 'B', 'P').
devicestrDevice to run on ('cpu' or 'cuda').
embed(self, cover_list: List[ndarray], secrets: List[List[int]]) -> Result#
Embed 100-bit watermarks into cover images.
Parameters
cover_listList[ndarray]List of RGB images [H, W, 3], uint8 [0, 255].
secretsList[List[int]]List of 100-bit binary watermarks.
Returns
ResultWatermarked images and embedded bits.
Example
# method of TrustMark
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract 100-bit watermarks from stego images.
Parameters
stego_listList[ndarray]Watermarked images [H, W, 3], uint8.
Returns
ResultExtracted binary watermarks.
Example
# method of TrustMark
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover original images from watermarked images.
Parameters
stego_listList[ndarray]Watermarked images [H, W, 3], uint8.
Returns
ResultRecovered clean images.
Example
# method of TrustMark
model.recover(stego_list=stego_images)watermarklab.watermarks.PGWs.vine
watermarklab/watermarks/PGWs/vine.pyclassVINE(BaseWatermarkModel)#
Wrapper for VINE (R/B) PyTorch models. Supports embedding and extraction of watermarks using separate PyTorch models. Supports two model variants: R (Robust), B (Base).
Reference:
Example
from watermarklab.watermarks.PGWs import VINE
model = VINE(img_size=256, bits_len=100, model_type='R', device='cuda', local_files_only=False)Constructor(self, img_size: int = 256, bits_len: int = 100, model_type: str = 'R', device: str = 'cuda', local_files_only: bool = False)#
Initialize the VINE model.
Parameters
img_sizeintInput image size for the encoder (256 for R/B).
bits_lenintLength of watermark (must be 100 for R/B).
model_typestrModel variant ('R' or 'B').
devicestrDevice to run on ('cpu' or 'cuda').
local_files_onlyboolIf True, avoid downloading the model. Requires model to be present locally.
embed(self, cover_list: List[ndarray], secrets: List[List[int]]) -> Result#
Embed 100-bit watermarks into cover images one by one (to avoid batch size issues).
Parameters
cover_listList[ndarray]List of RGB images [H, W, 3], uint8 [0, 255] or float.
secretsList[List[int]]List of 100-bit binary watermarks.
Returns
ResultWatermarked images and embedded bits.
Example
# method of VINE
model.embed(cover_list=cover_images, secrets=secrets)extract(self, stego_list: List[ndarray]) -> Result#
Extract 100-bit watermarks from stego images in batch (assumes images are 256x256).
Parameters
stego_listList[ndarray]Watermarked images [H, W, 3], uint8 [0, 255]. Expected to be 256x256.
Returns
ResultExtracted binary watermarks.
Example
# method of VINE
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover original images from watermarked images. Note: VINE-R/B models as provided do not include a recovery/remover component. This method is not implemented.
Example
# method of VINE
model.recover(stego_list=stego_images)In-generation (IGW)
watermarklab.watermarks.IGWs.gaussianshading
watermarklab/watermarks/IGWs/gaussianshading.pyclassGaussianShading(BaseWatermarkModel)#
Implements the Gaussian Shading watermarking method from the CVPR 2024 paper. This method embeds watermarks in the initial noise vector of a stable diffusion model without performance loss or additional training. Supports two modes:
- Detection: for copyright verification
- Traceability: for user identification
Reference:
Example
from watermarklab.watermarks.IGWs import GaussianShading
model = GaussianShading(local_files_only=True)
import watermarklab as wl
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_PROMPTS
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
prompts = MS_COCO_2017_VAL_PROMPTS(bit_len=256)
wl.evaluate(
"save_results/IGWs/",
model,
AttackersWithFactorsModel(),
DataLoader(prompts, batch_size=128),
noise_save=True,
)Constructor(self, image_size: int = 512, bit_length: int = 256, f_h: int = 8, f_w: int = 8, f_c: int = 1, l: int = 1, model_name: str = 'GaussianShading', model_id: str = 'stabilityai/stable-diffusion-2-1-base', embed_mode: str = 'traceability', threshold: float = 30.0, local_files_only = LOAD_FROM_LOCAL)#
Initialize the Gaussian Shading watermarking model with CPU offloading.
Parameters
image_sizeintSize of the input/output images (default: 512).
bit_lengthintLength of the watermark bit sequence (default: 256).
f_hintHeight ratio for embedding (default: 8).
f_wintWidth ratio for embedding (default: 8).
f_cintchannels ratio for embedding (default: 1).
lintbit per dimension (default: 1).
model_namestrName of the model (default: "GaussianShading").
embed_modestrEmbedding mode, either 'detection' or 'traceability' (default: 'detection').
model_idstrPath to the pre-trained diffusion model (default: stabilityai/stable-diffusion-2-1-base).
Diffusion_forward(self, prompts: List[str], latents: Optional[List[torch.Tensor]] = None, num_steps: int = 50, guidance_scale: float = 7.5) -> Tuple[List[np.ndarray], torch.Tensor]#
Generate a batch of images using the DDIM forward sampling process.
Parameters
promptsList[str]A list of text prompts for image generation.
latentsOptional[List[torch.Tensor]]A list of latent tensors, each of shape [1, 4, H//8, W//8]. If None, random latents are generated for each prompt.
num_stepsintNumber of denoising steps. Default is 50.
guidance_scalefloatScale for classifier-free guidance. Default is 7.5.
Returns
Tuple[List[np.ndarray], torch.Tensor]:
- List of generated images as float32 numpy arrays [H, W, 3] in [0, 1] range.
- The stacked initial latent tensor used for generation, shape [B, 4, H//8, W//8].
Example
# method of GaussianShading
model.Diffusion_forward(prompts=prompts, latents=None, num_steps=50, guidance_scale=7.5)Diffusion_inversion(self, image_tensor: List[torch.Tensor], num_steps: int = 50, guidance_scale: float = 7.5) -> torch.Tensor#
Perform DDIM inversion to recover the initial noise vector from an image.
Parameters
image_tensorList[torch.Tensor]List of image tensors, each of shape [1, 3, H, W] in [0, 1] range.
num_stepsintNumber of inversion steps.
guidance_scalefloatGuidance scale used during inversion.
Returns
torch.TensorThe inverted initial noise latent of shape [B, 4, H//8, W//8].
Example
# method of GaussianShading
model.Diffusion_inversion(image_tensor=image_tensor, num_steps=50, guidance_scale=7.5)embed(self, prompts: List[str], secrets: List[List[int]]) -> Result#
Embed watermarks into images using the Gaussian Shading method.
Parameters
promptsList[str]Text prompts for image generation.
secretsList[List[int]]Watermark bit sequences for traceability mode.
Returns
ResultObject containing the watermarked images and embedded bits.
Example
# method of GaussianShading
model.embed(prompts=prompts, secrets=secrets)extract(self, protected_images: List[ndarray]) -> Result#
Extract watermarks from watermarked images.
Parameters
protected_imagesList[ndarray]Watermarked images to analyze.
Returns
ResultObject containing the extracted watermark bits.
Example
# method of GaussianShading
model.extract(protected_images=protected_images)recover(self, watermarked_images: List[ndarray]) -> Result#
Recover the original image from the watermarked image. This method is not supported by Gaussian Shading.
Parameters
watermarked_imagesList[ndarray]Watermarked images.
Returns
ResultNotImplemented.
Example
# method of GaussianShading
model.recover(watermarked_images=watermarked_images)watermarklab.watermarks.IGWs.stablesignature
watermarklab/watermarks/IGWs/stablesignature.pyclassStableSignature(BaseWatermarkModel)#
StableSignature watermarking method for AIGC. Uses a fixed 48-bit watermark embedded via modified VAE decoding. Extracts watermark using a trained ONNX message extractor.
Reference:
Example
from watermarklab.watermarks.IGWs import StableSignature
model = StableSignature(local_files_only=True)
import watermarklab as wl
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_PROMPTS
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
prompts = MS_COCO_2017_VAL_PROMPTS(bit_len=256)
wl.evaluate(
"save_results/IGWs/",
model,
AttackersWithFactorsModel(),
DataLoader(prompts, batch_size=128),
noise_save=True,
)Constructor(self, img_size: int = 512, bits_len: int = 48, model_id: str = 'stabilityai/stable-diffusion-2-1-base', modelname: str = 'StableSignature', local_files_only = False)#
Initialize the StableSignature model.
Parameters
img_sizeintImage size (default 512).
bits_lenintLength of watermark (must be 48).
model_idstrHugging Face ID for the Stable Diffusion base model.
modelnamestrModel identifier.
embed(self, prompts: List[str], secrets: List[List[int]] = None) -> Result#
Generate watermarked images from text prompts (batched).
Parameters
promptsList[str]List of text prompts.
secretsList[List[int]]Ignored. Uses fixed watermark.
Returns
ResultWatermarked images, clean images, and embedded bits.
Example
# method of StableSignature
model.embed(prompts=prompts, secrets=None)extract(self, stego_list: List[ndarray]) -> Result#
Extract 48-bit watermark from watermarked images (batched).
Parameters
stego_listList[ndarray]List of watermarked images [H, W, 3], uint8.
Returns
ResultExtracted binary watermarks.
Example
# method of StableSignature
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover original image from watermarked image. Not supported by StableSignature.
Parameters
stego_listList[ndarray]Watermarked images.
Returns
ResultNotImplemented.
Raises
NotImplementedErrorRecovery not supported.
Example
# method of StableSignature
model.recover(stego_list=stego_images)watermarklab.watermarks.IGWs.treering
watermarklab/watermarks/IGWs/treering.pyclassTreeRing(BaseWatermarkModel)#
A wrapper class for Tree-Ring Watermarking, a robust and invisible watermarking technique for diffusion models. The watermark is embedded in the Fourier space of the initial noise vector used in the DDIM sampling process. Detection is performed via DDIM inversion to recover the initial noise and verify the presence of the predefined watermark pattern.
Reference:
Example
from watermarklab.watermarks.IGWs import TreeRing
model = TreeRing(local_files_only=True)
import watermarklab as wl
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_PROMPTS
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
prompts = MS_COCO_2017_VAL_PROMPTS(bit_len=256)
wl.evaluate(
"save_results/IGWs/",
model,
AttackersWithFactorsModel(),
DataLoader(prompts, batch_size=128),
noise_save=True,
)Constructor(self, img_size: int = 512, bits_len: int = 1, modelname: str = 'TreeRing', model_id: str = 'stabilityai/stable-diffusion-2-1-base', w_pattern: str = 'ring', w_radius: int = 10, w_channel: int = 3, local_files_only = False)#
Initialize the TreeRing watermarking system.
Parameters
img_sizeintSize of the generated image (must be divisible by 8). Default is 512.
bits_lenintLength of the watermark bits (not used in this method). Ignored.
modelnamestrName of the watermark model. Default is "TreeRing".
model_idstrHugging Face model ID for the diffusion model. Default is "stabilityai/stable-diffusion-2-1-base".
w_patternstrWatermark pattern type. Supported: 'ring', 'rand', 'zeros'. Default is "ring".
w_radiusintRadius of the circular watermark mask in the frequency domain. Default is 10.
w_channelintChannel index to embed the watermark. Use -1 for all channels, or 0-3 for a specific channel. Default is 3.
Diffusion_inversion(self, image_tensor: List[torch.Tensor], num_steps: int = 50, guidance_scale: float = 7.5) -> torch.Tensor#
Perform DDIM inversion to recover the initial noise vector from an image.
Parameters
image_tensorList[torch.Tensor]List of image tensors, each of shape [1, 3, H, W] in [0, 1] range.
num_stepsintNumber of inversion steps.
guidance_scalefloatGuidance scale used during inversion.
Returns
torch.TensorThe inverted initial noise latent of shape [B, 4, H//8, W//8].
Example
# method of TreeRing
model.Diffusion_inversion(image_tensor=image_tensor, num_steps=50, guidance_scale=7.5)embed(self, prompts: List[str], secrets: List[List[int]] = None) -> Result#
Generate watermarked images for a list of prompts.
Parameters
promptsList[str]A list of text prompts for image generation.
secretsList[List[int]]Not used. Tree-Ring does not use bit-based secrets.
Returns
ResultAn object containing:
- stego_img: List of watermarked images.
- clean_img: List of corresponding clean (unwatermarked) images.
Example
# method of TreeRing
model.embed(prompts=prompts, secrets=None)extract(self, stego_list: List[np.ndarray]) -> Result#
Extract the watermark from a list of watermarked images.
Detection is performed by: 1. Inverting the image to recover the initial latent. 2. Comparing the Fourier transform of the recovered latent with the stored gt_patch.
Parameters
stego_listList[np.ndarray]List of watermarked RGB images with shape [H, W, 3].
Returns
ResultAn object containing detected_values, a list of L1 distances. Lower values indicate a stronger presence of the watermark.
Example
# method of TreeRing
model.extract(stego_list=stego_images)recover(self, stego_list: List[np.ndarray]) -> Result#
Recover the original image from a watermarked image.
This method is not applicable for Tree-Ring watermarking, as it is a generative method without a reversible distortion process.
Parameters
stego_listList[np.ndarray]List of watermarked images.
Returns
ResultNotImplemented.
Example
# method of TreeRing
model.recover(stego_list=stego_images)attackers
TestAttacker for benchmarking robustness, and differentiable DiffAttacker for adversarial training and the development of new methods. The default AttackersWithFactorsModel() ships 44 attack configurations; the standard benchmark evaluates 34 of them.
Attacker collection
watermarklab.attackers.attackerloader
watermarklab/attackers/attackerloader.pyclassDistortionLoader(nn.Module)#
A module that applies a sequence of noise layers to an image, simulating distortions.
Parameters
noise_listList[BaseDiffNoiseModel]A list of noise models that will be applied sequentially.
max_stepint, optional (default=100)The maximum training step, used for scheduling the number of applied noise layers.
k_minint, optional (default=1)The minimum number of noise layers to apply.
k_maxint, optional (default=2)The maximum number of noise layers to apply. If larger than len(noise_list), it will be clipped.
Methods
stair_k()Determines the number of noise layers (k) to apply based on a step-wise (staircase) schedule.
parabolic_k()Determines k using a parabolic function, allowing a smooth increase over time.
forward()Applies k randomly selected noise layers sequentially to the marked image.
Example
from watermarklab.attackers.attackerloader import DistortionLoader
loader = DistortionLoader(noise_list=noise_list, k_mode='stair_k', k_min=1, k_max=2, max_step=1)Constructor(self, noise_list: List[BaseDiffAttackModel], k_mode: str = 'stair_k', k_min: int = 1, k_max: int = 2, max_step = 1)#
Initialize the distortion loader.
Parameters
noise_listList[BaseDiffAttackModel]Noise models applied sequentially during training.
k_modestrSchedule that selects the number of applied noise layers during training, "stair_k" or "parabolic_k". Defaults to "stair_k".
k_minintMinimum number of noise layers applied. Defaults to 1.
k_maxintMaximum number of noise layers applied; clipped to `len(noise_list)`. Defaults to 2.
max_stepintMaximum training step used by the schedule. Defaults to 1.
stair_k(self, now_step: int) -> int#
Determines the number of noise layers (k) to apply using a staircase function. The number of noise layers increases in discrete steps as training progresses.
Parameters
now_stepintThe current training step.
Returns
kintThe number of noise layers to apply.
Example
# method of DistortionLoader
loader.stair_k(now_step=1)parabolic_k(self, now_step: int, gamma: float = 1.3) -> int#
Determines the number of noise layers (k) using a parabolic growth function. The number of layers smoothly increases over time.
Parameters
now_stepintThe current training step.
gammafloat, optional (default=1.3)A parameter controlling the curvature of the growth function.
Returns
kintThe number of noise layers to apply.
Example
# method of DistortionLoader
loader.parabolic_k(now_step=1, gamma=1.3)forward(self, marked_img: torch.Tensor, cover_img: torch.Tensor, now_step: int = 0) -> torch.Tensor#
Applies randomly selected noise layers to the marked image.
Parameters
marked_imgtorch.TensorThe input image to which noise is applied.
cover_imgtorch.TensorThe original reference image (may be used by noise models).
now_stepint, optional (default=0)The current training step, used to determine k.
Returns
noised_imgtorch.TensorThe distorted image after applying k noise layers.
Example
# method of DistortionLoader
loader.forward(marked_img=marked_img, cover_img=cover_image, now_step=0)classAttackersWithFactorsModel(list)#
A class that extends Python's built-in list to hold attackers with their factors. This class behaves exactly like a regular list but provides a convenient way to initialize with a comprehensive set of default image attackers for adversarial attacks.
The list is lazily initialized to prevent creation when the module is imported, only creating the attackers when actually needed. This improves import performance and memory usage.
The default attackers cover various categories of image transformations and attacks:
- Diffusion-based attacks for regenerating images
- Neural compression attacks using VAE models
- Noise injection attacks (salt & pepper, Gaussian, Poisson)
- Blur attacks (Gaussian, median, mean, unsharp masking)
- Image compression attacks (JPEG, JPEG2000, WebP)
- Geometric transformations (resize, rotate, crop, etc.)
- Color transformations (contrast, saturation, hue shifts, etc.)
Example
from watermarklab.attackers.attackerloader import (
AttackersWithFactorsModel, AttackerWithFactors,
)
from watermarklab.attackers.testattackers.blur import GaussianBlur
# All built-in attackers, at every calibrated strength:
attackers = AttackersWithFactorsModel()
# ...or only the ones you care about:
attackers = AttackersWithFactorsModel(
default_attackers=[
AttackerWithFactors(
attacker=GaussianBlur(),
attackername="GaussianBlur",
factors=[0.5, 1.0, 2.0, 4.0],
factorsymbol=r"$\sigma$",
)
]
)Constructor(self, default_attackers: List[AttackerWithFactors] = None, attacker_groups: Dict = None)#
Initialize the AttackersWithFactorsModel with either provided attackers or defaults.
Parameters
default_attackersList[AttackerWithFactors]A list of pre-defined attackers. If provided, these attackers will be used instead of the default comprehensive set. If None, a default set of 40+ different attackers across multiple categories will be automatically created and populated.
Test attackers
watermarklab.attackers.testattackers.advattack
watermarklab/attackers/testattackers/advattack.pyclassClipEmbeddingAttack(BaseTestAttackModel)#
An adversarial attack that perturbs stego images to maximally distort their CLIP image embeddings.
This attack uses Projected Gradient Descent (PGD) to generate minimal L∞-bounded perturbations that cause significant deviation in the CLIP embedding space. It represents a strong adaptive adversary with full knowledge of the feature extractor, commonly used to evaluate watermark robustness.
The 'strength' parameter controls the perturbation budget:
- strength = 2 → ε = 2/255
- strength = 4 → ε = 4/255
- strength = 6 → ε = 6/255
- strength = 8 → ε = 8/255
Implementation details:
- Uses CLIP-ViT-B/32 from OpenAI
- Applies 200-step PGD with α = 0.05 × ε
- Automatically converts grayscale images to RGB for processing
- Attack is performed in original resolution; CLIP input is temporarily resized to 224×224
- Output preserves original spatial dimensions and color mode (grayscale or RGB)
Radford, A., Kim, J. W., Hallacy, C., Ramesh, A., Goh, G., Agarwal, S., Sastry, G., Askell, A., Mishkin, P., Clark,
J., et al. Learning transferable visual models from natural language supervision. In International conference on machine learning, pp. 8748–8763. PMLR, 2021.Notes
- Input: List of uint8 images, [H, W], [H, W, 1], or [H, W, 3], range [0, 255]
- Output: List of uint8 images with same shape and color mode as input
- First run downloads ~600MB CLIP model from Hugging Face
Example
from watermarklab.attackers.testattackers.advattack import ClipEmbeddingAttack
attack = ClipEmbeddingAttack(noisename='ClipEmbeddingAttack')Constructor(self, noisename: str = 'ClipEmbeddingAttack')#
Initialize the CLIP embedding attack.
Parameters
noisenamestrName identifier for logging and reporting. Defaults to "ClipEmbeddingAttack".
attack(self, stego_imgs: List[np.ndarray], cover_img: Optional[List[np.ndarray]] = None, strength: float = 2.0) -> List[np.ndarray]#
Perturb stego images with 200-step PGD to distort their CLIP image embeddings.
Parameters
stego_imgsList[np.ndarray]uint8 images, [H, W], [H, W, 1] or [H, W, 3], range [0, 255].
cover_imgList[np.ndarray], optionalCover images; ignored by this attack.
strengthfloatL-inf perturbation budget eps = strength / 255; larger values give a stronger attack. Defaults to 2.0.
Returns
List[np.ndarray]uint8 adversarial images, same shape and color mode as the input.
Raises
ValueErrorIf an image has an unsupported number of dimensions or channels.
Example
# method of ClipEmbeddingAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, strength=2.0)classVAEEmbeddingAttack(BaseTestAttackModel)#
An adversarial attack that perturbs stego images to maximally distort their VAE latent representations.
This attack uses Projected Gradient Descent (PGD) to generate minimal L∞-bounded perturbations that cause significant deviation in the VAE's latent space (mode of the posterior). It simulates an adaptive adversary aware of the generative prior, commonly used in diffusion-based watermarking.
Supported VAEs:
- "stabilityai/sd-vae-ft-mse" (SD 1.x VAE)
- "stabilityai/sdxl-vae" (SDXL VAE)
Podell, D., English, Z., Lacey, K., Blattmann, A., Dockhorn, T., Müller, J., Penna, J., and Rombach, R.
Sdxl: Improving latent diffusion models for high-resolution image synthe sis. arXiv preprint arXiv:2307.01952, 2023.
The 'strength' parameter controls the perturbation budget:
- strength = 2 → ε = 2/255
- strength = 4 → ε = 4/255
- strength = 6 → ε = 6/255
- strength = 8 → ε = 8/255
Implementation details:
- Input images normalized to [-1, 1] before VAE encoding
- Uses 200-step PGD with α = 0.05 × ε and L2 loss
- Attack performed in original resolution
- Output preserves original spatial dimensions and color mode
Notes
- Input: List of uint8 images, [H, W], [H, W, 1], or [H, W, 3], range [0, 255]
- Output: List of uint8 images with same shape and color mode as input
Example
from watermarklab.attackers.testattackers.advattack import VAEEmbeddingAttack
attack = VAEEmbeddingAttack(model_name='stabilityai/sd-vae-ft-mse', noisename='VAEEmbeddingAttack')Constructor(self, model_name: str = 'stabilityai/sd-vae-ft-mse', noisename: str = 'VAEEmbeddingAttack')#
Initialize the VAE embedding attack.
Parameters
model_namestrHugging Face id of the VAE whose latent space is attacked; defaults to "stabilityai/sd-vae-ft-mse" ("stabilityai/sdxl-vae" is also supported).
noisenamestrName identifier for logging and reporting. Defaults to "VAEEmbeddingAttack".
attack(self, stego_imgs: List[np.ndarray], cover_img: Optional[List[np.ndarray]] = None, strength: float = 2.0) -> List[np.ndarray]#
Perturb stego images with 200-step PGD to distort their VAE latent representations.
Parameters
stego_imgsList[np.ndarray]uint8 images, [H, W], [H, W, 1] or [H, W, 3], range [0, 255].
cover_imgList[np.ndarray], optionalCover images; ignored by this attack.
strengthfloatL-inf perturbation budget eps = strength / 255; larger values give a stronger attack. Defaults to 2.0.
Returns
List[np.ndarray]uint8 adversarial images, same shape and color mode as the input.
Raises
ValueErrorIf an image has an unsupported number of dimensions or channels.
Example
# method of VAEEmbeddingAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, strength=2.0)classResNet18EmbeddingAttack(BaseTestAttackModel)#
Adversarial attack that perturbs stego images to maximally distort ResNet-18 feature embeddings.
This attack uses PGD to generate minimal L∞-bounded perturbations that cause large deviations in the feature map of a specified ResNet-18 layer (e.g., "last" for global average pooled features).
Supported layers:
- "layer1", "layer2", "layer3", "layer4": intermediate feature maps
- "last": final global average pooled vector (512-dim)
The 'strength' parameter controls the perturbation budget:
- strength = 2 → ε = 2/255
- strength = 4 → ε = 4/255
- strength = 6 → ε = 6/255
- strength = 8 → ε = 8/255
Implementation details:
- Attack performed in original resolution
- Images temporarily resized to 224×224 for ResNet feature extraction
- Normalized with ImageNet mean/std
- 200-step PGD with α = 0.05 × ε and L2 loss
- Output preserves original spatial dimensions and color mode
Notes
- Input: List of uint8 images, [H, W], [H, W, 1], or [H, W, 3], range [0, 255]
- Output: List of uint8 images with same shape and color mode as input
- First run downloads ResNet-18 (~45MB) from torchvision
Example
from watermarklab.attackers.testattackers.advattack import ResNet18EmbeddingAttack
attack = ResNet18EmbeddingAttack(layer='last', noisename='ResNet18EmbeddingAttack')Constructor(self, layer: str = 'last', noisename: str = 'ResNet18EmbeddingAttack')#
Initialize the ResNet-18 embedding attack.
Parameters
layerstrResNet-18 layer whose features are distorted: "layer1", "layer2", "layer3", "layer4" or "last" (512-d global average pooled vector). Defaults to "last".
noisenamestrName identifier for logging and reporting. Defaults to "ResNet18EmbeddingAttack".
Raises
ValueErrorIf `layer` is not one of the supported names.
attack(self, stego_imgs: List[np.ndarray], cover_img: Optional[List[np.ndarray]] = None, strength: float = 2.0) -> List[np.ndarray]#
Perturb stego images with 200-step PGD to distort their ResNet-18 feature embeddings.
Parameters
stego_imgsList[np.ndarray]uint8 images, [H, W], [H, W, 1] or [H, W, 3], range [0, 255].
cover_imgList[np.ndarray], optionalCover images; ignored by this attack.
strengthfloatL-inf perturbation budget eps = strength / 255; larger values give a stronger attack. Defaults to 2.0.
Returns
List[np.ndarray]uint8 adversarial images, same shape and color mode as the input.
Raises
ValueErrorIf an image has an unsupported number of dimensions or channels.
Example
# method of ResNet18EmbeddingAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, strength=2.0)watermarklab.attackers.testattackers.blur
watermarklab/attackers/testattackers/blur.pyclassGaussianBlur(BaseTestAttackModel)#
A spatial smoothing attack that applies Gaussian blur to reduce image details.
This attack convolves the image with a Gaussian kernel, suppressing high-frequency components where many watermark signals are embedded. It simulates defocus blur or motion blur effects.
The 'sigma' parameter controls the standard deviation of the Gaussian kernel:
- Higher sigma = larger blur radius = stronger smoothing
- Lower sigma = milder blur
This implementation uses torchvision for true batched processing, enabling GPU acceleration and eliminating Python loops for maximum efficiency.
Reference:
Gonzalez, R. C., & Woods, R. E. (2008). Digital Image Processing (3rd ed.). Prentice Hall.Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of blurred images, same shape and dtype
- Uses torchvision for batched, GPU-accelerated Gaussian blur
Example
from watermarklab.attackers.testattackers.blur import GaussianBlur
attack = GaussianBlur(noisename='GaussianBlur')Constructor(self, noisename: str = 'GaussianBlur')#
Initializes the Gaussian blur attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, sigma: float = 1.0) -> List[ndarray]#
Applies Gaussian blur to a batch of stego images using torchvision's batched implementation.
The pipeline:
1. Stack images into a 4D numpy array [B, H, W, 3]
2. Convert to float32 and normalize to [0,1]
3. Convert to CHW tensor and move to device
4. Apply batched Gaussian blur using torchvision
5. Convert back to HWC uint8Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored).
sigmafloatStandard deviation of the Gaussian kernel, controls blur strength.
Returns
List[ndarray]Batch of blurred images, each with the same shape and dtype as input.
Example
# method of GaussianBlur
attack.attack(stego_imgs=stego_imgs, cover_img=None, sigma=1.0)classMedianFilter(BaseTestAttackModel)#
Applies a median filter to the input image to reduce noise and smooth details.
Parameters
noisenamestrName identifier for the model, defaults to "MedianFilter".
Example
from watermarklab.attackers.testattackers.blur import MedianFilter
attack = MedianFilter(noisename='MedianFilter')Constructor(self, noisename: str = 'MedianFilter')#
Initialize the median filter attack.
Parameters
noisenamestrName identifier for logging and reporting. Defaults to "MedianFilter".
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, kernel_size: int = 3) -> List[ndarray]#
Applies a median filter to the input image to smooth details and reduce noise.
Parameters
stego_imgsndarrayInput image in RGB format, uint8 [H, W, 3] [0,255].
cover_imgndarray, optionalNot used.
kernel_sizeintSize of the median filter kernel (must be odd and > 1).
Returns
ndarrayFiltered image, same shape and dtype as input.
Example
# method of MedianFilter
attack.attack(stego_imgs=stego_imgs, cover_img=None, kernel_size=3)classMeanFilter(BaseTestAttackModel)#
Applies a mean (average) filter to the input image to smooth details.
Parameters
noisenamestrName identifier for the model, defaults to "MeanFilter".
Example
from watermarklab.attackers.testattackers.blur import MeanFilter
attack = MeanFilter(noisename='MeanFilter')Constructor(self, noisename: str = 'MeanFilter')#
Initialize the mean (average) filter attack.
Parameters
noisenamestrName identifier for logging and reporting. Defaults to "MeanFilter".
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, kernel_size: int = 5) -> List[ndarray]#
Applies a mean filter to the input image to smooth details.
Parameters
stego_imgsndarrayInput image in RGB format, uint8 [H, W, 3] [0,255].
cover_imgndarray, optionalNot used.
kernel_sizeintSize of the mean filter kernel (must be odd).
Returns
ndarrayFiltered image, same shape and dtype as input.
Example
# method of MeanFilter
attack.attack(stego_imgs=stego_imgs, cover_img=None, kernel_size=5)watermarklab.attackers.testattackers.color
watermarklab/attackers/testattackers/color.pyclassIdentity(BaseTestAttackModel)#
Identity noise model that performs no operation (no-op) on the input images.
This model returns the input stego images unchanged and is primarily used as:
- A baseline for robustness testing (e.g., "No Attack" scenario)
- A control group to verify watermark extraction performance on clean images
- A placeholder in noise model pipelines
Since no distortion is applied, it represents the ideal condition where the watermark should be perfectly extractable (BER = 0, EA = 100%).
The model supports batched input (list of images) for efficient processing.
Example
from watermarklab.attackers.testattackers.color import Identity
attack = Identity(noisename='Identity')Constructor(self, noisename: str = 'Identity')#
Initializes the Identity noise model.
Parameters
noisenamestrDisplay name for logging and reporting. Defaults to "Identity".
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = None) -> List[ndarray]#
Alias for test(), applying no distortion to the input images.
Provided for semantic clarity in adversarial testing contexts where "attack" implies a degradation process. In this case, the "attack" is null.
Parameters
stego_imgsList[ndarray]Batch of stego images to be "attacked".
cover_imgList[ndarray], optionalOriginal cover images (ignored).
factorfloat, optionalIntensity parameter (ignored).
Returns
List[ndarray]Unmodified stego images.
Notes
Example
# method of Identity
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=None)classContrastReduction(BaseTestAttackModel)#
A contrast reduction attack that decreases the intensity difference between light and dark regions of an image.
This attack scales pixel values toward the overall mean intensity, reducing dynamic range. It can weaken watermark signals that rely on contrast variations.
The 'factor' parameter controls the strength:
- 1.0: No change (identity)
- 0.0: All pixels become the mean value (maximum reduction)
The transformation is: output = mean + (input - mean) * factor
Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of contrast-reduced images, same shape and dtype
- The attack is applied independently to each image in the batch
Example
from watermarklab.attackers.testattackers.color import ContrastReduction
attack = ContrastReduction(noisename='ContrastReduction')Constructor(self, noisename: str = 'ContrastReduction')#
Initializes the contrast reduction attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 0.7) -> List[ndarray]#
Applies contrast reduction to a batch of images (grayscale or RGB) using a vectorized implementation.
The attack reduces the dynamic range by scaling pixel intensities around the image mean. This is equivalent to reducing the gain of the image signal.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatContrast scaling factor in [0.0, 1.0]. 1.0 = no change, 0.0 = fully flattened.
Returns
List[ndarray]Batch of contrast-reduced images, each with the same shape and dtype as input.
Example
# method of ContrastReduction
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=0.7)classContrastEnhancement(BaseTestAttackModel)#
A contrast enhancement attack that amplifies the intensity differences between light and dark areas of an image.
This attack scales pixel values away from the mean intensity, increasing the dynamic range. It can stress watermarking schemes that are sensitive to local contrast changes.
The 'factor' parameter controls the strength:
- 1.0: No change (identity)
- > 1.0: Increased contrast (e.g., 1.5, 2.0, 3.0)
The transformation is: output = mean + (input - mean) * factor
Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of enhanced images, same shape and dtype
- The attack is applied independently to each image in the batch
Example
from watermarklab.attackers.testattackers.color import ContrastEnhancement
attack = ContrastEnhancement(noisename='ContrastEnhancement')Constructor(self, noisename: str = 'ContrastEnhancement')#
Initializes the contrast enhancement attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 1.5) -> List[ndarray]#
Applies contrast enhancement to a batch of images (grayscale or RGB) using a vectorized implementation.
The attack increases the dynamic range by scaling pixel intensities around the image mean. This is equivalent to increasing the gain of the image signal.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatContrast scaling factor >= 1.0. 1.0 = no change, higher values = stronger enhancement.
Returns
List[ndarray]Batch of contrast-enhanced images, each with the same shape and dtype as input.
Example
# method of ContrastEnhancement
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=1.5)classGammaCorrection(BaseTestAttackModel)#
A brightness adjustment attack using gamma curve transformation.
Gamma correction applies a non-linear power-law transformation to the image intensity, which can simulate display calibration differences or intentional brightness attacks. This can affect watermark robustness, especially for methods sensitive to non-linear pixel shifts.
The 'factor' parameter is the gamma value:
- factor < 1.0: brightens the image (expands dark tones)
- factor = 1.0: no change
- factor > 1.0: darkens the image (compresses bright tones)
Reference:
Poynton, C. (1998). Digital Video and HDTV: Algorithms and Interfaces.Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of gamma-corrected images, same shape and dtype
- The transformation is applied per-channel for RGB images and to the single channel for grayscale
Example
from watermarklab.attackers.testattackers.color import GammaCorrection
attack = GammaCorrection(noisename='GammaCorrection')Constructor(self, noisename: str = 'GammaCorrection')#
Initializes the gamma correction attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 1.5) -> List[ndarray]#
Applies gamma correction to a batch of images (grayscale or RGB) using a lookup table (LUT) for efficiency.
The transformation: output = input ** (1/gamma) A lookup table is precomputed for all 256 possible pixel values and applied via cv2.LUT.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatGamma value, typically in [0.1, 3.0]. <1.0 brightens, >1.0 darkens.
Returns
List[ndarray]Batch of gamma-corrected images, each with the same shape and dtype as input.
Example
# method of GammaCorrection
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=1.5)classChromaticAberration(BaseTestAttackModel)#
A color distortion attack that simulates chromatic aberration by laterally shifting color channels.
This attack mimics an optical phenomenon where different wavelengths (colors) are focused at different positions, causing red and blue fringes at high-contrast edges. It can disrupt watermark signals that rely on precise color alignment.
The 'factor' parameter controls the pixel shift amount:
- Positive values: blue shifts right, red shifts left
- Higher magnitude = stronger visual artifact
Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of distorted images, same shape and dtype as input
- For grayscale images, the single channel is replicated to three channels for processing,
and the output is converted back to grayscale by taking one channel
- For RGB images, the attack shifts red and blue channels while keeping green unchanged
- The shift wraps around the horizontal edges (using np.roll)
Example
from watermarklab.attackers.testattackers.color import ChromaticAberration
attack = ChromaticAberration(noisename='ChromaticAberration')Constructor(self, noisename: str = 'ChromaticAberration')#
Initializes the chromatic aberration attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 2) -> List[ndarray]#
Applies chromatic aberration to a batch of images (grayscale or RGB) using vectorized NumPy operations.
For RGB images:
- Blue channel (index 2) is shifted to the right by 'factor' pixels
- Red channel (index 0) is shifted to the left by 'factor' pixels
- Green channel (index 1) remains unchanged
For grayscale images:
- The single channel is replicated to three channels ([H, W] -> [H, W, 3]) for processing
- After applying the attack, one channel is taken to return a grayscale image ([H, W])
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintNumber of pixels to shift the red and blue channels. Typical range [1, 10].
Returns
List[ndarray]Batch of images with chromatic aberration applied, same shape and dtype as input.
Example
# method of ChromaticAberration
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=2)classColorQuantization(BaseTestAttackModel)#
A color reduction attack that reduces the number of distinct colors in an image.
This attack simulates low-color-depth displays or aggressive image compression by quantizing pixel values to the nearest multiple of the 'factor'. It can disrupt watermark signals that rely on fine color gradients or high color fidelity.
The 'factor' parameter controls the quantization step size:
- 4: Very coarse (16^3 = 4096 colors)
- 16: Medium (16^3 = 4096 colors, but coarser steps)
- 32: Very coarse (8^3 = 512 colors)
The transformation is: output = (input // factor) * factor
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of quantized images, same shape and dtype
- The operation is applied independently to each channel
Example
from watermarklab.attackers.testattackers.color import ColorQuantization
attack = ColorQuantization(noisename='ColorQuantization')Constructor(self, noisename: str = 'ColorQuantization')#
Initializes the color quantization attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 16) -> List[ndarray]#
Applies color quantization to a batch of stego images using vectorized integer arithmetic.
The attack reduces color precision by flooring each pixel value to the nearest multiple of 'factor'. This creates visible banding and eliminates subtle color variations.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintQuantization step size, typically in [4, 32]. Higher values = fewer colors.
Returns
List[ndarray]Batch of color-quantized images, each with the same shape and dtype as input.
Example
# method of ColorQuantization
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=16)classHueShiftAttack(BaseTestAttackModel)#
A color transformation attack that shifts the hue of an image in the HSV color space.
This attack modifies the perceived color of the image by rotating the hue channel, which can disrupt watermark signals that rely on specific color distributions or chrominance components.
The 'factor' parameter controls the degree of hue shift in degrees:
- 0.0: No change (identity)
- 30.0: Moderate color shift (e.g., red → orange)
- 180.0: Maximum shift (complementary colors)
The hue is cyclic modulo 180 (OpenCV convention), so shifts wrap around.
Reference:
Smith, A. R. (1978). Color gamut transform pairs.
In Proceedings of the 5th annual conference on Computer graphics and interactive techniques (SIGGRAPH '78).Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of hue-shifted images, same shape and dtype
- For grayscale images, the single channel is replicated to three channels for HSV processing,
and the output is converted back to grayscale by taking one channel
- For RGB images, the attack shifts the hue channel in HSV space
- Uses OpenCV's HSV representation (H: 0–180, S: 0–255, V: 0–255)
- Supports batch processing for efficiency
Example
from watermarklab.attackers.testattackers.color import HueShiftAttack
attack = HueShiftAttack(noisename='Hue')Constructor(self, noisename: str = 'Hue')#
Initializes the hue shift attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 30.0) -> List[ndarray]#
Applies hue shift to a batch of images (grayscale or RGB) in HSV color space.
For RGB images:
1. Converts from RGB to HSV.
2. Adds the shift value to the H channel, modulo 180.
3. Converts back to RGB.
For grayscale images:
1. Replicates the single channel to three channels to create a pseudo-RGB image.
2. Applies the hue shift in HSV space.
3. Converts back to grayscale by taking one channel.
This operation preserves luminance and saturation while altering color appearance for RGB images. For grayscale images, the effect may be limited due to the lack of initial color information.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatHue shift amount in degrees, range [0, 180].
Returns
List[ndarray]Batch of hue-shifted images, each with the same shape and dtype as input.
Example
# method of HueShiftAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=30.0)classDarkenAttack(BaseTestAttackModel)#
A brightness reduction attack that darkens the image by scaling the V (value) channel in HSV color space.
This attack simulates low-light conditions or display dimming, which can degrade watermark signals embedded in darker regions of the image. It preserves hue and saturation while reducing overall luminance.
The 'factor' parameter controls the brightness level:
- 1.0: No change (identity)
- 0.0: Completely black (maximum attack strength)
- Values in between: Proportional darkening
Reference:
Smith, A. R. (1978). Color gamut transform pairs.
In Proceedings of the 5th annual conference on Computer graphics and interactive techniques (SIGGRAPH '78).Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of darkened images, same shape and dtype
- For grayscale images, the single channel is replicated to three channels for HSV processing,
and the output is converted back to grayscale by taking one channel
- For RGB images, the attack scales the V channel in HSV space
- Uses OpenCV's HSV representation (V ∈ [0, 255])
Example
from watermarklab.attackers.testattackers.color import DarkenAttack
attack = DarkenAttack(noisename='Darken')Constructor(self, noisename: str = 'Darken')#
Initializes the darken attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 0.7) -> List[ndarray]#
Applies a darkening effect to a batch of images (grayscale or RGB) using HSV color space transformation.
For RGB images:
1. Converts RGB to HSV.
2. Scales the value channel (V) by 'factor'.
3. Clips the result to the valid range [0, 255].
4. Converts back to RGB.
For grayscale images:
1. Replicates the single channel to three channels to create a pseudo-RGB image.
2. Applies the darkening in HSV space by scaling the V channel.
3. Converts back to grayscale by taking one channel.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatBrightness scaling factor in [0.0, 1.0]. 1.0 = no change, 0.0 = completely black.
Returns
List[ndarray]Batch of darkened images, each with the same shape and dtype as input.
Example
# method of DarkenAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=0.7)classBrightenAttack(BaseTestAttackModel)#
A brightness enhancement attack that increases image luminance by amplifying the V (value) channel in HSV color space.
This attack simulates overexposure or display brightening, which can wash out subtle details and degrade watermark signals embedded in mid-to-dark tone regions. It preserves hue and saturation while increasing overall brightness.
The 'factor' parameter controls the amplification level:
- 1.0: No change (identity)
- >1.0: Increased brightness (e.g., 1.5, 2.0)
- Values are clipped to the valid range [0, 255] to prevent overflow
Reference:
Smith, A. R. (1978). Color gamut transform pairs.
In Proceedings of the 5th annual conference on Computer graphics and interactive techniques (SIGGRAPH '78).Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of brightened images, same shape and dtype
- For grayscale images, the single channel is replicated to three channels for HSV processing,
and the output is converted back to grayscale by taking one channel
- For RGB images, the attack scales the V channel in HSV space
- Uses OpenCV's HSV representation (V ∈ [0, 255])
Example
from watermarklab.attackers.testattackers.color import BrightenAttack
attack = BrightenAttack(noisename='Brighten')Constructor(self, noisename: str = 'Brighten')#
Initializes the brighten attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 2.0) -> List[ndarray]#
Applies a brightening effect to a batch of images (grayscale or RGB) using HSV color space transformation.
For RGB images:
1. Converts RGB to HSV.
2. Scales the value channel (V) by 'factor'.
3. Clips the result to the valid range [0, 255].
4. Converts back to RGB.
For grayscale images:
1. Replicates the single channel to three channels to create a pseudo-RGB image.
2. Applies the brightening in HSV space by scaling the V channel.
3. Converts back to grayscale by taking one channel.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatBrightness amplification factor, typically >= 1.0. 1.0 = no change, higher values = brighter image.
Returns
List[ndarray]Batch of brightened images, each with the same shape and dtype as input.
Example
# method of BrightenAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=2.0)classDesaturateAttack(BaseTestAttackModel)#
A color degradation attack that reduces image saturation by scaling the S (saturation) channel in HSV space.
This attack weakens color-based watermark signals by making the image appear more grayscale. It simulates poor display conditions or intentional color suppression.
The 'factor' parameter controls the saturation level:
- 1.0: No change (full color)
- 0.0: Complete desaturation (grayscale)
- Values in between: Partial desaturation
Reference:
Smith, A. R. (1978). Color gamut transform pairs.
In Proceedings of the 5th annual conference on Computer graphics and interactive techniques (SIGGRAPH '78).Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of desaturated images, same shape and dtype
- For grayscale images, the single channel is replicated to three channels for HSV processing,
and the output is converted back to grayscale by taking one channel
- For RGB images, the attack scales the S channel in HSV space
- Uses OpenCV's HSV representation (S ∈ [0, 255])
- Desaturation has minimal effect on grayscale images due to their lack of color information
Example
from watermarklab.attackers.testattackers.color import DesaturateAttack
attack = DesaturateAttack(noisename='Desaturate')Constructor(self, noisename: str = 'Desaturate')#
Initializes the desaturation attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 0.5) -> List[ndarray]#
Applies desaturation to a batch of images (grayscale or RGB) using HSV color space transformation.
For RGB images:
1. Converts RGB to HSV.
2. Scales the saturation channel (S) by 'factor'.
3. Clips to valid range [0, 255].
4. Converts back to RGB.
For grayscale images:
1. Replicates the single channel to three channels to create a pseudo-RGB image.
2. Applies desaturation in HSV space by scaling the S channel.
3. Converts back to grayscale by taking one channel.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatSaturation scaling factor in [0.0, 1.0]. 1.0 = no change, 0.0 = grayscale.
Returns
List[ndarray]Batch of desaturated images, each with the same shape and dtype as input.
Example
# method of DesaturateAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=0.5)classOversaturateAttack(BaseTestAttackModel)#
A color enhancement attack that increases image saturation by amplifying the S (saturation) channel in HSV space.
This attack pushes colors towards their most vivid state, potentially causing clipping and color distortion. It can disrupt watermark signals that rely on subtle color variations or are sensitive to chrominance changes.
The 'factor' parameter controls the amplification level:
- 1.0: No change (identity)
- >1.0: Increased saturation (e.g., 1.5, 2.0, 3.0)
Reference:
Smith, A. R. (1978). Color gamut transform pairs.
In Proceedings of the 5th annual conference on Computer graphics and interactive techniques (SIGGRAPH '78).Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of oversaturated images, same shape and dtype
- For grayscale images, the single channel is replicated to three channels for HSV processing,
and the output is converted back to grayscale by taking one channel
- For RGB images, the attack scales the S channel in HSV space
- Uses OpenCV's HSV representation (S ∈ [0, 255])
- Oversaturation has minimal effect on grayscale images due to their lack of color information
Example
from watermarklab.attackers.testattackers.color import OversaturateAttack
attack = OversaturateAttack(noisename='Oversaturate')Constructor(self, noisename: str = 'Oversaturate')#
Initializes the oversaturation attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 2.0) -> List[ndarray]#
Applies oversaturation to a batch of images (grayscale or RGB) using HSV color space transformation.
For RGB images:
1. Converts RGB to HSV.
2. Scales the saturation channel (S) by 'factor'.
3. Clips the result to the valid range [0, 255].
4. Converts back to RGB.
For grayscale images:
1. Replicates the single channel to three channels to create a pseudo-RGB image.
2. Applies oversaturation in HSV space by scaling the S channel.
3. Converts back to grayscale by taking one channel.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatSaturation amplification factor, typically >= 1.0. 1.0 = no change, higher values = stronger saturation.
Returns
List[ndarray]Batch of oversaturated images, each with the same shape and dtype as input.
Example
# method of OversaturateAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=2.0)classUnsharpMasking(BaseTestAttackModel)#
An image sharpening attack using unsharp masking technique with full batch support.
This attack enhances high-frequency details by amplifying the residuals between the original and a blurred version of the image. It is effective against watermarking methods sensitive to edge enhancement.
The 'factor' parameter controls the sharpening strength:
- 0.0: No change
- >0.0: Increasing sharpening (may amplify artifacts)
This implementation uses torchvision for true batched Gaussian blur, enabling GPU acceleration and eliminating the need for Python loops.
Reference:
Pizer, S. M., et al. (1987). Adaptive histogram equalization and its variations.
Computer Vision, Graphics, and Image Processing, 39(3), 355–368.Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of sharpened images, same shape and dtype
- Uses torchvision for batched Gaussian blur (supports GPU)
Example
from watermarklab.attackers.testattackers.color import UnsharpMasking
attack = UnsharpMasking(noisename='UnsharpMasking', sigma=3.0, threshold=0)Constructor(self, noisename: str = 'UnsharpMasking', sigma: float = 3.0, threshold: float = 0)#
Initializes the unsharp masking attack.
Parameters
noisenamestrName identifier for logging and reporting.
sigmafloatStandard deviation of the Gaussian kernel. Default is 3.0.
thresholdfloatThreshold for high-frequency components (0 = no thresholding).
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 1.0) -> List[ndarray]#
Applies unsharp masking to a batch of stego images using fully vectorized operations.
The pipeline:
1. Stack images into a 4D numpy array
2. Convert to float32 and normalize to [0,1]
3. Convert to CHW tensor and move to device
4. Apply batched Gaussian blur using torchvision
5. Compute high-frequency residuals
6. Apply thresholding (optional)
7. Sharpen and clamp
8. Convert back to numpy HWC uint8Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored).
factorfloatSharpening strength factor, typically in [0.0, 5.0].
Returns
List[ndarray]Batch of sharpened images, each with the same shape and dtype as input.
Example
# method of UnsharpMasking
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=1.0)watermarklab.attackers.testattackers.compression
watermarklab/attackers/testattackers/compression.pyclassVAE_BMshj2018FactorizedAttack(BaseTestAttackModel)#
A Variational Autoencoder (VAE)-based attack using the bmshj2018_factorized model. Applies lossy compression to the input image to potentially disrupt embedded watermarks. Reference: Ballé, J., Laparra, V., & Simoncelli, E. P. (2018). End-to-end optimized image compression.
International Conference on Learning Representations (ICLR).Parameters
devicestrDevice to run the model on, defaults to "cuda".
noisenamestrName identifier for the model, defaults to "VAE_BMshj2018FactorizedAttack".
Notes
The 'factor' parameter controls compression quality (1-8):
- 1: strongest compression (most aggressive watermark removal).
- 8: weakest compression (most faithful to input).
Example
from watermarklab.attackers.testattackers.compression import VAE_BMshj2018FactorizedAttack
attack = VAE_BMshj2018FactorizedAttack(device='cuda', noisename='VAE_BMshj2018FactorizedAttack')Constructor(self, device: str = 'cuda', noisename: str = 'VAE_BMshj2018FactorizedAttack')#
Initialize the bmshj2018-factorized compression attack.
Parameters
devicestrDevice for the compression model, e.g. "cuda" or "cpu". Defaults to "cuda".
noisenamestrName identifier for logging and reporting. Defaults to "VAE_BMshj2018FactorizedAttack".
Notes
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 3) -> List[ndarray]#
Applies VAE-based compression attack to the input image.
Parameters
stego_imgsndarrayInput image in RGB format, uint8 [H, W, 3] [0,255].
cover_imgndarray, optionalNot used.
factorintCompression quality level (1-8).
Returns
ndarrayReconstructed image after compression, same shape and dtype as input.
Example
# method of VAE_BMshj2018FactorizedAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=3)classVAE_BMshj2018HyperpriorAttack(BaseTestAttackModel)#
A Variational Autoencoder (VAE)-based attack using the bmshj2018_hyperprior model. Applies learned image compression with a scale hyperprior to disrupt embedded watermarks.
This attack first resizes the input image to 512x512 using nearest-neighbor interpolation, then compresses and reconstructs it using the hyperprior VAE model, and finally resizes it back to the original resolution. The resize operations introduce additional geometric distortion, making this a stronger attack than compression alone.
The 'factor' parameter controls the compression quality (1-8):
- 1: strongest compression (lowest bitrate, highest distortion)
- 8: weakest compression (highest bitrate, near lossless)
Reference:
Ballé, J., Minnen, D., Singh, S., Hwang, S. J., & Johnston, N. (2018).
Variational image compression with a scale hyperprior. International Conference on Learning Representations (ICLR).
https://arxiv.org/abs/1802.01436Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of reconstructed images, same shape and dtype
- The model is cached per quality level and device for efficiency
Example
from watermarklab.attackers.testattackers.compression import VAE_BMshj2018HyperpriorAttack
attack = VAE_BMshj2018HyperpriorAttack(device='cuda', noisename='VAE_BMshj2018HyperpriorAttack')Constructor(self, device: str = 'cuda', noisename: str = 'VAE_BMshj2018HyperpriorAttack')#
Initializes the attack model with the specified device and name.
Parameters
devicestrDevice to run the model on ('cuda' or 'cpu').
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 3) -> List[ndarray]#
Applies the VAE-based compression attack with hyperprior and resize pre/post-processing.
The attack pipeline is:
1. Resize each input image to 512x512 using nearest-neighbor interpolation.
2. Batch the preprocessed tensors and move to GPU.
3. Forward pass through the hyperprior VAE model.
4. Resize each reconstructed image back to its original size.
5. Return the batch of distorted images.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each of shape [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (not used in this attack).
factorintCompression quality level (1-8). Higher values preserve more detail.
Returns
List[ndarray]Batch of reconstructed images, each with the same shape and dtype as the input.
Example
# method of VAE_BMshj2018HyperpriorAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=3)classVAE_MBT2018MeanAttack(BaseTestAttackModel)#
A Variational Autoencoder (VAE)-based attack using the mbt2018_mean model. Applies learned image compression with a mean-scale hyperprior to disrupt embedded watermarks.
This attack first resizes the input image to 512x512 using nearest-neighbor interpolation, then compresses and reconstructs it using the MBT2018 (Minnen et al.) model with mean-scale hyperprior, and finally resizes it back to the original resolution. The resize operations introduce additional geometric distortion, making this a stronger attack than compression alone.
The 'factor' parameter controls the compression quality (1-8):
- 1: strongest compression (lowest bitrate, highest distortion)
- 8: weakest compression (highest bitrate, near lossless)
Reference:
Minnen, D., Ballé, J., & Toderici, G. (2018).
Joint autoregressive and hierarchical priors for learned image compression.
Advances in Neural Information Processing Systems (NeurIPS).
https://arxiv.org/abs/1809.02736Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of reconstructed images, same shape and dtype
- The model is cached per quality level and device for efficiency
Example
from watermarklab.attackers.testattackers.compression import VAE_MBT2018MeanAttack
attack = VAE_MBT2018MeanAttack(device='cuda', noisename='VAE_MBT2018MeanAttack')Constructor(self, device: str = 'cuda', noisename: str = 'VAE_MBT2018MeanAttack')#
Initializes the attack model with the specified device and name.
Parameters
devicestrDevice to run the model on ('cuda' or 'cpu').
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 3) -> List[ndarray]#
Applies the VAE-based compression attack with mean-scale hyperprior and resize pre/post-processing.
The attack pipeline is:
1. Resize each input image to 512x512 using nearest-neighbor interpolation.
2. Batch the preprocessed tensors and move to GPU.
3. Forward pass through the MBT2018 VAE model.
4. Resize each reconstructed image back to its original size.
5. Return the batch of distorted images.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each of shape [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (not used in this attack).
factorintCompression quality level (1-8). Higher values preserve more detail.
Returns
List[ndarray]Batch of reconstructed images, each with the same shape and dtype as the input.
Example
# method of VAE_MBT2018MeanAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=3)classVAE_MBT2018Attack(BaseTestAttackModel)#
A Variational Autoencoder (VAE)-based attack using the mbt2018 model. Applies learned image compression to disrupt embedded watermarks.
This attack first resizes the input image to 512x512 using nearest-neighbor interpolation, then compresses and reconstructs it using the MBT2018 (Minnen et al.) model, and finally resizes it back to the original resolution. The resize operations introduce additional geometric distortion, making this a stronger attack than compression alone.
The 'factor' parameter controls the compression quality (1-8):
- 1: strongest compression (lowest bitrate, highest distortion)
- 8: weakest compression (highest bitrate, near lossless)
Reference:
Minnen, D., Ballé, J., & Toderici, G. (2018).
Joint autoregressive and hierarchical priors for learned image compression.
Advances in Neural Information Processing Systems (NeurIPS).
https://arxiv.org/abs/1809.02736Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of reconstructed images, same shape and dtype
- The model is cached per quality level and device for efficiency
Example
from watermarklab.attackers.testattackers.compression import VAE_MBT2018Attack
attack = VAE_MBT2018Attack(device='cuda', noisename='VAE_MBT2018Attack')Constructor(self, device: str = 'cuda', noisename: str = 'VAE_MBT2018Attack')#
Initializes the attack model with the specified device and name.
Parameters
devicestrDevice to run the model on ('cuda' or 'cpu').
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 3) -> List[ndarray]#
Applies the VAE-based compression attack with resize pre/post-processing.
The attack pipeline is:
1. Resize each input image to 512x512 using nearest-neighbor interpolation.
2. Batch the preprocessed tensors and move to GPU.
3. Forward pass through the MBT2018 VAE model.
4. Resize each reconstructed image back to its original size.
5. Return the batch of distorted images.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each of shape [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (not used in this attack).
factorintCompression quality level (1-8). Higher values preserve more detail.
Returns
List[ndarray]Batch of reconstructed images, each with the same shape and dtype as the input.
Example
# method of VAE_MBT2018Attack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=3)classVAE_Cheng2020Attack(BaseTestAttackModel)#
A Variational Autoencoder (VAE)-based attack using the cheng2020_anchor model. Applies learned image compression with attention modules to disrupt embedded watermarks.
This attack first resizes the input image to 512x512 using nearest-neighbor interpolation, then compresses and reconstructs it using the Cheng2020 (CVPR 2020) model, and finally resizes it back to the original resolution. The resize operations introduce additional geometric distortion, making this a stronger attack than compression alone.
The 'factor' parameter controls the compression quality (1-6):
- 1: strongest compression (lowest bitrate, highest distortion)
- 6: weakest compression (highest bitrate, near lossless)
Reference:
Cheng, Z., Sun, H., & Takeuchi, M. (2020).
Learned image compression with discretized Gaussian mixture likelihoods and attention modules.
IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR).
https://arxiv.org/abs/2001.01568Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of reconstructed images, same shape and dtype
- The model is cached per quality level and device for efficiency
Example
from watermarklab.attackers.testattackers.compression import VAE_Cheng2020Attack
attack = VAE_Cheng2020Attack(device='cuda', noisename='VAE_Cheng2020Attack')Constructor(self, device: str = 'cuda', noisename: str = 'VAE_Cheng2020Attack')#
Initializes the attack model with the specified device and name.
Parameters
devicestrDevice to run the model on ('cuda' or 'cpu').
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 3) -> List[ndarray]#
Applies the VAE-based compression attack with resize pre/post-processing.
The attack pipeline is:
1. Resize each input image to 512x512 using nearest-neighbor interpolation.
2. Batch the preprocessed tensors and move to GPU.
3. Forward pass through the Cheng2020 VAE model.
4. Resize each reconstructed image back to its original size.
5. Return the batch of distorted images.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each of shape [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (not used in this attack).
factorintCompression quality level (1-6). Higher values preserve more detail.
Returns
List[ndarray]Batch of reconstructed images, each with the same shape and dtype as the input.
Example
# method of VAE_Cheng2020Attack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=3)classWebPCompression(BaseTestAttackModel)#
A lossy compression attack that simulates WebP encoding artifacts.
This attack encodes the input image into the WebP format at a specified quality level and then decodes it back to RGB. The recompression introduces compression artifacts such as blockiness, blurring, and color banding, which can disrupt embedded watermarks.
The 'factor' parameter controls the compression quality:
- 10: Very low quality (high compression, severe artifacts)
- 100: Lossless (no artifacts, for baseline testing)
This attack is highly relevant for evaluating watermark robustness against web-based image delivery systems where WebP is widely used.
Reference:
Google. (2023). WebP Image Format.
https://developers.google.com/speed/webpNotes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of compressed images, same shape and dtype
- Requires OpenCV with WebP support enabled
Example
from watermarklab.attackers.testattackers.compression import WebPCompression
attack = WebPCompression(noisename='WebPCompression')Constructor(self, noisename: str = 'WebPCompression')#
Initializes the WebP compression attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 20) -> List[ndarray]#
Applies WebP compression to a batch of stego images using OpenCV.
For each image:
1. Converts from RGB to BGR (OpenCV default).
2. Encodes to WebP format with specified quality.
3. Decodes back to BGR.
4. Converts back to RGB.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintWebP quality factor in [10, 100]. 10 = high compression, 100 = lossless.
Returns
List[ndarray]Batch of WebP-compressed images, each with the same shape and dtype as input.
Example
# method of WebPCompression
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=20)classJpeg(BaseTestAttackModel)#
A lossy compression attack that applies JPEG encoding to introduce compression artifacts.
This attack simulates common image degradation from web publishing, social media sharing, or storage optimization. It introduces blockiness, ringing, and high-frequency loss, which are particularly effective at disrupting watermark signals embedded in AC coefficients or high-frequency DCT components.
The 'factor' parameter controls the JPEG quality setting:
- 100: Near-lossless (very weak attack)
- 95: High quality (minimal artifacts)
- 50: Medium quality (visible block artifacts)
- 20: Low quality (severe degradation, strong attack)
- 1: Lowest quality (maximum compression, extreme distortion)
This implementation uses OpenCV's imencode/imdecode for JPEG compression.
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of JPEG-compressed images, same shape and dtype
- Uses OpenCV with JPEG quality factor [1, 100]
Example
from watermarklab.attackers.testattackers.compression import Jpeg
attack = Jpeg(noisename='Jpeg')Constructor(self, noisename: str = 'Jpeg')#
Initializes the JPEG compression attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_img: List[ndarray], cover_img: List[ndarray] = None, factor: int = 20) -> List[ndarray]#
Applies JPEG compression to a batch of stego images using OpenCV.
For each image:
1. Converts from RGB to BGR (OpenCV default).
2. Encodes to JPEG format with specified quality.
3. Decodes back to BGR.
4. Converts back to RGB.Parameters
stego_imgList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintJPEG quality factor in [1, 100]. 100 = best quality, 1 = worst quality.
Returns
List[ndarray]Batch of JPEG-compressed images, each with the same shape and dtype as input.
Example
# method of Jpeg
attack.attack(stego_img=stego_image, cover_img=None, factor=20)classMultiJpeg(BaseTestAttackModel)#
A multiple JPEG compression attack that applies repeated JPEG encoding with quality factors varying in a range around a central value.
- Class parameter
quality_factor: central JPEG quality (e.g., 80) - Class parameter
quality_range: half-width of quality variation (e.g., 10 → [70, 90]) - Method parameter
factor: number of compression rounds (e.g., 1, 3, 5)
Simulates real-world scenarios where an image undergoes multiple saves with slightly different compression settings, accumulating artifacts.
Notes
- Input: List of uint8 images [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: Same shape and dtype
- Uses OpenCV's imencode/imdecode via self.jpeg.attack()
Example
from watermarklab.attackers.testattackers.compression import MultiJpeg
attack = MultiJpeg(noisename='Multi-Jpeg', quality_factor=80, quality_range=5)Constructor(self, noisename: str = 'Multi-Jpeg', quality_factor: int = 80, quality_range: int = 5)#
Parameters
noisenamestrName for logging. Defaults to "Multi-Jpeg".
quality_factorintCentral JPEG quality in [1, 100]. Default is 80.
quality_rangeintHalf-range of quality variation. Final QF ∈ [qf−range, qf+range] ∩ [1,100]. If 0, uses fixed quality (original behavior). Default: 5.
attack(self, stego_img: List[np.ndarray], cover_img: Optional[List[np.ndarray]] = None, factor: int = 1) -> List[np.ndarray]#
Applies JPEG compression factor times. Each round uses a quality factor sampled from:
[quality_factor - quality_range, quality_factor + quality_range],
clamped to [1, 100].
Parameters
stego_imgList of images, each [H, W] or [H, W, 3], dtype=uint8, range [0,255].
cover_imgIgnored (for interface compatibility).
factorNumber of JPEG compression rounds (≥1). Default: 1.
Returns
List of images after repeated JPEG compression.
Example
# method of MultiJpeg
attack.attack(stego_img=stego_image, cover_img=None, factor=1)classJpeg2000(BaseTestAttackModel)#
A lossy wavelet-based compression attack using the JPEG2000 format.
This attack applies JPEG2000 compression, which uses discrete wavelet transform (DWT) instead of DCT, resulting in different artifacts (e.g., less blockiness, more ringing) compared to standard JPEG. It is effective for evaluating watermark robustness against modern compression standards.
The 'factor' parameter controls the compression ratio:
- 1: Minimal compression (highest quality)
- 100: Maximum compression (lowest quality)
Higher values = stronger attack.
This implementation uses OpenCV's imencode/imdecode for JPEG2000 compression. Note: OpenCV relies on external libraries (e.g., Jasper, OpenJPEG) for JP2 support.
Reference:
Skodras, A., Christopoulos, C., & Ebrahimi, T. (2001).
The JPEG 2000 still image compression standard.
IEEE Signal Processing Magazine, 18(5), 36–58.Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of JPEG2000-compressed images, same shape and dtype
- Requires OpenCV with JPEG2000 support (IMWRITE_JPEG2000_COMPRESSION_X1000)
Example
from watermarklab.attackers.testattackers.compression import Jpeg2000
attack = Jpeg2000(noisename='Jpeg2000')Constructor(self, noisename: str = 'Jpeg2000')#
Initializes the JPEG2000 compression attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_img: List[ndarray], cover_img: List[ndarray] = None, factor: int = 20) -> List[ndarray]#
Applies JPEG2000 compression to a batch of stego images using OpenCV.
For each image:
1. Converts from RGB to BGR (OpenCV default).
2. Encodes to JPEG2000 (.jp2) format with specified compression ratio.
3. Decodes back to BGR.
4. Converts back to RGB.Parameters
stego_imgList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintCompression ratio factor in [1, 100]. 1 = low compression, 100 = high compression.
Returns
List[ndarray]Batch of JPEG2000-compressed images, each with the same shape and dtype as input.
Example
# method of Jpeg2000
attack.attack(stego_img=stego_image, cover_img=None, factor=20)classMultiJpeg2000(BaseTestAttackModel)#
An attack model that applies JPEG2000 compression multiple times to stego images, with quality factor varying around a central value during repeated rounds.
- quality_factor: central quality level (higher = less compression)
- quality_range: half-width of variation (e.g., range=10 → [qf-10, qf+10])
- factor: number of compression rounds
Simulates real-world scenarios where images undergo multiple saves with slightly different JPEG2000 settings.
Example
from watermarklab.attackers.testattackers.compression import MultiJpeg2000
attack = MultiJpeg2000(quality_factor=80, quality_range=5, noisename='Multi-Jpeg2000')Constructor(self, quality_factor: int = 80, quality_range: int = 5, noisename: str = 'Multi-Jpeg2000')#
Initialize the MultiJpeg2000 attack.
Parameters
quality_factorintCentral quality level for JPEG2000 (e.g., 80).
quality_rangeintHalf-range for quality variation. Final QF ∈ [qf−range, qf+range] ∩ [1, 100]. Set to 5 for fixed quality (default).
noisenamestrName identifier for this noise/attack type.
attack(self, stego_img: List[ndarray], cover_img: Optional[List[ndarray]] = None, factor: int = 3) -> List[ndarray]#
Apply multiple rounds of JPEG2000 compression. Each round uses a quality factor sampled from [quality_factor ± quality_range], clamped to [1, 100].
Parameters
stego_imgList[ndarray]List of stego images (uint8, [0,255], shape [H,W] or [H,W,3]).
cover_imgList[ndarray], optionalIgnored.
factorintNumber of compression rounds (≥1).
Returns
List[ndarray]Attacked images after repeated JPEG2000 compression.
Example
# method of MultiJpeg2000
attack.attack(stego_img=stego_image, cover_img=None, factor=3)watermarklab.attackers.testattackers.geometric
watermarklab/attackers/testattackers/geometric.pyclassResize(BaseTestAttackModel)#
A spatial resampling attack that scales an image down and then back up to the original resolution.
This attack introduces interpolation artifacts (blurring, aliasing) by reducing the image to a smaller size and then upsampling it. It simulates common image processing operations like thumbnail generation or transmission over bandwidth-limited channels.
The 'scale_p' parameter controls the downscaling factor:
- 1.0: No change (identity)
- 0.8: Reduce to 80% size, then upscale back
- 0.5: Halve the dimensions, then double back (stronger distortion)
This implementation uses torchvision.transforms.Resize for true batched processing, enabling GPU acceleration and eliminating Python loops.
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of resized images, same shape and dtype
- Uses torchvision for batched, GPU-accelerated resizing
Example
from watermarklab.attackers.testattackers.geometric import Resize
attack = Resize(noisename='Resize', mode='bilinear')Constructor(self, noisename: str = 'Resize', mode: str = 'bilinear')#
Initializes the resize attack.
Parameters
noisenamestrName identifier for logging and reporting.
modestrInterpolation method: 'nearest', 'bilinear', 'bicubic'.
attack(self, stego_img: List[ndarray], cover_img: List[ndarray] = None, scale_p: float = 0.8) -> List[ndarray]#
Applies resize distortion to a batch of stego images using torchvision's Resize transform. Supports both RGB and grayscale images.
The pipeline:
1. Stack images into a 4D numpy array [B, H, W, C]
2. Convert to float32 and normalize to [0,1]
3. Convert to CHW tensor and move to device
4. Downsample using transforms.Resize
5. Upsample back to original size using transforms.Resize
6. Convert back to HWC uint8 numpy arraysParameters
stego_imgList[ndarray]Batch of watermarked images, each [H, W] or [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored).
scale_pfloatDownscaling factor, range (0.01, 1.0].
Returns
List[ndarray]Batch of resized images, each with the same shape and dtype as input.
Example
# method of Resize
attack.attack(stego_img=stego_image, cover_img=None, scale_p=0.8)classRotate(BaseTestAttackModel)#
A geometric attack that rotates an image around its center by a specified angle.
This attack simulates camera rotation or document misalignment, which can disrupt watermark signals that are sensitive to spatial orientation or rely on fixed pixel patterns.
The 'factor' parameter controls the rotation angle in degrees:
- 0.0: No rotation (identity)
- 10.0: 10-degree clockwise rotation
- 360: Maximum rotation (wraps around)
The rotation is performed around the image center using bilinear interpolation, and the borders are filled with black (0, 0, 0).
This implementation uses torchvision.transforms.functional.rotate for true batched processing, enabling GPU acceleration and eliminating Python loops.
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of rotated images, same shape and dtype
- Uses torchvision for batched, GPU-accelerated rotation
Example
from watermarklab.attackers.testattackers.geometric import Rotate
attack = Rotate(noisename='Rotate')Constructor(self, noisename: str = 'Rotate')#
Initializes the rotation attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_img: List[ndarray], cover_img: List[ndarray] = None, factor: float = 10.0) -> List[ndarray]#
Applies rotation to a batch of stego images using torchvision's rotate function.
Parameters
stego_imgList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored).
factorfloatRotation angle in degrees, range [-180, 180].
Returns
List[ndarray]Batch of rotated images, each with the same shape and dtype as input.
Example
# method of Rotate
attack.attack(stego_img=stego_image, cover_img=None, factor=10.0)classFlipAttack(BaseTestAttackModel)#
A spatial flip attack that flips images either horizontally or vertically.
✅ Assumes all input images have the SAME shape [H, W, C] or [H, W] ✅ Fully vectorized batch processing (no Python loops during flip) ✅ Supports both grayscale and color images ✅ GUARANTEES output dtype is uint8
The 'factor' parameter controls the flip direction:
- 'H': Horizontal flip (left-right mirror)
- 'V': Vertical flip (up-down mirror)
Notes
- Input: List of uint8 images, all same shape [H, W] or [H, W, C], range [0, 255]
- Output: List of flipped images, same shape and guaranteed uint8 dtype
Example
from watermarklab.attackers.testattackers.geometric import FlipAttack
attack = FlipAttack(noisename='FlipAttack')Constructor(self, noisename: str = 'FlipAttack')#
Initialize the flip attack.
Parameters
noisenamestrName identifier for logging and reporting. Defaults to "FlipAttack".
attack(self, stego_imgs: List[ndarray[np.uint8]], cover_img: Optional[List[ndarray[np.uint8]]] = None, factor: str = 'H') -> List[ndarray[np.uint8]]#
Applies flip to a batch of images with identical shape using full vectorization. GUARANTEES that output dtype is uint8.
Parameters
stego_imgsList[ndarray]List of uint8 images, all same shape [H, W] or [H, W, C].
cover_imgIgnored (for compatibility).
factorstr'H' for horizontal, 'V' for vertical flip.
Returns
List[ndarray]Flipped images, same shape and guaranteed uint8 dtype.
Raises
ValueErrorIf factor is not 'H' or 'V'.
Example
# method of FlipAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor='H')classTranslationAttack(BaseTestAttackModel)#
A simplified translation attack using OpenCV's warpAffine for accurate translation.
- Only one parameter:
percent(e.g., 0.1 means up to 10% of width/height). - The actual shift magnitude is controlled by the input
factor(0.0 ~ 1.0). - Supports both grayscale (H, W) and color (H, W, C) images.
- Padding is always zero-filled (borderValue=(0,0,0)).
Example
from watermarklab.attackers.testattackers.geometric import TranslationAttack
attack = TranslationAttack(noisename='TranslationAttack')Constructor(self, noisename: str = 'TranslationAttack')#
Parameters
noisenamestrName for logging. Defaults to "TranslationAttack".
attack(self, stego_imgs: List[ndarray], cover_img: Optional[List[ndarray]] = None, factor: Optional[float] = 0.1) -> List[ndarray]#
Apply random translation with magnitude controlled by factor.
Final shift = factor * image_dimension. If factor is None, it defaults to 1.0 (i.e., full intensity).
Parameters
stego_imgsList of images, each (H, W) or (H, W, C).
cover_imgIgnored.
factorFloat in [0, 1]. If None, treated as 1.0.
Returns
List of translated images with same shapes and dtypes.
Example
# method of TranslationAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=0.1)classCrop(BaseTestAttackModel)#
A spatial attack that simulates partial occlusion by cropping a region and filling the rest based on a specified mode.
The 'factor' parameter controls the area ratio of the kept region:
- 1.0: No change (entire image kept)
- <1.0: A sub-region is preserved, rest is filled
Supported fill modes:
- 'constant_replace': Fill with a constant color (e.g., black)
- 'cover_replace': Fill with the corresponding region from the original cover image
Supported crop modes:
- 'center': Keep central region (deterministic)
- 'random': Keep a randomly positioned region using Gaussian-sampled rectangle (stochastic)
Example
from watermarklab.attackers.testattackers.geometric import Crop
attack = Crop(noisename='Crop', mode='constant_replace', constant=0.0, crop_mode='center')Constructor(self, noisename: str = 'Crop', mode: str = 'constant_replace', constant: float = 0.0, crop_mode: str = 'center')#
Initialize the crop attack.
Parameters
noisenamestrName identifier for logging and reporting. Defaults to "Crop".
modestrFill strategy for the cropped region, "constant_replace" or "cover_replace". Defaults to "constant_replace".
constantfloatFill intensity in [0, 1] used by "constant_replace" (scaled by 255 in :meth:attack). Defaults to 0.0.
crop_modestrRegion selection, "center" or "random". Defaults to "center".
Raises
ValueErrorIf `mode or crop_mode` is not a supported value.
attack(self, stego_imgs: List[ndarray], cover_img: Optional[List[ndarray]] = None, factor: float = 0.7) -> List[ndarray]#
Apply the crop distortion to a batch of stego images, filling the cropped region with a constant gray value or with the matching cover pixels (`self.mode`).
Parameters
stego_imgsList[ndarray]uint8 images, [H, W] or [H, W, C], range [0, 255].
cover_imgList[ndarray], optionalRequired and size-matched for "cover_replace".
factorfloatKept-area ratio, clipped to [0.01, 1.0]. In "center" mode a smaller factor removes more content and is therefore a stronger attack; in "random" mode the kept rectangle is sampled with ratio `1 - factor`. Defaults to 0.7.
Returns
List[ndarray]Attacked uint8 images with the same shape as the inputs.
Raises
ValueErrorIf "cover_replace" is used without a matching cover image.
Example
# method of Crop
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=0.7)classCropout(BaseTestAttackModel)#
Cropout attack with two modes:
- 'center': remove a central rectangle (deterministic)
- 'random': remove a random rectangle using Gaussian-sampled size (your logic)
factor: proportion of area to REMOVE (0.0 ~ 1.0)
Example
from watermarklab.attackers.testattackers.geometric import Cropout
attack = Cropout(noisename='Cropout', constant=0.0, mode='constant_replace', cropout_mode='random')Constructor(self, noisename: str = 'Cropout', constant: float = 0.0, mode: str = 'constant_replace', cropout_mode: str = 'random')#
Initialize the cropout attack.
Parameters
noisenamestrName identifier for logging and reporting. Defaults to "Cropout".
constantfloatFill intensity in [0, 1] used by "constant_replace" (stored scaled by 255). Defaults to 0.0.
modestrFill strategy, "constant_replace" or "cover_replace". Defaults to "constant_replace".
cropout_modestrRemoved-region selection, "random" or "center". Defaults to "random".
Raises
ValueErrorIf `mode or cropout_mode` is not a supported value.
attack(self, stego_img: List[ndarray], cover_img: Optional[List[ndarray]] = None, factor: float = 0.3) -> List[ndarray]#
Apply the cropout distortion to a batch of stego images, replacing the removed region with a constant gray value or with the matching cover pixels (`self.mode`).
Parameters
stego_imgList[ndarray]uint8 images, [H, W] or [H, W, C], range [0, 255].
cover_imgList[ndarray], optionalRequired and size-matched for "cover_replace".
factorfloatProportion of the image area removed, clipped to [0.0, 1.0]; a larger factor removes more content and is therefore a stronger attack. Defaults to 0.3.
Returns
List[ndarray]Attacked uint8 images with the same shape as the inputs.
Raises
ValueErrorIf "cover_replace" is used without a matching cover image.
Example
# method of Cropout
attack.attack(stego_img=stego_image, cover_img=None, factor=0.3)classRegionZoom(BaseTestAttackModel)#
A spatial attack that simulates digital zoom by cropping a random sub-region and resizing it to full resolution.
This attack removes peripheral information and enlarges a central portion, potentially disrupting watermark signals embedded in image borders or relying on global structure.
The 'factor' parameter controls the relative area of the cropped region:
- 1.0: Crop covers almost the entire image (minimal zoom, weakest attack)
- <1.0: Smaller region is cropped and upscaled (stronger zoom, stronger attack)
The aspect ratio of the original image is preserved in the cropped region.
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of zoomed images, same shape and dtype
- Uses bilinear interpolation for resizing
Example
from watermarklab.attackers.testattackers.geometric import RegionZoom
attack = RegionZoom(noisename='RegionZoom')Constructor(self, noisename: str = 'RegionZoom')#
Initializes the region zoom attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 0.7) -> List[ndarray]#
Applies region zoom (crop + resize) distortion to a batch of stego images.
For each image:
1. Calculate the size of a sub-region to crop, based on 'factor' and aspect ratio.
2. Randomly determine the top-left position of the crop.
3. Crop the image to the sub-region.
4. Resize the cropped region back to the original dimensions using bilinear interpolation.Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorfloatRatio of the cropped area to the original image area, range (0.01, 1.0].
Returns
List[ndarray]Batch of zoomed images, each with the same shape and dtype as input.
Example
# method of RegionZoom
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=0.7)classPixelDropout(BaseTestAttackModel)#
A pixel-level occlusion attack that randomly drops (replaces) pixels to simulate data loss or noise.
This attack sets a random subset of pixels to a replacement value, disrupting local texture and high-frequency information where many watermark signals are embedded.
The 'factor' parameter controls the dropout probability:
- 0.0: No pixels dropped (identity)
- 0.1: 10% of pixels replaced
- 1.0: All pixels replaced (complete destruction)
Supported replacement modes:
- 'constant_replace': Replace with a constant color (e.g., black)
- 'cover_replace': Replace with the corresponding pixel from the original cover image
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of modified images, same shape and dtype
- For 'cover_replace',
cover_imgmust be provided and at least as large asstego_img
Example
from watermarklab.attackers.testattackers.geometric import PixelDropout
attack = PixelDropout(noisename='PixelDropout', mode='constant_replace', constant=0)Constructor(self, noisename: str = 'PixelDropout', mode: str = 'constant_replace', constant: int = 0)#
Initializes the pixel dropout attack.
Parameters
noisenamestrName identifier for logging and reporting.
modestrReplacement strategy: 'constant_replace' or 'cover_replace'.
constantintPixel value (0-1) for 'constant_replace' mode. Default is 0 (black).
Raises
AssertionErrorIf mode is not supported.
attack(self, stego_img: List[ndarray], cover_img: List[ndarray] = None, factor: float = 0.1) -> List[ndarray]#
Applies pixel dropout to a batch of stego images.
For each image:
1. Generates a random binary mask based on the dropout probability ('factor').
2. Keeps pixels where mask is True.
3. Replaces pixels where mask is False with either a constant value or the cover image content.Parameters
stego_imgList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images for 'cover_replace' mode.
factorfloatProbability of dropping a pixel, range [0.0, 1.0].
Returns
List[ndarray]Batch of images with pixel dropout applied, each with the same shape and dtype as input.
Example
# method of PixelDropout
attack.attack(stego_img=stego_image, cover_img=None, factor=0.1)classShearAttack(BaseTestAttackModel)#
A shear attack controlled by angle (in degrees) and explicit direction.
factor: shear angle in degrees (e.g., 15, 30, 45).direction: one of "x" (horizontal), "y" (vertical), or "random".- Shear magnitude = tan(radians(angle)).
- Supports grayscale (H, W) and color (H, W, C).
- Padding is zero-filled (black).
Example
from watermarklab.attackers.testattackers.geometric import ShearAttack
attack = ShearAttack(noisename='ShearAttack', direction='random')Constructor(self, noisename: str = 'ShearAttack', direction: str = 'random')#
Parameters
noisenamestrName for logging.
directionstrShear direction. Must be one of:
- "x": horizontal shear (columns slant)
- "y": vertical shear (rows slant)
- "random": randomly choose x or y per image
attack(self, stego_imgs: List[ndarray], cover_img: Optional[List[ndarray]] = None, factor: Optional[float] = 15.0) -> List[ndarray]#
Apply shear using angle in degrees and predefined direction.
Parameters
stego_imgsList of images, each (H, W) or (H, W, C).
cover_imgIgnored.
factorShear angle in degrees (e.g., 15.0). If None, defaults to 15°.
Returns
List of sheared images with same shape and dtype.
Example
# method of ShearAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=15.0)watermarklab.attackers.testattackers.noise
watermarklab/attackers/testattackers/noise.pyclassPoissonNoise(BaseTestAttackModel)#
A noise attack that adds Poisson-distributed noise to a batch of images.
Poisson noise models sensor noise in digital imaging systems, where the variance of the noise is proportional to the pixel intensity (e.g., photon counting noise). This makes it particularly relevant for evaluating watermark robustness under low-light conditions.
The 'factor' parameter controls the effective signal-to-noise ratio:
- Lower factor: stronger noise (simulates low light)
- Higher factor: weaker noise (simulates high light)
Reference:
Foi, A., Trimeche, M., Katkovnik, V., & Egiazarian, K. (2008).
Practical Poissonian-Gaussian noise modeling and denoising based on precise noise parameter estimation.
IEEE Transactions on Image Processing, 17(6), 10.1109/TIP.2008.921849Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of noisy images, same shape and dtype
- This implementation uses fully vectorized NumPy operations for maximum CPU efficiency
Example
from watermarklab.attackers.testattackers.noise import PoissonNoise
attack = PoissonNoise(noisename='PoissonNoise')Constructor(self, noisename: str = 'PoissonNoise')#
Initializes the Poisson noise attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: float = 1.0) -> List[ndarray]#
Applies Poisson noise to a batch of stego images using fully vectorized operations.
The noise model is:
noisy_img = clip( Poisson(img / factor) * factor, 0, 255 )
This preserves the mean while scaling the variance, simulating realistic sensor noise.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored).
factorfloatNoise intensity scaling factor. Typical range [0.1, 10.0].
Returns
List[ndarray]Batch of noisy images, each with the same shape and dtype as input.
Example
# method of PoissonNoise
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=1.0)classGaussianNoise(BaseTestAttackModel)#
A noise attack that adds zero-mean Gaussian noise to the input image.
This attack simulates random pixel perturbations caused by electronic sensor noise or transmission errors. It is a fundamental test for watermark robustness under random signal degradation.
The 'std' parameter controls the standard deviation of the noise:
- 0.0: No noise (identity)
- 0.05: Low noise (barely perceptible)
- 0.15: Medium noise (clearly visible)
- >0.2: High noise (severe degradation)
The noise is scaled to the [0, 255] range before addition.
Reference:
Foi, A., Trimeche, M., Katkovnik, V., & Egiazarian, K. (2008).
Practical Poissonian-Gaussian noise modeling and denoising based on precise noise parameter estimation.
IEEE Transactions on Image Processing, 17(6), 10.1109/TIP.2008.921849Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of noisy images, same shape and dtype
- The noise is generated independently for each image in the batch
Example
from watermarklab.attackers.testattackers.noise import GaussianNoise
attack = GaussianNoise(mu=0.0, noisename='GaussianNoise')Constructor(self, mu: float = 0.0, noisename: str = 'GaussianNoise')#
Initializes the Gaussian noise attack.
Parameters
mufloatMean of the Gaussian distribution. Default is 0.0.
noisenamestrName identifier for logging and reporting.
attack(self, stego_img: List[ndarray], cover_img: List[ndarray] = None, std: float = 1.5) -> List[ndarray]#
Applies Gaussian noise to a batch of stego images using vectorized operations.
The noise model is:
noised_img = clip( stego_img + N(mu, std) * 255, 0, 255 )Parameters
stego_imgList[ndarray]Batch of watermarked images, each [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
stdfloatStandard deviation of the Gaussian noise, relative to [0,1] range.
Returns
List[ndarray]Batch of noisy images, each with the same shape and dtype as input.
Example
# method of GaussianNoise
attack.attack(stego_img=stego_image, cover_img=None, std=1.5)classSaltPepperNoise(BaseTestAttackModel)#
A non-linear noise attack that simulates salt-and-pepper noise by randomly setting pixels to extreme values.
This attack models severe pixel corruption, such as that caused by faulty sensors, bit errors, or transmission faults. It flips a random subset of pixels to either the minimum (0, "pepper") or maximum (255, "salt") intensity value.
The 'noise_ratio' parameter controls the proportion of pixels affected:
- 0.0: No noise (identity)
- 0.1: 10% of pixels are corrupted (5% salt, 5% pepper)
- 1.0: All pixels are set to either 0 or 255 (complete destruction)
The attack is applied independently to each image in the batch and supports both grayscale and color images by checking the input dimensionality.
Reference:
González, R. C., & Woods, R. E. (2008). Digital Image Processing (3rd ed.). Prentice Hall.Notes
- Input: List of uint8 images, either [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of noisy images, same shape and dtype
- The noise is distributed equally between salt (255) and pepper (0) pixels
Example
from watermarklab.attackers.testattackers.noise import SaltPepperNoise
attack = SaltPepperNoise(noisename='SaltPepperNoise')Constructor(self, noisename: str = 'SaltPepperNoise')#
Initializes the salt-and-pepper noise attack.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, noise_ratio: float = 0.1) -> List[ndarray]#
Applies salt-and-pepper noise to a batch of stego images.
For each image:
1. Creates a copy of the input image.
2. Generates a random noise mask over the spatial dimensions.
3. Sets pixels below `noise_ratio/2` to 255 ("salt").
4. Sets pixels between `noise_ratio/2` and `noise_ratio` to 0 ("pepper").
5. Preserves the remaining pixels.
The method handles both grayscale and color images:
- Grayscale: shape [H, W], scalar assignment
- Color: shape [H, W, 3], vector assignment
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] or [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
noise_ratiofloatProportion of pixels to corrupt, range [0.0, 1.0].
Returns
List[ndarray]Batch of noisy images, each with the same shape and dtype as input.
Example
# method of SaltPepperNoise
attack.attack(stego_imgs=stego_imgs, cover_img=None, noise_ratio=0.1)watermarklab.attackers.testattackers.regeneration
watermarklab/attackers/testattackers/regeneration.pyclassReSDPipeline(StableDiffusionPipeline)#
A custom Stable Diffusion pipeline for image generation with support for head-start latents and dual prompts. Extends the base StableDiffusionPipeline from the diffusers library.
Example
from watermarklab.attackers.testattackers.regeneration import ReSDPipeline
attack = ReSDPipeline()__call__(self, prompt: Union[str, List[str]], prompt1_steps: Optional[int] = None, prompt2: Optional[str] = None, head_start_latents: Optional[Union[torch.FloatTensor, list]] = None, head_start_step: Optional[int] = None, height: Optional[int] = None, width: Optional[int] = None, num_inference_steps: int = 50, guidance_scale: float = 7.5, negative_prompt: Optional[Union[str, List[str]]] = None, num_images_per_prompt: Optional[int] = 1, eta: float = 0.0, generator: Optional[torch.Generator] = None, latents: Optional[torch.FloatTensor] = None, output_type: Optional[str] = 'pil', return_dict: bool = True, callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None, callback_steps: Optional[int] = 1)#
Generates images using the Stable Diffusion model with optional head-start latents and dual prompts.
Parameters
promptUnion[str, List[str]]The text prompt(s) to guide image generation.
prompt1_stepsOptional[int]Number of steps to use the first prompt before switching to prompt2.
prompt2Optional[str]Secondary prompt for later denoising steps.
head_start_latentsOptional[Union[torch.FloatTensor, list]]Pre-generated latents for head-start.
head_start_stepOptional[int]Step to start denoising from when using head-start latents.
heightOptional[int]Height of the generated image in pixels.
widthOptional[int]Width of the generated image in pixels.
num_inference_stepsintNumber of denoising steps, defaults to 50.
guidance_scalefloatGuidance scale for classifier-free guidance, defaults to 7.5.
negative_promptOptional[Union[str, List[str]]]Negative prompt(s) to avoid in generation.
num_images_per_promptOptional[int]Number of images to generate per prompt, defaults to 1.
etafloatDDIM eta parameter, defaults to 0.0.
generatorOptional[torch.Generator]Random number generator for reproducibility.
latentsOptional[torch.FloatTensor]Pre-generated noisy latents.
output_typeOptional[str]Output format ("pil" or "np.array"), defaults to "pil".
return_dictboolWhether to return a StableDiffusionPipelineOutput object, defaults to True.
callbackOptional[Callable]Callback function called during inference.
callback_stepsOptional[int]Frequency of callback invocation, defaults to 1.
Returns
StableDiffusionPipelineOutput or tuple: Generated images and NSFW flags if return_dict is True, otherwise a tuple of (images, nsfw_content_detected).
Example
# method of ReSDPipeline
attack.__call__(prompt=prompt, prompt1_steps=None, prompt2=None, head_start_latents=None, head_start_step=None, height=None, width=None, num_inference_steps=50, guidance_scale=7.5, negative_prompt=None, num_images_per_prompt=1, eta=0.0, generator=None, latents=None, output_type='pil', return_dict=True, callback=None, callback_steps=1)classDiffuseAttack(BaseTestAttackModel)#
A single-step diffusion-based attack using ReSDPipeline. Adds noise at a specified timestep and regenerates the image via a head-start mechanism to disrupt embedded watermarks.
This attack leverages classifier-free guidance to regenerate the image with high fidelity while preserving semantic content. It is particularly effective against watermarking schemes that rely on high-frequency signals.
The process:
Notes
- Input: List of uint8 images, each [H, W] (grayscale) or [H, W, 3] (RGB), range [0, 255]
- Output: List of regenerated images, same shape and dtype
- For grayscale images, the single channel is replicated to three channels for processing,
and the output is converted back to grayscale by taking one channel
- The model uses Stable Diffusion 2.1 base (fp16) and requires CUDA
- 'factor' controls the noise timestep (1-200): higher = more noise
Example
from watermarklab.attackers.testattackers.regeneration import DiffuseAttack
attack = DiffuseAttack(model_id='stabilityai/stable-diffusion-2-1-base', noisename='DiffuseAttack')Constructor(self, model_id: str = 'stabilityai/stable-diffusion-2-1-base', noisename: str = 'DiffuseAttack')#
Initializes the diffusion attack model.
Parameters
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 60) -> List[ndarray]#
Applies a single-step diffusion regeneration attack to a batch of images (grayscale or RGB).
The attack uses a "head-start" decoding strategy:
- Noise is added at an early diffusion timestep (controlled by 'factor').
- The decoder starts from a later step (head_start_step), allowing the model
to regenerate content while preserving some original structure.
For grayscale images:
- The single channel is replicated to three channels to create a pseudo-RGB image.
- After processing, one channel is taken to restore the grayscale shape.
This method is highly efficient due to batched processing and minimizes CPU-GPU transfer.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each [H, W] (grayscale) or [H, W, 3] (RGB), dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintDiffusion timestep for noise injection, range [1, 200]. Higher values = more noise.
Returns
List[ndarray]Batch of regenerated images, each with the same shape and dtype as input.
Example
# method of DiffuseAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=60)classMultiDiffuseAttack(BaseTestAttackModel)#
A multi-step diffusion-based attack that applies DiffuseAttack repeatedly for multiple rounds. Each round injects noise and regenerates the image using the same fixed diffusion timestep.
This attack amplifies the watermark-removal effect by performing sequential regeneration. The cumulative distortion can effectively erase subtle, high-frequency watermark signals that survive a single diffusion step.
The 'factor' parameter controls the number of attack rounds (iterations), enabling a continuous control over attack strength.
Notes
- Input: List of uint8 RGB images [H, W, 3], range [0, 255]
- Output: List of regenerated images, same shape and dtype
- Each round uses the same fixed noise timestep (self.noise_step)
- 'factor' specifies the number of iterations (attack strength)
Example
from watermarklab.attackers.testattackers.regeneration import MultiDiffuseAttack
attack = MultiDiffuseAttack(model_id='stabilityai/stable-diffusion-2-1-base', noise_step=30, noisename='MultiDiffuseAttack')Constructor(self, model_id: str = 'stabilityai/stable-diffusion-2-1-base', noise_step: int = 30, noisename: str = 'MultiDiffuseAttack')#
Initializes the multi-step diffusion attack.
Parameters
noise_stepintFixed diffusion timestep for noise injection in each round, range [1, 200].
noisenamestrName identifier for logging and reporting.
attack(self, stego_imgs: List[ndarray], cover_img: List[ndarray] = None, factor: int = 1) -> List[ndarray]#
Applies multiple rounds of diffusion regeneration attack to a batch of stego images.
The attack pipeline is:
For round in range(factor):
x = DiffuseAttack(x, factor=self.noise_step)
Each round adds noise and regenerates the image, progressively distorting watermark signals.
Parameters
stego_imgsList[ndarray]Batch of watermarked images, each of shape [H, W, 3], dtype=uint8, range [0,255].
cover_imgList[ndarray], optionalCover images (ignored, for interface compatibility).
factorintNumber of attack rounds (>=1). More rounds = stronger attack.
Returns
List[ndarray]Final images after factor rounds of diffusion attack, same shape and dtype as inputs.
Example
# method of MultiDiffuseAttack
attack.attack(stego_imgs=stego_imgs, cover_img=None, factor=1)Differentiable attackers
watermarklab.attackers.diffattackers.diffattackers
watermarklab/attackers/diffattackers/diffattackers.pyclassIdentity(BaseDiffAttackModel)#
A no-op attacker that returns its input image unchanged.
It provides a differentiable pass-through for the diffusion-attacker pipeline and acts as the neutral baseline: no distortion is applied and no factor value influences the result.
Example
from watermarklab.attackers.diffattackers.diffattackers import Identity
attack = Identity(test=False, max_step=100, noisename='Identity')Constructor(self, test: bool = False, max_step: int = 100, noisename: str = 'Identity')#
Initialize the Identity attacker.
Parameters
testboolKept for interface compatibility; not used (default: False).
max_stepintKept for interface compatibility; not used (default: 100).
noisenamestrIdentifier name for this attack type (default: "Identity").
forward(self, marked_img, cover_img: Tensor = None, now_step: int = 0)#
Return the input image unchanged during training.
Parameters
marked_imgTensorInput stego/marked image of shape [N, C, H, W].
cover_imgTensor, optionalCover image; ignored.
now_stepintCurrent training step; ignored.
Returns
TensorThe unmodified `marked_img`.
Example
# method of Identity
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img, cover_img: Tensor = None, now_step: int = 0)#
Return the input image unchanged during evaluation.
Parameters
marked_imgTensorInput stego/marked image of shape [N, C, H, W].
cover_imgTensor, optionalCover image; ignored.
now_stepintCurrent evaluation step; ignored.
Returns
TensorThe unmodified `marked_img`.
Example
# method of Identity
attack.test(marked_img=marked_img, cover_img=None, now_step=0)classMeanFilter(BaseDiffAttackModel)#
A differentiable mean (average) filtering attack that applies a uniform averaging kernel to smooth the image.
This simulates common image denoising or blurring operations that may degrade high-frequency watermark signals, testing robustness against low-pass filtering.
Example
from watermarklab.attackers.diffattackers.diffattackers import MeanFilter
attack = MeanFilter(noise_name='MeanFilter', kernel_size_range=(3, 7))Constructor(self, noise_name: str = 'MeanFilter', kernel_size_range: tuple = (3, 7))#
Initialize the MeanFilter attack module.
Parameters
noise_namestrIdentifier name for this attack type.
kernel_size_rangetuple of intRange [min, max] of kernel sizes (must be odd positive integers). Example: (3, 7) → randomly choose kernel size from {3, 5, 7}.
test(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, factor: float = None) -> torch.Tensor#
Apply differentiable mean filtering to input images.
Parameters
stego_imgtorch.TensorInput tensor of shape [N, C, H, W], values in [0, 1].
cover_imgtorch.Tensor, optionalCover image (ignored for compatibility).
factorfloat, optionalNot used; kernel size is randomly sampled per batch.
Returns
torch.TensorMean-filtered image of shape [N, C, H, W].
Example
# method of MeanFilter
attack.test(stego_img=stego_image, cover_img=None, factor=None)forward(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Forward pass during training (delegates to test method).
Parameters
stego_imgtorch.TensorInput stego image tensor.
cover_imgtorch.Tensor, optionalCover image (ignored).
now_stepintCurrent training step (ignored).
Returns
Output from test() method.
Example
# method of MeanFilter
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)classRegionZoom(BaseDiffAttackModel)#
A differentiable local zoom (region magnification) attack that randomly selects a sub-region of the image and magnifies it to full size using differentiable interpolation.
This simulates cropping-and-zooming operations that may occur during image editing or social media processing, testing the watermark's robustness against local content magnification.
Example
from watermarklab.attackers.diffattackers.diffattackers import RegionZoom
attack = RegionZoom(noise_name='RegionZoom', zoom_factor_range=(1.5, 3.0), min_crop_size=32)Constructor(self, noise_name: str = 'RegionZoom', zoom_factor_range: tuple = (1.5, 3.0), min_crop_size: int = 32)#
Initialize the LocalZoom attack module.
Parameters
noise_namestrIdentifier name for this attack type.
zoom_factor_rangetuple of floatRange [min, max] of zoom factor (>1.0). Effective crop size = full_size / zoom_factor.
min_crop_sizeintMinimum allowed crop size (in pixels) to avoid extreme zoom.
test(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, factor: torch.Tensor = None) -> torch.Tensor#
Apply differentiable local zoom attack to input images.
Parameters
stego_imgtorch.TensorInput tensor of shape [N, C, H, W], values in [0, 1].
cover_imgtorch.Tensor, optionalCover image (ignored for compatibility).
factorfloat, optionalGlobal zoom intensity scaling (not used; zoom is randomized per sample).
Returns
torch.TensorZoomed image of shape [N, C, H, W].
Example
# method of RegionZoom
attack.test(stego_img=stego_image, cover_img=None, factor=None)forward(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Forward pass during training (delegates to test method).
Parameters
stego_imgtorch.TensorInput stego image tensor.
cover_imgtorch.Tensor, optionalCover image (ignored).
now_stepintCurrent training step (ignored).
Returns
Output from test() method.
Example
# method of RegionZoom
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)classRandomRotation(BaseDiffAttackModel)#
A differentiable random rotation attack module that randomly rotates images by 90, 180, or 270 degrees.
This attack simulates common image orientation changes that may occur during image processing or transmission, testing the watermark's robustness against 90-degree increments of rotation.
Example
from watermarklab.attackers.diffattackers.diffattackers import RandomRotation
attack = RandomRotation(noise_name='RandomRotation')Constructor(self, noise_name: str = 'RandomRotation')#
Initialize the RandomRotation90 attack module.
Parameters
noise_namestrIdentifier name for this attack type (used for logging/debugging).
test(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, factor: float = None)#
Apply random rotation attack to the input image.
Parameters
stego_imgtorch.TensorInput tensor of shape [N, C, H, W], typically in range [0, 1].
cover_imgtorch.Tensor, optionalCover image (ignored for compatibility with attack interface).
factorfloat, optionalIntensity scaling factor (not used in current implementation).
Returns
torch.TensorRotated image of shape [N, C, H, W].
Example
# method of RandomRotation
attack.test(stego_img=stego_image, cover_img=None, factor=None)forward(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0)#
Forward pass during training (delegates to test method).
Parameters
stego_imgtorch.TensorInput stego image tensor.
cover_imgtorch.Tensor, optionalCover image (ignored).
now_stepintCurrent training step (ignored).
Returns
Output from test() method.
Example
# method of RandomRotation
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)classRandomAffine(BaseDiffAttackModel)#
A differentiable random affine attack module designed for robustness evaluation and supervised training of Spatial Transformer Networks (STNs) or inverse recovery modules.
This module applies geometric distortions via affine transformations and optionally returns ground-truth transformation parameters (and their perturbed inverses) to enable direct supervision or reconstruction-based learning.
Supported attack modes:
- "combined": Composes rotation, isotropic scaling, shear (x or y), and translation
in a single affine matrix, following the parameterization used in
torchvision.transforms.RandomAffine.
- "single": Randomly selects one transformation type (rotation, translation, scaling,
or shear) and applies it uniformly across the entire batch (though with
independently sampled magnitudes per sample).
To increase realism and diversity, the interpolation mode ('nearest', 'bilinear', 'bicubic') and padding behavior ('zeros', 'border', 'reflection') are randomly selected per forward pass if padding_mode='random'.
When return_mode is not "only_transformed", the module returns:
- The forward-transformed image
- An inverse-transformed version (possibly using a perturbed inverse matrix)
- The exact forward affine matrix (
theta) - A simulated "estimated" inverse matrix (
inv_theta), optionally perturbed - Binary masks indicating valid (non-padded) regions after forward and inverse warping
The perturbation on inv_theta (controlled by inv_noise_scale) simulates the imperfect inverse estimation that occurs in practice (e.g., when an STN predicts the inverse transform). This is critical for training models that must handle real-world estimation errors.
Example
from watermarklab.attackers.diffattackers.diffattackers import RandomAffine
attack = RandomAffine(degrees=60.0, translate=(0.3, 0.3), scale=(0.7, 1.3), shear=30.0, attack_mode='combined', return_mode='only_transformed', padding_mode='zeros', noise_name='RandomAffine', inv_noise_scale=0.0)Constructor(self, degrees: float = 60.0, translate: Tuple[float, float] = (0.3, 0.3), scale: Tuple[float, float] = (0.7, 1.3), shear: float = 30.0, attack_mode: str = 'combined', return_mode: str = 'only_transformed', padding_mode: str = 'zeros', noise_name: str = 'RandomAffine', inv_noise_scale: float = 0.0)#
Initializes the differentiable random affine attack module.
Parameters
degreesfloatMaximum absolute rotation angle in degrees. The actual rotation angle for each sample is uniformly sampled from [-degrees, +degrees]. Larger values induce stronger geometric distortion.
translateTuple[float, float]Maximum translation as a fraction of the image width (horizontal) and height (vertical). For example, (0.3, 0.3) allows shifts up to ±30% of the image dimensions. Translations are converted to the normalized coordinate system [-1, 1] used by PyTorch's grid_sample.
scaleTuple[float, float]Range for isotropic scaling factor. A value of 1.0 means no scaling. Values < 1 zoom in (magnify), > 1 zoom out (shrink). Sampled uniformly per sample.
shearfloatMaximum shear angle in degrees. Shear is applied along either the x-axis or y-axis, chosen randomly per sample. This simulates slanted or skewed perspectives.
attack_modestrStrategy for composing transformations:
- "combined": All four transforms (rotation, scale, shear, translation) are
composed into a single affine matrix (default).
- "single": Only one transform type is applied per forward pass (selected randomly
once per batch, but parameters vary per sample).
return_modestrControls the output format:
- "only_transformed": Returns only the distorted image (standard attack mode).
- "only_transformed_back": Returns the image after forward + inverse transformation.
Useful for evaluating reconstruction quality.
- "with_factors": Returns a tuple containing transformed image, reconstructed image,
forward matrix (theta), perturbed inverse matrix (inv_theta), and binary validity masks for both directions.
padding_modestrBehavior for sampling outside the image boundaries:
- 'zeros': Pad with zeros.
- 'border': Replicate edge pixels.
- 'reflection': Reflect around image edges.
- 'random': Randomly select one of the above per forward pass to increase diversity.
noise_namestrA human-readable identifier for logging, debugging, or attack registry purposes.
inv_noise_scalefloatStandard deviation of zero-mean Gaussian noise added to the exact inverse affine matrix (inv_theta) to simulate estimation error (e.g., from a learned STN).
- Set to 0.0 to disable perturbation (perfect inverse).
- Typical values: 0.01–0.02 to match MSE ~1e-4 to 4e-4 in parameter space.
test(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, factor: float = None)#
Applies a differentiable random affine attack to the input image.
This method: 1. Samples a random affine transformation (theta) 2. Warps the input image using F.affine_grid and F.grid_sample 3. Optionally computes an inverse warp (with perturbed inv_theta) 4. Returns images, parameters, and masks as specified by return_mode
The forward and inverse warps use independent sampling modes and padding behaviors (except the inverse always uses 'nearest' and 'zeros' for stability).
Parameters
stego_imgtorch.TensorInput tensor of shape [N, C, H, W], with values typically in [0, 1].
cover_imgtorch.Tensor, optionalIgnored. Included for compatibility with generic attack interfaces.
factorfloat, optionalIgnored. Reserved for future intensity modulation.
Returns
Depending on return_mode:
- "only_transformed":
transformed (torch.Tensor) — distorted image.
- "only_transformed_back":
inv_img (torch.Tensor) — image after forward + inverse warp.
- "with_factors":
Tuple of ( transformed, # forward-warped image inv_img, # reconstructed image theta, # ground-truth forward affine matrix [N, 2, 3] inv_theta, # perturbed inverse matrix [N, 2, 3] transformed_mask, # binary mask of valid pixels after forward warp inv_mask # binary mask after inverse warp )
Example
# method of RandomAffine
attack.test(stego_img=stego_image, cover_img=None, factor=None)forward(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0)#
Forward pass during training or evaluation.
Delegates to the test method for consistency between training and testing behavior.
Parameters
stego_imgtorch.TensorInput stego image tensor of shape [N, C, H, W].
cover_imgtorch.Tensor, optionalUnused (for interface compatibility).
now_stepintCurrent training step (unused).
Returns
Output from the test method.
Example
# method of RandomAffine
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)classRandomTranslation(BaseDiffAttackModel)#
A differentiable random translation distortion layer that randomly shifts the input image horizontally and/or vertically by a percentage of its width/height.
Uses affine transformation for more accurate translation.
Example
from watermarklab.attackers.diffattackers.diffattackers import RandomTranslation
attack = RandomTranslation(max_hshift_percent=0.1, max_vshift_percent=0.1, padding_mode='zeros', noise_name='RandomTranslation')Constructor(self, max_hshift_percent: float = 0.1, max_vshift_percent: float = 0.1, padding_mode: str = 'zeros', noise_name: str = 'RandomTranslation')#
Initialize the RandomTranslationDistortion layer.
Parameters
max_hshift_percentfloat - Max horizontal shift as fraction of width (0.0 ~ 1.0).
max_vshift_percentfloat - Max vertical shift as fraction of height (0.0 ~ 1.0).
padding_modestr - Padding mode: 'zeros', 'border', 'reflection'.
noise_namestr - Name for the noise model.
forward(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Apply random translation to the input image.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used.
now_stepint - Current training step (unused).
Returns
- Tensor - Translated image tensor with shape (N, C, H, W).
Example
# method of RandomTranslation
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: torch.Tensor, cover_img: torch.Tensor = None, factor: float = None) -> torch.Tensor#
Apply random horizontal and vertical translations using affine transformation.
Parameters
stego_imgTensor - Input image tensor (N, C, H, W).
cover_imgTensor - Ignored.
factorfloat - Optional scaling factor for shift magnitude (e.g., 1.0 for max).
Returns
- Tensor - Distorted image after random translation.
Example
# method of RandomTranslation
attack.test(stego_img=stego_image, cover_img=None, factor=None)classSpeckleNoise(BaseDiffAttackModel)#
A differentiable speckle noise layer that adds multiplicative noise to the input image.
Attributes
factorfloat - The intensity of the speckle noise. Higher values result in more noise. Typically, factor should range from 0.1 to 1.0.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import SpeckleNoise
attack = SpeckleNoise(sigma=0.5, max_step=1000, noisename='SpeckleNoise')Constructor(self, sigma: float = 0.5, max_step: int = 1000, noisename: str = 'SpeckleNoise')#
Initialize the SpeckleNoise layer.
Parameters
factorfloat - The intensity of the speckle noise (default: 0.5).
max_stepint - Maximum number of steps for dynamic factor scaling (default: 1000).
noisenamestr - Name of the noise model (default: "SpeckleNoise").
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply speckle noise with a dynamically adjusted factor based on now_step.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for scaling the noise factor.
Returns
- Tensor - The noisy image tensor with shape (N, C, H, W).
Example
# method of SpeckleNoise
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, factor: float = None) -> Tensor#
Apply speckle noise with a specified factor.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
factorfloat - The intensity of the speckle noise.
Returns
- Tensor - The noisy image tensor with shape (N, C, H, W).
Example
# method of SpeckleNoise
attack.test(stego_img=stego_image, cover_img=None, factor=None)classColorQuantization(BaseDiffAttackModel)#
Color quantization reduces the number of colors in an image by approximating pixel values to the nearest multiple of the factor. This is a fully differentiable version using a soft quantization approach in PyTorch.
Attributes
factorint - The maximum quantization factor. Higher values result in more color reduction (fewer distinct colors). Typically, factor should range from 4 to 32.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import ColorQuantization
attack = ColorQuantization(factor=16, max_step=1000, noisename='ColorQuantization')Constructor(self, factor: int = 16, max_step: int = 1000, noisename: str = 'ColorQuantization')#
Initialize the differentiable ColorQuantization class.
Parameters
factorint - The maximum quantization factor (typically 4 to 32).
max_stepint - Maximum number of steps for dynamic factor scaling in forward.
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable color quantization with a dynamically adjusted factor based on now_step, delegating the core computation to the test method.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for scaling the quantization factor.
Returns
- Tensor - The color-quantized image tensor with shape (N, C, H, W).
Example
# method of ColorQuantization
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, factor = None) -> Tensor#
Core computation for color quantization with a specified factor using a differentiable soft quantization approximation.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
factorfloat - The quantization factor determining color reduction.
Returns
- Tensor - The color-quantized image tensor with shape (N, C, H, W).
Example
# method of ColorQuantization
attack.test(stego_img=stego_image, cover_img=None, factor=None)classChromaticAberration(BaseDiffAttackModel)#
Chromatic aberration introduces a color distortion effect by shifting the red and blue channels. This is a differentiable version implemented using PyTorch. For grayscale images (C=1), the effect is skipped, returning the input unchanged.
Attributes
factorint - The maximum shift amount for the red and blue channels. The higher the factor, the greater the shift. Typically, factor should range from 1 to 10.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import ChromaticAberration
attack = ChromaticAberration(factor=2, max_step=1000, noisename='ChromaticAberration')Constructor(self, factor: int = 2, max_step: int = 1000, noisename: str = 'ChromaticAberration')#
Initialize the differentiable ChromaticAberration class.
Parameters
factorint - The maximum shift amount in pixels (typically 1 to 10).
max_stepint - Maximum number of steps for dynamic factor scaling in forward.
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable chromatic aberration with a dynamically adjusted shift based on now_step, delegating the core computation to the test method.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W), where C=1 (grayscale) or C=3 (RGB).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for scaling the shift factor.
Returns
- Tensor - The image tensor with chromatic aberration (RGB) or unchanged (grayscale), shape (N, C, H, W).
Example
# method of ChromaticAberration
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, factor = None) -> Tensor#
Core computation for chromatic aberration with a specified shift factor. For grayscale images (C=1), returns the input unchanged.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W), where C=1 or C=3.
cover_imgTensor - Optional, not used in this implementation.
factorint - The number of pixels to shift the red and blue channels.
Returns
- Tensor - The image tensor with chromatic aberration (RGB) or unchanged (grayscale), shape (N, C, H, W).
Example
# method of ChromaticAberration
attack.test(stego_img=stego_image, cover_img=None, factor=None)classGammaCorrection(BaseDiffAttackModel)#
Gamma correction adjusts the brightness of an image using a gamma curve. This is a differentiable version implemented using PyTorch.
Attributes
factorfloat - The maximum gamma value. A value > 1 brightens the image, a value < 1 darkens it. Typically, factor should range from 0.1 to 3.0.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import GammaCorrection
attack = GammaCorrection(factor=0.5, max_step=1000, noisename='GammaCorrection')Constructor(self, factor: float = 0.5, max_step: int = 1000, noisename: str = 'GammaCorrection')#
Initialize the differentiable GammaCorrection class.
Parameters
factorfloat - The maximum gamma value for brightness adjustment (typically 0.1 to 3.0).
max_stepint - Maximum number of steps for dynamic factor scaling in forward.
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable gamma correction with a dynamically adjusted factor based on now_step, delegating the core computation to the test method.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for scaling the gamma factor.
Returns
- Tensor - The gamma-corrected image tensor with shape (N, C, H, W).
Example
# method of GammaCorrection
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, gamma = None) -> Tensor#
Core computation for gamma correction with a specified factor.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
gammafloat - The gamma value for brightness adjustment.
Returns
- Tensor - The gamma-corrected image tensor with shape (N, C, H, W).
Example
# method of GammaCorrection
attack.test(stego_img=stego_image, cover_img=None, gamma=None)classPoissonNoise(BaseDiffAttackModel)#
A differentiable Poisson noise layer that adds Poisson-distributed noise to the input image.
Attributes
factorfloat - The intensity of the Poisson noise. Higher values result in more noise. Typically, factor should range from 0.1 to 10.0.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import PoissonNoise
attack = PoissonNoise(factor=0.3, max_step=1000, noisename='PoissonNoise')Constructor(self, factor: float = 0.3, max_step: int = 1000, noisename: str = 'PoissonNoise')#
Initialize the PoissonNoise layer.
Parameters
factorfloat - The intensity of the Poisson noise (default: 1.0).
max_stepint - Maximum number of steps for dynamic factor scaling (default: 1000).
noisenamestr - Name of the noise model (default: "PoissonNoise").
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply Poisson noise with a dynamically adjusted factor based on now_step.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for scaling the noise factor.
Returns
- Tensor - The noisy image tensor with shape (N, C, H, W).
Example
# method of PoissonNoise
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, factor: float = None) -> Tensor#
Apply Poisson noise with a specified factor.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
factorfloat - The intensity of the Poisson noise.
Returns
- Tensor - The noisy image tensor with shape (N, C, H, W).
Example
# method of PoissonNoise
attack.test(stego_img=stego_image, cover_img=None, factor=None)classMotionBlur(BaseDiffAttackModel)#
Motion blur applies a blur effect that simulates the effect of camera motion. This is a differentiable version implemented using PyTorch with a randomized factor.
Attributes
factorint - The maximum size of the kernel used for the motion blur. The higher the value, the more pronounced the blur effect. Typically, factor should be between 3 and 15.
max_stepint - Maximum number of steps for dynamic factor scaling.
noisenamestr - Name of the noise model (inherited from BaseDiffAttackModel).
Example
from watermarklab.attackers.diffattackers.diffattackers import MotionBlur
attack = MotionBlur(factor=5, max_step=1000, noisename='MotionBlur')Constructor(self, factor: int = 5, max_step: int = 1000, noisename: str = 'MotionBlur')#
Initialize the differentiable MotionBlur class.
Parameters
factorint - The maximum kernel size for the motion blur (typically 3 to 15).
max_stepint - Maximum number of steps for dynamic factor scaling in forward.
noisenamestr - Name of the noise model (default: "MotionBlur").
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable motion blur with a dynamically adjusted and randomized kernel size based on now_step, delegating the core computation to the test method.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for scaling the maximum motion blur kernel size.
Returns
- Tensor - The motion-blurred image tensor with shape (N, C, H, W).
Example
# method of MotionBlur
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, factor = None) -> Tensor#
Core computation for motion blur with a specified kernel size and randomly chosen direction.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
factorint - The kernel size for the motion blur (larger values increase blur).
Returns
- Tensor - The motion-blurred image tensor with shape (N, C, H, W).
Example
# method of MotionBlur
attack.test(stego_img=stego_image, cover_img=None, factor=None)classContrast(BaseDiffAttackModel)#
Contrast adjustment modifies the contrast of an image with a factor sampled from [1-contrast_factor, 1+contrast_factor]. This ensures a differentiable transformation inspired by torchvision.transforms.ColorJitter.
Attributes
contrast_factorfloat - Maximum absolute value of contrast adjustment.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import Contrast
attack = Contrast(contrast_factor=0.15, max_step=100, noisename='Contrast')Constructor(self, contrast_factor: float = 0.15, max_step: int = 100, noisename: str = 'Contrast')#
Initialize the Contrast transformation.
Parameters
contrast_factorfloat - The maximum absolute value of contrast adjustment.
max_stepint - Maximum step count to control contrast scaling.
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable contrast adjustment with a dynamically adjusted factor.
Parameters
marked_imgTensor - Input image tensor with shape (N, C, H, W), assumed in [0, 1] range.
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for dynamic adjustment of contrast factor.
Returns
- Tensor - Contrast-adjusted image tensor, clamped to [0, 1].
Example
# method of Contrast
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, contrast_factor = None) -> Tensor#
Apply the contrast transformation in test mode.
Parameters
marked_imgTensor - Input image tensor with shape (N, C, H, W), assumed in [0, 1] range.
cover_imgTensor - Optional, not used in this implementation.
contrast_factorfloat - The contrast multiplier in [1-A, 1+A].
Returns
- Tensor - Contrast-adjusted image tensor, clamped to [0, 1].
Example
# method of Contrast
attack.test(marked_img=marked_img, cover_img=None, contrast_factor=None)classUnsharpMasking(BaseDiffAttackModel)#
A differentiable unsharp-masking (sharpening) attack that amplifies high-frequency detail by adding a scaled copy of the image's residual (image minus Gaussian blur).
`amount sets the maximum sharpening strength, sigma the Gaussian blur scale used to build the residual, and threshold the residual magnitude below which detail is discarded. In forward the effective amount ramps from 0 to amount as now_step` grows, so a higher factor gives stronger sharpening.
Example
from watermarklab.attackers.diffattackers.diffattackers import UnsharpMasking
attack = UnsharpMasking(amount=5, sigma=3.0, threshold=0, max_step=1000, noisename='UnsharpMasking')Constructor(self, amount: float = 5, sigma: float = 3.0, threshold: float = 0, max_step: int = 1000, noisename: str = 'UnsharpMasking')#
Initialize the differentiable UnsharpMasking class.
Parameters
amountfloat - amount for unsharp masking.
sigmafloat - Standard deviation of the Gaussian kernel.
thresholdfloat - Threshold for edge enhancement.
devicestr - Computation device ("cpu" or "cuda").
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable Unsharp Masking distortion to the stego image.
Parameters
stego_imgTensor - Input image tensor with shape (B, C, H, W) or (C, H, W).
cover_imgTensor - Optional, not used in this implementation.
amountfloat - Sharpening strength factor.
Returns
result_imgTensor - Sharpened image tensor after unsharp masking.
Example
# method of UnsharpMasking
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, amount = None) -> Tensor#
Apply differentiable Unsharp Masking distortion to the stego image.
Parameters
stego_imgTensor - Input image tensor with shape (B, C, H, W) or (C, H, W).
cover_imgTensor - Optional, not used in this implementation.
amountfloat - Sharpening strength factor.
Returns
result_imgTensor - Sharpened image tensor after unsharp masking.
Example
# method of UnsharpMasking
attack.test(stego_img=stego_image, cover_img=None, amount=None)classGaussianBlur(BaseDiffAttackModel)#
Gaussian blur applies a blur effect to an image using a Gaussian kernel. This is a differentiable version implemented using PyTorch.
Attributes
sigmafloat - The maximum standard deviation of the Gaussian kernel. Higher values result in stronger blur. Typically in the range [0.1, 5.0].
max_stepint - Maximum number of steps for dynamic sigma scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import GaussianBlur
attack = GaussianBlur(sigma=1.5, max_step=1000, noisename='GaussianBlur')Constructor(self, sigma: float = 1.5, max_step: int = 1000, noisename: str = 'GaussianBlur')#
Initialize the differentiable GaussianBlur class.
Parameters
sigmafloat - The maximum standard deviation of the Gaussian kernel.
max_stepint - Maximum step count to control sigma scaling.
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable Gaussian blur with a dynamically adjusted sigma based on now_step, delegating the core computation to the test method.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for dynamic adjustment of sigma.
Returns
- Tensor - Blurred image tensor with shape (N, C, H, W).
Example
# method of GaussianBlur
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, sigma = None) -> Tensor#
Core computation for Gaussian blur with a specified sigma.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used in this implementation.
sigmafloat - The standard deviation of the Gaussian kernel.
Returns
- Tensor - Blurred image tensor with shape (N, C, H, W).
Example
# method of GaussianBlur
attack.test(stego_img=stego_image, cover_img=None, sigma=None)classBrightness(BaseDiffAttackModel)#
Brightness adjustment modifies the intensity of an image with a factor sampled from [-brightness_factor, brightness_factor], applied as a multiplicative scaling from [1-brightness_factor, 1+brightness_factor]. This ensures a differentiable transformation inspired by torchvision.transforms.ColorJitter.
Attributes
brightness_factorfloat - Maximum absolute value of brightness adjustment.
max_stepint - Maximum number of steps for dynamic factor scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import Brightness
attack = Brightness(brightness_factor=0.15, max_step=100, noisename='Brightness')Constructor(self, brightness_factor: float = 0.15, max_step: int = 100, noisename: str = 'Brightness')#
Initialize the Brightness transformation.
Parameters
brightness_factorfloat - The maximum absolute value of brightness range (non-negative).
max_stepint - Maximum step count to control brightness scaling.
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply differentiable brightness adjustment with a dynamically adjusted factor.
Parameters
marked_imgTensor - Input image tensor with shape (N, C, H, W), assumed in [0, 1] range.
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for dynamic adjustment of brightness factor.
Returns
- Tensor - Brightness-adjusted image tensor, clamped to [0, 1].
Example
# method of Brightness
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, brightness_factor = None) -> Tensor#
Apply the brightness transformation in test mode.
Parameters
marked_imgTensor - Input image tensor with shape (N, C, H, W), assumed in [0, 1] range.
cover_imgTensor - Optional, not used in this implementation.
brightness_factorfloat - The brightness multiplier in [1-A, 1+A].
Returns
- Tensor - Brightness-adjusted image tensor, clamped to [0, 1].
Example
# method of Brightness
attack.test(marked_img=marked_img, cover_img=None, brightness_factor=None)classMedianFilter(BaseDiffAttackModel)#
A class that applies a median filter to images for noise reduction.
The median filter is useful for removing noise while preserving edges. It operates by replacing each pixel's value with the median value of the neighboring pixels defined by a kernel.
Attributes
kernelintThe size of the kernel for the median filter (should be odd).
max_stepintThe maximum number of steps for dynamic adjustment (not currently used).
Example
from watermarklab.attackers.diffattackers.diffattackers import MedianFilter
attack = MedianFilter(kernel=7, max_step=100, noisename='MedianFilter')Constructor(self, kernel: int = 7, max_step: int = 100, noisename: str = 'MedianFilter')#
Initializes the MedianFilter class with specified parameters.
Parameters
kernelintThe size of the kernel for the median filter (default is 7).
max_stepintThe maximum number of steps for dynamic adjustment (default is 100).
forward(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Applies the median filter to the input marked image.
The method randomly decides whether to apply the median filter based on the defined probability. If in test mode, the filter is always applied.
Parameters
marked_imgtorch.TensorThe input image tensor to which the median filter will be applied.
cover_imgtorch.Tensor, optionalThe cover image tensor (not used in this method).
now_stepintThe current step in the training process (not currently used).
Returns
torch.TensorThe resulting image after applying the median filter.
Example
# method of MedianFilter
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, kernel = None) -> torch.Tensor#
Applies the median filter to the input image tensor for testing.
Parameters
marked_imgtorch.TensorThe input image tensor.
cover_imgtorch.Tensor, optionalAn optional cover image tensor (not used in this method).
kernelintThe kernel size to use for the median filter (default is 7).
Returns
torch.TensorThe resulting image after applying the median filter, clamped to [0, 1].
Example
# method of MedianFilter
attack.test(marked_img=marked_img, cover_img=None, kernel=None)classSaturation(BaseDiffAttackModel)#
A differentiable saturation attack that rescales image chroma with torchvision's `adjust_saturation`.
`saturation_factor bounds the random offset sampled uniformly from [-saturation_factor, saturation_factor] in forward (ramped by now_step); the applied multiplier is 1 + factor`, so a positive factor boosts saturation, a negative factor desaturates, and a larger factor means a stronger colour shift.
Example
from watermarklab.attackers.diffattackers.diffattackers import Saturation
attack = Saturation(saturation_factor=0.15, max_step=100, noisename='Saturation')Constructor(self, saturation_factor: float = 0.15, max_step: int = 100, noisename: str = 'Saturation')#
Initialize the Saturation transformation.
Parameters
saturation_factorfloatBase factor for adjusting saturation. Should be in the range [0, ∞), where 1 means no change.
max_stepintThe maximum number of steps for dynamic adjustment.
forward(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Apply the saturation transformation.
Parameters
marked_imgtorch.TensorThe input image tensor.
cover_imgtorch.Tensor, optionalAn optional cover image tensor (not used in this transform).
now_stepintThe current step in the training process.
Returns
torch.TensorThe transformed image.
Example
# method of Saturation
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, saturation_factor = None) -> torch.Tensor#
Apply the saturation transformation in test mode.
Parameters
marked_imgtorch.TensorThe input image tensor.
cover_imgtorch.Tensor, optionalAn optional cover image tensor (not used in this transform).
saturation_factorfloatThe saturation adjustment factor.
Returns
torch.TensorThe transformed image.
Example
# method of Saturation
attack.test(marked_img=marked_img, cover_img=None, saturation_factor=None)classHue(BaseDiffAttackModel)#
Hue adjustment modifies the hue of an image by applying a transformation based on a factor. The hue factor ranges from [-0.5, 0.5], where 0 means no change, and the factor is dynamically adjusted based on the training step.
Attributes
hue_factorfloat - The maximum hue adjustment factor.
max_stepint - Maximum number of steps for dynamic scaling.
Example
from watermarklab.attackers.diffattackers.diffattackers import Hue
attack = Hue(hue_factor=0.1, max_step=100, noisename='Hue')Constructor(self, hue_factor: float = 0.1, max_step: int = 100, noisename: str = 'Hue')#
Initialize the Hue transformation.
Parameters
hue_factorfloat - The maximum hue adjustment factor, should be in the range [-0.5, 0.5].
max_stepint - Maximum number of steps for dynamic scaling.
forward(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Apply the hue transformation with a dynamically adjusted factor.
Parameters
marked_imgTensor - Input image tensor with shape (N, C, H, W), assumed in [0, 1] range.
cover_imgTensor - Optional, not used in this implementation.
now_stepint - Current step for dynamic adjustment of the hue factor.
Returns
- Tensor - Hue-adjusted image tensor, clamped to [0, 1].
Example
# method of Hue
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, factor = None) -> torch.Tensor#
Apply the hue transformation in test mode by modifying the image's hue channel.
Parameters
marked_imgTensor - Input image tensor with shape (N, C, H, W), assumed in [0, 1] range.
cover_imgTensor - Optional, not used in this implementation.
hue_factorfloat - The hue factor to apply during testing.
Returns
- Tensor - Hue-adjusted image tensor, clamped to [0, 1].
Example
# method of Hue
attack.test(marked_img=marked_img, cover_img=None, factor=None)classRandomFlipping(BaseDiffAttackModel)#
A differentiable random flip distortion layer that randomly applies horizontal and/or vertical flips to the input image.
Attributes
p_hflipfloat - Probability of applying horizontal flip (default: 0.5).
p_vflipfloat - Probability of applying vertical flip (default: 0.5).
noisenamestr - Name of the distortion model.
Example
from watermarklab.attackers.diffattackers.diffattackers import RandomFlipping
attack = RandomFlipping(p_hflip=0.5, p_vflip=0.5, noisename='RandomFlipping')Constructor(self, p_hflip: float = 0.5, p_vflip: float = 0.5, noisename: str = 'RandomFlipping')#
Initialize the RandomFlipDistortion layer.
Parameters
p_hflipfloat - Probability of horizontal flip (0.0 to 1.0).
p_vflipfloat - Probability of vertical flip (0.0 to 1.0).
noisenamestr - Name of the noise model.
forward(self, stego_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply random flips to the input image.
Parameters
stego_imgTensor - Input image tensor with shape (N, C, H, W).
cover_imgTensor - Optional, not used.
now_stepint - Current step (unused, kept for interface consistency).
Returns
- Tensor - The flipped (or not) image tensor with shape (N, C, H, W).
Example
# method of RandomFlipping
attack.forward(stego_img=stego_image, cover_img=None, now_step=0)test(self, stego_img: Tensor, cover_img: Tensor = None, factor: float = None) -> Tensor#
Apply random horizontal and vertical flips independently.
Parameters
stego_imgTensor - Input image tensor (N, C, H, W).
cover_imgTensor - Ignored.
factorfloat - Ignored (for API compatibility).
Returns
- Tensor - Distorted image after random flips.
Example
# method of RandomFlipping
attack.test(stego_img=stego_image, cover_img=None, factor=None)classCrop(BaseDiffAttackModel)#
A differentiable crop attack that keeps a randomly placed rectangular region of the marked image and fills the remainder with the cover image or a constant.
`retain_ratio (clamped to [0, 1]) is the maximum fraction of the image area kept as that rectangle, mode selects "cover_pad" or "constant_pad", and constant is the fill value. In test the factor` is the retained-area ratio, so a larger factor keeps more of the original image and therefore distorts it less.
Example
from watermarklab.attackers.diffattackers.diffattackers import Crop
attack = Crop(retain_ratio=0.7, mode='constant_pad', constant=0.0, max_step=100, noisename='Crop')Constructor(self, retain_ratio = 0.7, mode = 'constant_pad', constant: float = 0.0, max_step: int = 100, noisename: str = 'Crop')#
Initializes the Crop layer.
Parameters
retain_ratiofloatimage retain ratio of the image to be retained.
modestrThe mode of operation, either 'cover_pad' or 'constant_pad'.
constantfloatConstant value used in 'constant_pad' mode.
max_stepintThe maximum number of steps for dynamic adjustment.
noisenamestrName of the noise model.
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Apply the Crop operation to the input image. The crop ratio is dynamically adjusted based on the current step.
Parameters
marked_imgTensorThe marked image tensor.
cover_imgTensorThe cover image tensor (used when mode is 'cover_pad').
now_stepintCurrent step in the training process.
Returns
TensorThe resulting image after applying Crop.
Example
# method of Crop
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, factor: float = None) -> Tensor#
Apply the Crop operation for testing with a fixed crop ratio.
Parameters
marked_imgTensorThe marked image tensor.
cover_imgTensorThe cover image tensor (used when mode is 'cover_pad').
factorfloatThe ratio of the image area to be cropped out.
Returns
TensorThe resulting image after applying Crop.
Example
# method of Crop
attack.test(marked_img=marked_img, cover_img=None, factor=None)random_cropout_mask(self, marked_img: Tensor, crop_ratio: float) -> Tensor#
Generate a mask for Cropout operation, where a rectangular region in the middle of the image is cropped out.
Parameters
marked_imgTensorInput tensor of shape (N, C, H, W), where N is the batch size, C is the number of channels, H is the height, and W is the width.
crop_ratiofloatThe ratio of the image area to be cropped out.
Returns
TensorA mask of shape (N, C, H, W) with values 1 for the visible area and 0 for the cropped-out region.
Example
# method of Crop
attack.random_cropout_mask(marked_img=marked_img, crop_ratio=0.5)classCropout(BaseDiffAttackModel)#
A differentiable cropout attack that erases a randomly placed rectangular region of the marked image and replaces it with the cover image or a constant value.
`crop_ratio (clamped to [0, 1]) is the maximum fraction of the image area removed, mode selects "cover_pad" or "constant", and constant_value is the fill value. The removed fraction ramps up with now_step in forward; in test a larger factor` removes more pixels and gives a stronger attack.
Example
from watermarklab.attackers.diffattackers.diffattackers import Cropout
attack = Cropout(crop_ratio=0.5, max_step=100, noisename='Cropout', mode='constant', constant_value=0)Constructor(self, crop_ratio = 0.5, max_step: int = 100, noisename: str = 'Cropout', mode: str = 'constant', constant_value: float = 0)#
Initializes the Cropout layer.
Parameters
crop_ratiofloatimage retain ratio of the image to be cropped out.
max_stepintThe maximum number of steps for dynamic adjustment.
modestrThe mode to use for filling the cropped area. Options: 'cover_pad' or 'constant'.
constant_valuefloatThe constant value to use for the 'constant' mode.
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Applies the Cropout operation to the input image.
Parameters
marked_imgTensorThe marked image tensor.
cover_imgTensorThe cover image tensor (used when mode is 'cover_pad').
now_stepintCurrent step in the training process.
Returns
TensorThe resulting image after applying Cropout.
Example
# method of Cropout
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, factor: float = None) -> Tensor#
Applies the Cropout operation to the input image during testing.
Parameters
marked_imgTensorThe marked image tensor.
cover_imgTensorThe cover image tensor (used when mode is 'cover_pad').
factorfloatThe ratio of pixels to remain in the marked image.
Returns
TensorThe resulting image after applying Cropout.
Example
# method of Cropout
attack.test(marked_img=marked_img, cover_img=None, factor=None)random_cropout_mask(self, marked_img: Tensor, crop_ratio: float) -> Tensor#
Generate a mask for Cropout operation, where a rectangular region in the middle of the image is cropped out.
Parameters
marked_imgTensorInput tensor of shape (N, C, H, W), where N is the batch size, C is the number of channels, H is the height, and W is the width.
crop_ratiofloatThe ratio of the image area to be cropped out.
Returns
TensorA mask of shape (N, C, H, W) with values 1 for the visible area and 0 for the cropped-out region.
Example
# method of Cropout
attack.random_cropout_mask(marked_img=marked_img, crop_ratio=0.5)classDropout(BaseDiffAttackModel)#
A differentiable dropout attack that replaces randomly chosen pixels of the marked image with the corresponding pixels of the cover image.
`drop_prob (clamped to [0, 1]) is the maximum per-pixel replacement probability. forward scales it by now_step / max_step, so a larger now_step and a larger drop_prob/factor` both mean more pixels are destroyed (a stronger attack).
Example
from watermarklab.attackers.diffattackers.diffattackers import Dropout
attack = Dropout(drop_prob=0.3, max_step=100, noisename='Dropout')Constructor(self, drop_prob = 0.3, max_step: int = 100, noisename: str = 'Dropout')#
Initializes the Dropout layer, which simulates the process of randomly dropping pixels in the image.
Parameters
drop_probfloatProbability of dropping a pixel. Should be between 0 and 1.
max_stepintMaximum number of steps for dynamic adjustment of drop probability during training.
noisenamestrThe name of the noise model.
forward(self, marked_img: Tensor, cover_image: Tensor = None, now_step: int = 0) -> Tensor#
Applies the Dropout operation to the input image by randomly dropping pixels.
Parameters
marked_imgTensorThe marked image tensor that contains the information to be distorted.
cover_imageTensorThe cover image tensor used to replace the dropped pixels when using the 'cover_pad' mode.
now_stepintCurrent step in the training process, used to dynamically adjust drop probability.
Returns
TensorThe resulting image after applying dropout.
Example
# method of Dropout
attack.forward(marked_img=marked_img, cover_image=None, now_step=0)test(self, marked_img: Tensor, cover_image: Tensor, drop_prob = None) -> Tensor#
Applies the Dropout operation to the input image during testing.
Parameters
marked_imgTensorThe marked image tensor that contains the information to be distorted.
cover_imageTensorThe cover image tensor used for padding the dropped areas.
drop_probfloatProbability of dropping a pixel during testing. Should be between 0 and 1.
Returns
TensorThe resulting image after applying dropout.
Example
# method of Dropout
attack.test(marked_img=marked_img, cover_image=cover_image, drop_prob=None)classGaussianNoise(BaseDiffAttackModel)#
A differentiable additive white Gaussian noise attack.
`mu and std are the mean and maximum standard deviation of the sampled noise, and intensity scales that noise before it is added to the image. In forward the effective standard deviation ramps from 0 to std as now_step grows; in test a larger std/factor (or intensity`) means stronger distortion.
Example
from watermarklab.attackers.diffattackers.diffattackers import GaussianNoise
attack = GaussianNoise(mu=0, std=1.5, intensity=1.0, max_step=100, noisename='GaussianNoise')Constructor(self, mu: float = 0, std: float = 1.5, intensity: float = 1.0, max_step: int = 100, noisename: str = 'GaussianNoise')#
Initializes the GaussianNoise layer, which adds Gaussian noise to the image.
Parameters
mufloatMean of the Gaussian noise.
stdfloatStandard deviation of the Gaussian noise.
intensityfloatMaximum intensity of the noise.
max_stepintMaximum number of steps for dynamic adjustment of noise.
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Applies Gaussian noise to the input image during training.
Parameters
marked_imgTensorThe input image to which noise will be added.
cover_imgTensor, optionalNot used in this implementation.
now_stepintCurrent step to adjust noise standard deviation.
Returns
TensorThe resulting image after adding Gaussian noise.
Example
# method of GaussianNoise
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, std = None) -> Tensor#
Applies Gaussian noise to the input image during testing.
Parameters
marked_imgTensorThe input image to which noise will be added.
cover_imgTensor, optionalNot used in this implementation.
stdfloatStandard deviation of the Gaussian noise during testing.
Returns
TensorThe resulting noised image.
Example
# method of GaussianNoise
attack.test(marked_img=marked_img, cover_img=None, std=None)classSaltPepperNoise(BaseDiffAttackModel)#
A differentiable salt-and-pepper (impulse) noise attack that sets a fraction of the pixels to 1 ("salt") or 0 ("pepper").
`noise_ratio (clamped to [0, 1]) is the maximum proportion of corrupted pixels and noise_prob is the probability that a corrupted pixel becomes salt rather than pepper. In forward the ratio ramps with now_step; in test a larger noise_ratio/factor` corrupts more pixels and gives a stronger attack.
Example
from watermarklab.attackers.diffattackers.diffattackers import SaltPepperNoise
attack = SaltPepperNoise(noise_ratio=0.1, noise_prob=0.5, max_step=100, noisename='SaltPepperNoise')Constructor(self, noise_ratio: float = 0.1, noise_prob: float = 0.5, max_step: int = 100, noisename: str = 'SaltPepperNoise')#
Initializes the SaltPepperNoise layer.
Parameters
noise_ratiofloatProportion of pixels to be noised (default is 0.1).
noise_probfloatProbability of applying "salt" (1) or "pepper" (0) to the selected pixels (default is 0.5).
max_stepintMaximum number of steps for dynamic adjustment.
apply_noise(self, img: torch.Tensor, noise_ratio: float, noise_mode = 'salt') -> torch.Tensor#
Applies differentiable salt and pepper noise to the input image.
Parameters
imgTensorThe input image (C, H, W).
noise_ratiofloatProportion of pixels to be noised.
noise_modestrMode of noise ("salt" or "pepper").
Returns
TensorThe noised image.
Example
# method of SaltPepperNoise
attack.apply_noise(img=img, noise_ratio=0.5, noise_mode='salt')forward(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, now_step: int = 0) -> torch.Tensor#
Applies differentiable salt and pepper noise to the input image during training.
Parameters
marked_imgTensorThe input image (C, H, W).
cover_imgTensor, optionalA cover image, not used in this implementation.
now_stepintCurrent step to adjust noise ratio.
Returns
TensorThe noised image.
Example
# method of SaltPepperNoise
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: torch.Tensor, cover_img: torch.Tensor = None, noise_ratio = None) -> torch.Tensor#
Applies differentiable salt and pepper noise to the input image during testing.
Parameters
marked_imgTensorThe input image (C, H, W).
cover_imgTensor, optionalNot used in this implementation.
noise_ratiofloatProportion of pixels to be noised during testing.
Returns
TensorThe noised image.
Example
# method of SaltPepperNoise
attack.test(marked_img=marked_img, cover_img=None, noise_ratio=None)classResize(BaseDiffAttackModel)#
Resize the image using a random scaling factor.
Parameters
scale_pfloatscale factor.
probfloatProbability of applying the resizing operation.
modestrInterpolation mode, either 'nearest' or 'bilinear'.
max_stepintMaximum number of steps for dynamic adjustment.
Example
from watermarklab.attackers.diffattackers.diffattackers import Resize
attack = Resize(scale_p=0.8, prob=0.8, mode='bilinear', max_step=100, noisename='Resize')Constructor(self, scale_p: float = 0.8, prob: float = 0.8, mode: str = 'bilinear', max_step: int = 100, noisename: str = 'Resize')#
Initialize the Resize attacker.
Parameters
scale_pfloatMinimum down-scaling factor, clamped to [0.01, 1.0]; the actual factor is drawn uniformly from [scale_p, 1.0] (default: 0.8).
probfloatProbability of applying the resize, clamped to [0.0, 1.0]; stored but not used by `forward/test` (default: 0.8).
modestrInterpolation mode, "nearest" or "bilinear"; any other value falls back to "bilinear" (default: "bilinear").
max_stepintMaximum number of steps for the dynamic scale ramp (default: 100).
noisenamestrIdentifier name for this attack type (default: "Resize").
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> torch.Tensor#
Perform the resizing operation on the input image.
Parameters
marked_imgTensorInput image tensor of shape (N, C, H, W).
cover_imgTensor, optionalNot used in this operation.
now_stepintCurrent step to adjust scale factor.
Returns
TensorResized image tensor of the same shape as the input.
Example
# method of Resize
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, scale_p = None) -> torch.Tensor#
Resizes the input image during testing using a specified scale factor.
Parameters
marked_imgTensorInput image tensor of shape (N, C, H, W).
cover_imgTensor, optionalNot used in this operation.
scale_pfloatScale factor for resizing during testing.
Returns
TensorResized image tensor of the same shape as the input.
Example
# method of Resize
attack.test(marked_img=marked_img, cover_img=None, scale_p=None)classRotate(BaseDiffAttackModel)#
Applies a random rotation to the input image.
Parameters
angleintMaximum rotation angle in degrees (0 to 360).
max_stepintMaximum number of steps for dynamic adjustment.
Example
from watermarklab.attackers.diffattackers.diffattackers import Rotate
attack = Rotate(angle=120, max_step=100, noisename='Rotate')Constructor(self, angle: float = 120, max_step: int = 100, noisename: str = 'Rotate')#
Initialize the Rotate attacker.
Parameters
anglefloatMaximum absolute rotation angle in degrees; `forward samples uniformly from [-angle, angle] after ramping by now_step, while test` uses it directly when no explicit angle is supplied (default: 120).
max_stepintMaximum number of steps for the dynamic angle ramp (default: 100).
noisenamestrIdentifier name for this attack type (default: "Rotate").
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Applies rotation to the input image.
Parameters
marked_imgTensorInput image tensor of shape (N, C, H, W).
cover_imgTensor, optionalNot used in this operation.
now_stepintCurrent step to adjust the rotation angle.
Returns
TensorRotated image tensor with the same shape as input.
Example
# method of Rotate
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)test(self, marked_img: Tensor, cover_img: Tensor = None, angle = None) -> Tensor#
Applies a fixed-angle rotation to the input image during testing.
Parameters
marked_imgTensorInput image tensor of shape (N, C, H, W).
cover_imgTensor, optionalNot used in this operation.
anglefloatRotation angle in degrees.
Returns
TensorRotated image tensor with the same shape as input.
Example
# method of Rotate
attack.test(marked_img=marked_img, cover_img=None, angle=None)classRandomCompensateTransformer(BaseDiffAttackModel)#
A differentiable random perspective (four-corner jitter) attack that simulates the geometric misalignment of photographed or reprinted watermarked images.
`shift_d is the maximum displacement, in pixels, applied to each image corner before the perspective warp. forward uses shift_d * now_step / max_step + 1 as that displacement, so a larger now_step (or shift_d`) produces a stronger warp.
Example
from watermarklab.attackers.diffattackers.diffattackers import RandomCompensateTransformer
attack = RandomCompensateTransformer(shift_d=8, test=False, max_step=100, noisename='RandomCompensateTransformer')Constructor(self, shift_d: int = 8, test: bool = False, max_step: int = 100, noisename: str = 'RandomCompensateTransformer')#
Initializes the RandomCompensateTrans layer.
Parameters
shift_dintMaximum displacement for the image vertices during transformation (in pixels).
testboolWhether the layer is in test mode (not currently used).
max_stepintMaximum number of steps for dynamic adjustment.
forward(self, marked_img: Tensor, cover_img: Tensor = None, now_step: int = 0) -> Tensor#
Applies a random perspective transformation to the input image.
Parameters
marked_imgTensorThe input image tensor of shape (N, C, H, W).
cover_imgTensor, optionalNot used in this operation.
now_stepintCurrent step to adjust the displacement.
Returns
TensorThe transformed image after applying the perspective transformation.
Example
# method of RandomCompensateTransformer
attack.forward(marked_img=marked_img, cover_img=None, now_step=0)perspective(self, marked_img: Tensor, d: int = 8) -> Tensor#
Applies a random perspective transformation to the input batch of images.
Parameters
marked_imgTensorInput batch of images, shape (N, C, H, W).
dintMaximum displacement for the image vertices during transformation.
Returns
TensorThe transformed batch of images with the same shape (N, C, H, W).
Example
# method of RandomCompensateTransformer
attack.perspective(marked_img=marked_img, d=8)classFieldOfViewTransformer(nn.Module)#
A module to apply random affine and perspective transformations to a batch of images. The transformations include rotation, scaling, translation, and perspective warping.
Example
from watermarklab.attackers.diffattackers.diffattackers import FieldOfViewTransformer
attack = FieldOfViewTransformer(max_z_angle=60, max_x_angle=60, max_y_angle=60, max_fov=70, min_fov=60, max_translate_factor=0.2, max_plane_angle=60)Constructor(self, max_z_angle: int = 60, max_x_angle: int = 60, max_y_angle: int = 60, max_fov: int = 70, min_fov: int = 60, max_translate_factor: float = 0.2, max_plane_angle: int = 60)#
Initialize the transformer with maximum transformation parameters.
Parameters
max_z_angleintMaximum rotation angle around the z-axis (in degrees).
max_x_angleintMaximum rotation angle around the x-axis (in degrees).
max_y_angleintMaximum rotation angle around the y-axis (in degrees).
max_fovintMaximum field of view (FOV) for perspective transformation (in degrees).
min_fovintMinimum field of view (FOV) for perspective transformation (in degrees).
max_translate_factorfloatMaximum translation factor as a fraction of image size.
max_plane_angleintMaximum tilt angle for the plane (in degrees).
random_perspective_transform(self, img_shape, angle_xs, angle_ys, angle_zs, field_of_view)#
Generate a perspective transformation matrix based on rotation angles and field of view.
Parameters
img_shapetupleShape of the input image (N, C, H, W).
angle_xstorch.TensorRotation angles around the x-axis (in degrees).
angle_ystorch.TensorRotation angles around the y-axis (in degrees).
angle_zstorch.TensorRotation angles around the z-axis (in degrees).
field_of_viewtorch.TensorField of view for perspective transformation (in degrees).
Returns
torch.TensorPerspective transformation matrix of shape (N, 3, 3).
Example
# method of FieldOfViewTransformer
attack.random_perspective_transform(img_shape=img_shape, angle_xs=angle_xs, angle_ys=angle_ys, angle_zs=angle_zs, field_of_view=field_of_view)transform_points(self, pts, matrix)#
Transform 2D points using a 3x3 transformation matrix.
Parameters
ptstorch.TensorOriginal points of shape (N, 4, 2).
matrixtorch.TensorTransformation matrix of shape (N, 3, 3).
Returns
torch.TensorTransformed points of shape (N, 4, 2).
Example
# method of FieldOfViewTransformer
attack.transform_points(pts=pts, matrix=matrix)forward(self, batch_img: Tensor, current_step: int, reset_step: int, batch_img_mask: Tensor = None, scale_factor: float = 1.1)#
Apply random affine and perspective transformations to the input batch of images.
Parameters
batch_imgtorch.TensorInput batch of images of shape (N, C, H, W).
current_stepintCurrent step in the transformation schedule.
reset_stepintStep interval for resetting the transformation parameters.
batch_img_masktorch.Tensor, optionalOptional mask for the input images of shape (N, C, H, W).
Returns
tupleA tuple containing:
- warped_images (torch.Tensor): Transformed images of shape (N, C, H, W).
- warped_masks (torch.Tensor): Transformed masks of shape (N, C, H, W).
- warped_corners (torch.Tensor): Transformed corner points of shape (N, 4, 2).
:param scale_factor:
Example
# method of FieldOfViewTransformer
attack.forward(batch_img=batch_img, current_step=1, reset_step=1, batch_img_mask=None, scale_factor=1.1)classJpegMask(BaseDiffAttackModel)#
A differentiable JPEG attack whose quantisation rounding is approximated with a straight-through mask rounding function.
Compression is applied end to end during training through `DiffJpeg with round_mode="mask", so gradients still flow through the JPEG step; in test the exact TestJpeg implementation is used instead. The quality factor ramps from 100 down towards Q as now_step grows, so a larger factor (a lower Q`) means stronger compression.
Example
from watermarklab.attackers.diffattackers.diffattackers import JpegMask
attack = JpegMask(Q=50, max_step=100, noisename='JpegMask')Constructor(self, Q: int = 50, max_step: int = 100, noisename: str = 'JpegMask')#
Initialize the Jpeg module.
Parameters
QintJPEG quality factor, clamped between 50 and 100.
max_stepintMaximum number of steps for quality adjustment.
gamma_density(self, Q, shape = 2.0, scale = 1.0)#
Calculate gamma density for quality adjustment.
Parameters
QintQuality factor.
shapefloatShape parameter for the gamma distribution.
scalefloatScale parameter for the gamma distribution.
Returns
List[float]List of gamma density values.
Example
# method of JpegMask
attack.gamma_density(Q=Q, shape=2.0, scale=1.0)forward(self, marked_img: Tensor, cover_img = None, now_step: int = 1)#
Forward pass for JPEG processing with dynamic quality adjustment.
Parameters
marked_imgTensorInput image tensor.
cover_imgTensor, optionalCover image tensor (unused).
now_stepintCurrent step for quality adjustment.
Returns
TensorNoised image tensor after JPEG processing.
Example
# method of JpegMask
attack.forward(marked_img=marked_img, cover_img=None, now_step=1)test(self, marked_img: Tensor, cover_img = None, Q = None)#
Test mode for JPEG processing.
Parameters
marked_imgTensorInput image tensor.
cover_imgTensor, optionalCover image tensor (unused).
QintJPEG quality factor for testing.
Returns
TensorNoised image tensor after JPEG processing.
Example
# method of JpegMask
attack.test(marked_img=marked_img, cover_img=None, Q=None)classJpegPolynomial(BaseDiffAttackModel)#
A differentiable JPEG attack whose quantisation rounding is approximated by a polynomial surrogate.
Identical to `JpegMask except for the rounding surrogate: training uses DiffJpeg with round_mode="polynomial" and evaluation uses the exact TestJpeg. The quality factor ramps from 100 down towards Q as now_step grows, so a larger factor (a lower Q`) means stronger compression.
Example
from watermarklab.attackers.diffattackers.diffattackers import JpegPolynomial
attack = JpegPolynomial(Q=50, max_step=100, noisename='JpegPolynomial')Constructor(self, Q: int = 50, max_step: int = 100, noisename: str = 'JpegPolynomial')#
Initialize the Jpeg module.
Parameters
QintJPEG quality factor, clamped between 50 and 100.
max_stepintMaximum number of steps for quality adjustment.
gamma_density(self, Q, shape = 2.0, scale = 1.0)#
Calculate gamma density for quality adjustment.
Parameters
QintQuality factor.
shapefloatShape parameter for the gamma distribution.
scalefloatScale parameter for the gamma distribution.
Returns
List[float]List of gamma density values.
Example
# method of JpegPolynomial
attack.gamma_density(Q=Q, shape=2.0, scale=1.0)forward(self, marked_img: Tensor, cover_img = None, now_step: int = 1)#
Forward pass for JPEG processing with dynamic quality adjustment.
Parameters
marked_imgTensorInput image tensor.
cover_imgTensor, optionalCover image tensor (unused).
now_stepintCurrent step for quality adjustment.
Returns
TensorNoised image tensor after JPEG processing.
Example
# method of JpegPolynomial
attack.forward(marked_img=marked_img, cover_img=None, now_step=1)test(self, marked_img: Tensor, cover_img = None, Q = None)#
Test mode for JPEG processing.
Parameters
marked_imgTensorInput image tensor.
cover_imgTensor, optionalCover image tensor (unused).
QintJPEG quality factor for testing.
Returns
TensorNoised image tensor after JPEG processing.
Example
# method of JpegPolynomial
attack.test(marked_img=marked_img, cover_img=None, Q=None)classJpegFourier(BaseDiffAttackModel)#
A differentiable JPEG attack whose quantisation rounding is approximated in the Fourier domain.
Identical to `JpegMask except for the rounding surrogate: training uses DiffJpeg with round_mode="fourier" and evaluation uses the exact TestJpeg. The quality factor ramps from 100 down towards Q as now_step grows, so a larger factor (a lower Q`) means stronger compression.
Example
from watermarklab.attackers.diffattackers.diffattackers import JpegFourier
attack = JpegFourier(Q=50, max_step=100, noisename='JpegFourier')Constructor(self, Q: int = 50, max_step: int = 100, noisename: str = 'JpegFourier')#
Initialize the Jpeg module.
Parameters
QintJPEG quality factor, clamped between 50 and 100.
max_stepintMaximum number of steps for quality adjustment.
gamma_density(self, Q, shape = 2.0, scale = 1.0)#
Calculate gamma density for quality adjustment.
Parameters
QintQuality factor.
shapefloatShape parameter for the gamma distribution.
scalefloatScale parameter for the gamma distribution.
Returns
List[float]List of gamma density values.
Example
# method of JpegFourier
attack.gamma_density(Q=Q, shape=2.0, scale=1.0)forward(self, marked_img: Tensor, cover_img = None, now_step: int = 1)#
Forward pass for JPEG processing with dynamic quality adjustment.
Parameters
marked_imgTensorInput image tensor.
cover_imgTensor, optionalCover image tensor (unused).
now_stepintCurrent step for quality adjustment.
Returns
TensorNoised image tensor after JPEG processing.
Example
# method of JpegFourier
attack.forward(marked_img=marked_img, cover_img=None, now_step=1)test(self, marked_img: Tensor, cover_img = None, Q = None)#
Test mode for JPEG processing.
Parameters
marked_imgTensorInput image tensor.
cover_imgTensor, optionalCover image tensor (unused).
QintJPEG quality factor for testing.
Returns
TensorNoised image tensor after JPEG processing.
Example
# method of JpegFourier
attack.test(marked_img=marked_img, cover_img=None, Q=None)classPIMoG(BaseDiffAttackModel)#
A differentiable screen-shooting noise-layer simulation that applies light distortion and Moire pattern interference to the marked image.
This implements the PIMoG noise layer of Fang et al., "PIMoG: An Effective Screen-shooting Noise-Layer Simulation for Deep-Learning-Based Watermarking Network" (ACM MM 2022). The only constructor argument, `noisename, names the layer; the distortion is fully randomized per call and is not driven by a factor`.
Example
from watermarklab.attackers.diffattackers.diffattackers import PIMoG
attack = PIMoG(noisename='ScreenCapture')Constructor(self, noisename = 'ScreenCapture')#
ScreenCapture Class simulates screen-shooting noise, including light distortion and Moire patterns.
This noiselayer is proposed by the work in: H. Fang, Z. Jia, Z. Ma, E. Chang, and W. Zhang. PIMoG: An Effective Screen-shooting Noise-Layer Simulation for Deep-Learning-Based Watermarking Network. Proceedings of the 30th ACM International Conference on Multimedia (ACM MM), 2022.
[Code]: https://github.com/FangHanNUS/PIMoG-An-Effective-Screen-shooting-Noise-Layer-Simulation-for-Deep-Learning-Based-Watermarking-Netw/
MoireGen(self, p_size, theta, center_x, center_y)#
Generates a Moire pattern with specified parameters, simulating the screen capture effect.
Parameters
p_sizeintSize of the generated pattern.
thetafloatRotation angle in degrees.
center_xfloatX-coordinate of the pattern center.
center_yfloatY-coordinate of the pattern center.
Returns
Mnumpy arrayGenerated Moire pattern matrix.
Example
# method of PIMoG
attack.MoireGen(p_size=p_size, theta=theta, center_x=center_x, center_y=center_y)Light_Distortion(self, c, embed_image)#
Simulates light distortion over an embedded image by altering brightness gradients or introducing radial distortion.
Parameters
cintRandom selection parameter to choose between gradient or radial distortion.
embed_imageTensorThe input image with the embedded watermark.
Returns
Onumpy arrayLight distortion mask applied to the image.
Example
# method of PIMoG
attack.Light_Distortion(c=c, embed_image=embed_image)Moire_Distortion(self, embed_image)#
Simulates Moire distortion on the embedded image by generating multiple Moire patterns.
Parameters
embed_imageTensorThe input image with the embedded watermark.
Returns
Znumpy arrayMoire distortion pattern applied to the image.
Example
# method of PIMoG
attack.Moire_Distortion(embed_image=embed_image)forward(self, embed_image, cover_img: Tensor = None, now_step: int = 0)#
Applies combined light distortion and Moire distortion to the input image.
Parameters
embed_imageTensorThe input image with the embedded watermark.
cover_imgTensorThe original cover image (not used in current implementation).
Returns
noised_imageTensorThe distorted image after applying noise layers.
Example
# method of PIMoG
attack.forward(embed_image=embed_image, cover_img=None, now_step=0)classStegaStamp(nn.Module)#
A differentiable StegaStamp distortion pipeline that emulates the print-and-camera capture channel by chaining blur, additive noise, contrast/brightness jitter, desaturation and optional JPEG compression.
Every perturbation ramps in linearly with `now_step relative to its *_ramp length, and each behavioural parameter (rnd_bri, rnd_hue, rnd_noise, rnd_sat, the contrast range and jpeg_quality`) sets the maximum strength reached once the matching ramp is complete.
Example
from watermarklab.attackers.diffattackers.diffattackers import StegaStamp
attack = StegaStamp(rnd_trans=0.1, rnd_bri_ramp=1000, rnd_sat_ramp=1000, rnd_hue_ramp=1000, rnd_noise_ramp=1000, contrast_ramp=1000, jpeg_quality_ramp=1000, rnd_bri=0.3, rnd_hue=0.1, jpeg_quality=50, rnd_noise=0.02, contrast_low=0.5, contrast_high=1.5, rnd_sat=1.0, no_jpeg=True, borders='white')Constructor(self, rnd_trans = 0.1, rnd_bri_ramp = 1000, rnd_sat_ramp = 1000, rnd_hue_ramp = 1000, rnd_noise_ramp = 1000, contrast_ramp = 1000, jpeg_quality_ramp = 1000, rnd_bri = 0.3, rnd_hue = 0.1, jpeg_quality = 50, rnd_noise = 0.02, contrast_low = 0.5, contrast_high = 1.5, rnd_sat = 1.0, no_jpeg = True, borders = 'white')#
Initialize the StegaStamp distortion pipeline.
Parameters
rnd_transfloatMaximum random translation; stored but not used by `__call__` (default: 0.1).
rnd_bri_rampintSteps over which brightness jitter ramps up (default: 1000).
rnd_sat_rampintSteps over which saturation jitter ramps up (default: 1000).
rnd_hue_rampintSteps over which hue jitter ramps up (default: 1000).
rnd_noise_rampintSteps over which additive noise ramps up (default: 1000).
contrast_rampintSteps over which contrast jitter ramps up (default: 1000).
jpeg_quality_rampintSteps over which JPEG quality degradation ramps up (default: 1000).
rnd_brifloatMaximum brightness offset added to the image (default: 0.3).
rnd_huefloatMaximum hue shift applied with the brightness offset (default: 0.1).
jpeg_qualityfloatLowest JPEG quality reached at the end of the ramp (default: 50).
rnd_noisefloatMaximum standard deviation of the additive Gaussian noise (default: 0.02).
contrast_lowfloatLowest contrast scale reached at the ramp end (default: 0.5).
contrast_highfloatHighest contrast scale reached at the ramp end (default: 1.5).
rnd_satfloatMaximum fraction of luminance blended into the image, i.e. the strength of the desaturation (default: 1.0).
no_jpegboolIf True, JPEG compression is skipped entirely (default: True).
bordersstrBorder padding style; stored but not used by `__call__` (default: "white").
__call__(self, encoded_image, cover_img = None, now_step = 0)#
Apply the full distortion pipeline to a batch of watermarked images.
Parameters
encoded_imageTensorWatermarked image batch of shape [N, 3, H, W] with values in [0, 1].
cover_imgTensor, optionalCover image; ignored, kept for interface compatibility.
now_stepintCurrent training step used to ramp every distortion strength (default: 0).
Returns
TensorDistorted image batch of shape [N, 3, H, W], clamped to [0, 1].
Example
# method of StegaStamp
attack.__call__(encoded_image=encoded_image, cover_img=None, now_step=0)metrics
Robustness metrics (BER, EA, TPR@x%FPR) and imperceptibility metrics (PSNR, SSIM, LPIPS, FID), plus a base class for custom metrics.
Robustness & visual quality
watermarklab.metrics.metrics4test
watermarklab/metrics/metrics4test.pyclassSSIM(BaseMetric)#
Structural Similarity Index Measure (SSIM) for image quality assessment.
SSIM evaluates the perceived quality of images by comparing luminance, contrast, and structure between two images (e.g., original vs. distorted). Values range from -1 to 1, where 1 indicates perfect similarity.
Reference:
Example
from watermarklab.metrics.metrics4test import SSIM
metric = SSIM(window_size=11, data_range=255.0, metric_name='SSIM')Constructor(self, window_size: int = 11, data_range: float = 255.0, metric_name: str = 'SSIM')#
Initializes the SSIM metric.
Parameters
window_sizeintSize of the sliding window for local statistics (must be odd).
data_rangefloatDynamic range of pixel values (e.g., 255 for uint8 images).
metric_namestrName of the metric for reporting.
test(self, img1: np.ndarray, img2: np.ndarray) -> float#
Computes the mean SSIM index between two images.
Parameters
img1np.ndarrayReference image (H, W, C) or (H, W).
img2np.ndarrayDistorted image, same shape as img1.
Returns
floatMean SSIM value across the image.
Raises
ValueErrorIf input images have different shapes.
Example
# method of SSIM
metric.test(img1=img1, img2=img2)classRMSE(BaseMetric)#
Root Mean Squared Error (RMSE) measures the standard deviation of pixel-wise differences.
Lower RMSE indicates higher similarity. Commonly used in regression and image reconstruction tasks.
Example
from watermarklab.metrics.metrics4test import RMSE
metric = RMSE(metric_name='RMSE')Constructor(self, metric_name: str = 'RMSE')#
Initializes the RMSE metric.
Parameters
metric_namestrName of the metric for reporting.
test(self, img1: np.ndarray, img2: np.ndarray) -> float#
Computes RMSE between two images.
Parameters
img1np.ndarrayFirst image.
img2np.ndarraySecond image, same shape.
Returns
floatRMSE value.
Raises
ValueErrorIf image dimensions do not match.
Example
# method of RMSE
metric.test(img1=img1, img2=img2)classMAE(BaseMetric)#
Mean Absolute Error (MAE) measures average absolute pixel differences.
Less sensitive to outliers than RMSE. Useful for detecting small but consistent distortions.
Example
from watermarklab.metrics.metrics4test import MAE
metric = MAE(metric_name='MAE')Constructor(self, metric_name: str = 'MAE')#
Initializes the MAE metric.
Parameters
metric_namestrName of the metric for reporting.
test(self, img1: np.ndarray, img2: np.ndarray) -> float#
Computes MAE between two images.
Parameters
img1np.ndarrayFirst image.
img2np.ndarraySecond image, same shape.
Returns
floatMAE value.
Raises
ValueErrorIf image dimensions do not match.
Example
# method of MAE
metric.test(img1=img1, img2=img2)classPSNR(BaseMetric)#
Peak Signal-to-Noise Ratio (PSNR) measures image fidelity in decibels (dB).
Higher PSNR indicates less distortion. Assumes known maximum pixel value (e.g., 255).
Example
from watermarklab.metrics.metrics4test import PSNR
metric = PSNR(data_range=255.0, metric_name='PSNR')Constructor(self, data_range: float = 255.0, metric_name: str = 'PSNR')#
Initializes the PSNR metric.
Parameters
data_rangefloatMaximum possible pixel value (e.g., 255 for uint8).
metric_namestrName of the metric for reporting.
test(self, img1: np.ndarray, img2: np.ndarray) -> float#
Computes PSNR between two images.
Parameters
img1np.ndarrayReference image.
img2np.ndarrayDistorted image.
Returns
floatPSNR value in dB. Returns inf if images are identical.
Raises
ValueErrorIf image dimensions do not match.
Example
# method of PSNR
metric.test(img1=img1, img2=img2)classLPIPS(BaseMetric)#
Learned Perceptual Image Patch Similarity (LPIPS) uses deep features to measure perceptual similarity.
Lower values indicate higher similarity. More aligned with human perception than PSNR/SSIM.
Reference:
Example
from watermarklab.metrics.metrics4test import LPIPS
metric = LPIPS(device='cpu', metric_name='LPIPS', net_stype='alex')Constructor(self, device: str = 'cpu', metric_name: str = 'LPIPS', net_stype: str = 'alex')#
Initializes the LPIPS metric.
Parameters
devicestrDevice to run computation ('cpu' or 'cuda').
metric_namestrName of the metric for reporting.
net_stypestrFeature extractor network ('alex', 'vgg', 'squeeze').
test(self, img1: Union[np.ndarray, Image.Image], img2: Union[np.ndarray, Image.Image]) -> float#
Computes LPIPS distance between two images.
Parameters
img1Union[np.ndarray, Image.Image]First image.
img2Union[np.ndarray, Image.Image]Second image.
Returns
floatLPIPS score (lower is better).
Raises
ValueErrorIf image sizes differ.
Example
# method of LPIPS
metric.test(img1=img1, img2=img2)classNEB(BaseMetric)#
Number of Error Bits (NEB) counts the total number of mismatched bits in watermark extraction.
Used to quantify absolute error in binary watermark retrieval.
Example
from watermarklab.metrics.metrics4test import NEB
metric = NEB(metric_name='NEB')Constructor(self, metric_name: str = 'NEB')#
Initializes the NEB metric.
Parameters
metric_namestrName of the metric for reporting.
test(self, ext_bits: List[int], target_bits: List[int]) -> int#
Computes the number of erroneous bits.
Parameters
ext_bitsList[int]Extracted watermark bits.
target_bitsList[int]Ground truth watermark bits.
Returns
intNumber of differing bits.
Raises
ValueErrorIf bit list lengths differ.
Example
# method of NEB
metric.test(ext_bits=ext_bits, target_bits=target_bits)classBER(BaseMetric)#
Bit Error Rate (BER) measures the ratio of incorrectly extracted bits.
BER = (Number of Error Bits) / (Total Number of Bits) Lower BER indicates better robustness.
Example
from watermarklab.metrics.metrics4test import BER
metric = BER(metric_name='BER')Constructor(self, metric_name: str = 'BER')#
Initializes the BER metric.
Parameters
metric_namestrName of the metric for reporting.
test(self, ext_bits: List[int], target_bits: List[int]) -> float#
Computes BER between extracted and target watermark bits.
Parameters
ext_bitsList[int]Extracted bits.
target_bitsList[int]Original embedded bits.
Returns
floatBER in range [0, 1].
Raises
ValueErrorIf list lengths differ.
Example
# method of BER
metric.test(ext_bits=ext_bits, target_bits=target_bits)classTPR_AT_N_PERCENT_FPR(BaseMetric)#
True Positive Rate at N% False Positive Rate (TPR@N%FPR).
Evaluates watermark detector performance under low false alarm constraints.
- Higher TPR@1%FPR = better detection reliability.
- Used when security demands low false positives.
Input:
- scores_attacked: Detection scores on attacked watermarked images (lower = less confident)
- scores_clean_stego: Detection scores on clean stego images (unattacked, should be high)
Assumption: Higher score = more likely to contain watermark.
Example
from watermarklab.metrics.metrics4test import TPR_AT_N_PERCENT_FPR
metric = TPR_AT_N_PERCENT_FPR(N=0.1, metric_name='TPR@1%FPR')Constructor(self, N: float = 0.1, metric_name: str = 'TPR@1%FPR')#
Initializes the TPR@N%FPR metric.
Parameters
NfloatTarget FPR threshold in percent (e.g., 1 → 1% FPR).
metric_namestrName of the metric (will replace '1' with N).
test(self, scores_clean: List[float], scores_attacked: List[float]) -> float#
Computes TPR at N% FPR using ROC curve interpolation.
Parameters
scores_cleanList[float]Detection scores on clean stego images.
scores_attackedList[float]Detection scores on attacked stego images.
Returns
floatTPR at N% FPR. Range [0, 1].
Raises
ValueErrorIf either list is empty.
Example
# method of TPR_AT_N_PERCENT_FPR
metric.test(scores_clean=scores_clean, scores_attacked=scores_attacked)classNC(BaseMetric)#
Normalized Correlation (NC) measures similarity between two binary sequences.
NC = (A • B) / (||A|| ||B||) Values close to 1 indicate strong correlation. Used in spread-spectrum watermarking.
Example
from watermarklab.metrics.metrics4test import NC
metric = NC(metric_name='Normalized Correlation')Constructor(self, metric_name: str = 'Normalized Correlation')#
Initializes the NC metric.
Parameters
metric_namestrName of the metric for reporting.
test(self, ext_bits: List[int], target_bits: List[int]) -> float#
Computes normalized correlation between extracted and target bits.
Parameters
ext_bitsList[int]Extracted watermark.
target_bitsList[int]Original watermark.
Returns
floatNC value in range [-1, 1]. 1 = perfect match.
Raises
ValueErrorIf list lengths differ.
Example
# method of NC
metric.test(ext_bits=ext_bits, target_bits=target_bits)classEA(BaseMetric)#
Extraction Accuracy (EA) measures the percentage of correctly extracted bits.
EA = (Correct Bits) / (Total Bits) * 100% Often used interchangeably with (1 - BER) * 100.
Example
from watermarklab.metrics.metrics4test import EA
metric = EA(metric_name='Extract Accuracy')Constructor(self, metric_name: str = 'Extract Accuracy')#
Initializes the EA metric.
Parameters
metric_namestrName of the metric for reporting.
test(self, ext_bits: List[int], target_bits: List[int]) -> float#
Computes extraction accuracy as percentage.
Parameters
ext_bitsList[int]Extracted bits.
target_bitsList[int]Original bits.
Returns
floatAccuracy in range [0, 100].
Raises
ValueErrorIf list lengths differ.
Example
# method of EA
metric.test(ext_bits=ext_bits, target_bits=target_bits)watermarklab.metrics.metrics4use
watermarklab/metrics/metrics4use.pyfunctionssim(img1, img2, window_size = 11, data_range = 255)#
Compute the Structural Similarity Index (SSIM) between two images.
:param img1: First image (numpy array). :param img2: Second image (numpy array). :param window_size: Size of the sliding window. :param data_range: Range of pixel values (default 255). :param metric_name: Name of the metric (default "ssim"). :return: SSIM value.
Example
from watermarklab.metrics.metrics4use import ssim
ssim(img1=img1, img2=img2, window_size=11, data_range=255)functionpsnr(img1, img2, data_range = 255)#
Calculate the Peak Signal-to-Noise Ratio (PSNR)
:param img1: Input image :param img2: Target image :param data_range: Range of pixel values (default 255). :return: PSNR value in decibels (dB)
Example
from watermarklab.metrics.metrics4use import psnr
psnr(img1=img1, img2=img2, data_range=255)functionlpips(img1, img2, device = 'cpu', net_stype = 'alex')#
Calculate the Learned Perceptual Image Patch Similarity (LPIPS)
:param img1: Input image :param img2: Target image :param device: Device to run the computation on (default "cpu"). :param net_stype: Network type for LPIPS (default "alex"). :return: LPIPS value
Example
from watermarklab.metrics.metrics4use import lpips
lpips(img1=img1, img2=img2, device='cpu', net_stype='alex')functionneb(ext_bits, target_bits)#
Calculate the Number of Error Bits (NEB)
:param ext_bits: List of extracted bits :param target_bits: List of target bits :return: Number of error bits
Example
from watermarklab.metrics.metrics4use import neb
neb(ext_bits=ext_bits, target_bits=target_bits)functionber(ext_bits, target_bits)#
Calculate the overall Bit Error Rate (BER) between the extracted watermarks and the target watermarks.
This function flattens both 1D and 2D inputs and computes a single, global BER value.
Parameters
ext_bitsThe extracted watermark bits. Can be:
- 1D: A single list of bits (e.g., [1, 0, 1]).
- 2D: A list of bit lists (e.g., [[1,0], [1,1]]).
target_bitsThe target watermark bits. Must match the shape of ext_bits.
Returns
floatThe overall Bit Error Rate across all bits.
Example
from watermarklab.metrics.metrics4use import ber
ber(ext_bits=ext_bits, target_bits=target_bits)functionnormalized_correlation(ext_bits, target_bits)#
Normalized Correlation (NC, Normalized Correlation)
:param ext_bits: List of extracted bits :param target_bits: List of target bits :return: NC
Example
from watermarklab.metrics.metrics4use import normalized_correlation
normalized_correlation(ext_bits=ext_bits, target_bits=target_bits)functionextraction_accuracy(ext_bits, target_bits)#
Calculate extraction accuracy
:param ext_bits: List of extracted bits :param target_bits: List of target bits :return: Extraction accuracy as the ratio of correct bits
Example
from watermarklab.metrics.metrics4use import extraction_accuracy
extraction_accuracy(ext_bits=ext_bits, target_bits=target_bits)tools
Auxiliary utilities such as compression coding and reversible data hiding, supporting the development of robust reversible watermarking.
Coding & reversible data hiding
watermarklab.tools.AC
watermarklab/tools/AC.pyCumulative sum objects and Fenwick trees for fast operations ============================================================
Fenwick tree and CumulativeSum classes designed to work with adaptive FED_MODEL.
In an adaptive model we do not use frequencies like
>>> frequencies = {'a': 4, 'b': 1, 'c': 3}
in the arithmetic coder. Instead we provide a list of symbols like
>>> symbols = ['a', 'b', 'c']
and set each count to one.
>>> frequencies = {symbol:1 for symbol in frequencies}
A cumulative sum object is updated as the model see more of each symbol.
>>> cumsum = CumulativeSum(frequencies) >>> cumsum.get_low_high('a') (0, 1) >>> cumsum.add_count('a', 1) >>> cumsum.get_low_high('a') (0, 2) >>> cumsum.get_low_high('b') (2, 3)
By using a Fenwick tree we can get O(log n) time operations for getting and setting counts as symbols are seen. Since the access pattern of the encoder is to alternate between getting symbol counts and updating them, this gives O(log n) performance instead of O(n). In practice n is the unique number of symbols, which is not a large value, so this does not matter that much. Still nice to use a data structure with good asymptotic performance though.
functionarithmetic_encode(data: ndarray, frequencies = None, level_bits_len: int = 10, freq_bits_len: int = 10)#
Encodes the input data using arithmetic encoding.
Parameters
datandarrayThe input data (e.g., sequence of symbols) to be encoded.
frequenciesoptionalThe frequency distribution of symbols in the input data, used to optimize encoding. If None, a default frequency calculation will be used.
level_bits_lenintThe number of bits to represent the level information during encoding. Default is 10.
freq_bits_lenintThe number of bits to represent the frequency information during encoding. Default is 10.
Returns
compressed_bitslistThe compressed bitstream as a list of bits representing the input data after encoding.
Example
from watermarklab.tools.AC import arithmetic_encode
arithmetic_encode(data=data, frequencies=None, level_bits_len=10, freq_bits_len=10)functionarithmetic_decode(data_freqs_bits: list, frequencies = None, level_bits_len: int = 10, freq_bits_len: int = 10)#
Decodes the compressed bitstream using arithmetic decoding.
Parameters
data_freqs_bitslistThe compressed bitstream to be decoded.
frequenciesoptionalThe frequency distribution of symbols in the data, used to assist with decoding. If None, a default frequency calculation will be used.
level_bits_lenintThe number of bits to represent the level information during decoding. Default is 10.
freq_bits_lenintThe number of bits to represent the frequency information during decoding. Default is 10.
Returns
decompressed_datandarrayThe decompressed data, reconstructed from the compressed bitstream.
Example
from watermarklab.tools.AC import arithmetic_decode
arithmetic_decode(data_freqs_bits=data_freqs_bits, frequencies=None, level_bits_len=10, freq_bits_len=10)watermarklab.tools.PEE
watermarklab/tools/PEE.pyfunctionPEE_embed(cover_img: ndarray, watermark_list: list, bit_plane: int = 3, level_bits_len: int = 10, freq_bits_len: int = 10)#
Performs Prediction Error Expansion (PEE)-based reversible data hiding (RDH) to embed a watermark into the cover image.
This function ensures that the input image is treated as a 3D array (with a single channel if it is originally grayscale), initializes the RDH process, and embeds the watermark into the cover image.
Parameters
cover_imgndarrayThe input cover image as a NumPy array. It can be a 2D grayscale image or a 3D image (H, W, C).
watermark_listlistA list of watermark bits to be embedded.
bit_planeintThe bit plane in which the LSB will be embedded. Default is 3.
level_bits_lenint, optionalThe bit length used for encoding intensity levels. Default is 10.
freq_bits_lenint, optionalThe bit length used for encoding frequency-related information. Default is 10.
Returns
tuple(successful, stego_img)
- successful (bool): Indicates whether embedding was successful.
- stego_img (ndarray): The resulting stego image after watermark embedding.
Example
from watermarklab.tools.PEE import PEE_embed
PEE_embed(cover_img=cover_image, watermark_list=watermark_list, bit_plane=3, level_bits_len=10, freq_bits_len=10)functionPEE_extract(stego_img: ndarray, bit_plane: int = 3, level_bits_len: int = 10, freq_bits_len: int = 10)#
Extracts the embedded message from a stego image using Reversible Data Hiding (RDH).
Parameters
stego_imgndarrayThe input stego image from which the embedded message is to be extracted.
bit_planeintThe bit plane from which the LSB is embedded. Default is 3.
level_bits_lenintThe number of bits used for encoding the level information in the embedded message. Default is 10.
freq_bits_lenintThe number of bits used for encoding the frequency information in the embedded message. Default is 10.
Returns
successfulboolIndicates whether the extraction process was successful or not.
rec_imgndarrayThe reconstructed image after extracting the embedded message, if the extraction was successful.
rec_bitsndarrayThe extracted bits representing the embedded message.
Example
from watermarklab.tools.PEE import PEE_extract
PEE_extract(stego_img=stego_image, bit_plane=3, level_bits_len=10, freq_bits_len=10)datasets
Mainstream benchmarks — MS-COCO 2017 images and captions, Kodak24 and USC-SIPI — with the batched loader that pairs data with watermark bits.
Benchmark datasets
watermarklab.datasets.datasets
watermarklab/datasets/datasets.pyclassUSC_SIPI(BaseDataset)#
USC-SIPI dataset loader.
Loads images from the USC-SIPI image database (typically the 'misc' subset), supporting both RGB and grayscale modes. Automatically downloads and extracts the dataset from Hugging Face Hub if not present locally. Only valid TIFF images that can be successfully opened and converted to the target color mode are retained.
Example
from watermarklab.datasets.datasets import USC_SIPI
dataset = USC_SIPI(im_size=256, bit_len=32, iter_num=1, dataset_name='USC_SIPI', random_seed=99, local_files_only=False, color_mode='RGB')Constructor(self, im_size: int, bit_len: int, iter_num: int = 1, dataset_name: str = 'USC_SIPI', random_seed: int = 99, local_files_only: bool = False, color_mode: str = 'RGB')#
Initializes the USC-SIPI dataset loader.
Parameters
im_sizeintTarget image size (height and width) after resizing. Images are center-cropped and resized to (im_size, im_size).
bit_lenintLength of the randomly generated binary secret sequence for each image.
iter_numint, optionalNumber of iterations over the dataset during evaluation. Default is 1.
dataset_namestr, optionalHuman-readable name of the dataset. Default is "USC_SIPI".
random_seedint, optionalSeed for random number generators to ensure reproducible shuffling and secret generation. Default is 99.
local_files_onlybool, optionalIf True, skips downloading and only uses files already present locally. Default is False.
color_modestr, optionalDesired color mode for loaded images. Must be either "RGB" (3-channel) or "GRAY" (1-channel). Default is "RGB".
load_paths(self)#
Recursively scans the dataset root for TIFF files, filters them by color mode compatibility, and builds a list of valid image paths. Only images that can be opened and converted to the target color mode are included. The list is shuffled using the configured random seed.
Example
# method of USC_SIPI
dataset.load_paths()load_data(self, index: int) -> Tuple[np.ndarray, List[int]]#
Loads and preprocesses a single image from the USC-SIPI dataset.
The image is opened, converted to the specified color mode ("RGB" or "L"), resized to (im_size, im_size) using center crop via ImageOps.fit, and returned as a float32 NumPy array with pixel values in [0.0, 255.0]. A deterministic random secret bit sequence is generated using the sample index as seed.
Parameters
indexintIndex of the image in the shuffled covers list.
Returns
Tuple[np.ndarray, List[int]]: A tuple containing:
coverfloat32 array of shape (H, W, 3) for RGB or (H, W) for GRAY.
secretlist of bit_length bits (0/1).
Example
# method of USC_SIPI
dataset.load_data(index=1)get_num_covers(self) -> int#
Returns the number of valid cover images loaded from the USC-SIPI dataset.
Returns
intNumber of usable images.
Example
# method of USC_SIPI
dataset.get_num_covers()classKODAK24(BaseDataset)#
KODAK24 dataset loader.
Loads the standard 24 high-quality KODAK images (originally in BMP format) from Hugging Face Hub. Supports both RGB and grayscale output modes. The dataset is small and commonly used for image quality evaluation.
Example
from watermarklab.datasets.datasets import KODAK24
dataset = KODAK24(im_size=256, bit_len=32, iter_num=1, dataset_name='KODAK24', random_seed=99, local_files_only=False, color_mode='RGB')Constructor(self, im_size: int, bit_len: int, iter_num: int = 1, dataset_name: str = 'KODAK24', random_seed: int = 99, local_files_only: bool = False, color_mode: str = 'RGB')#
Initializes the KODAK24 dataset loader.
Parameters
im_sizeintTarget image size (height and width) after resizing. Images are center-cropped and resized to (im_size, im_size).
bit_lenintLength of the randomly generated binary secret sequence for each image.
iter_numint, optionalNumber of iterations over the dataset during evaluation. Default is 1.
dataset_namestr, optionalHuman-readable name of the dataset. Default is "KODAK24".
random_seedint, optionalSeed for random number generators to ensure reproducible shuffling and secret generation. Default is 99.
local_files_onlybool, optionalIf True, skips downloading and only uses files already present locally. Default is False.
color_modestr, optionalDesired color mode for loaded images. Must be either "RGB" (3-channel) or "GRAY" (1-channel). Default is "RGB".
load_paths(self)#
Loads all BMP files from the KODAK24 root directory.
The original KODAK24 dataset contains exactly 24 images. A warning is logged if the count differs. The list is shuffled using the configured random seed for reproducibility.
Example
# method of KODAK24
dataset.load_paths()load_data(self, index: int) -> Tuple[np.ndarray, List[int]]#
Loads a single KODAK24 image, converts it to the specified color mode, resizes it to (im_size, im_size), and generates a deterministic random secret.
Parameters
indexintIndex of the image in the shuffled covers list.
Returns
Tuple[np.ndarray, List[int]]: A tuple containing:
coverfloat32 array of shape (H, W, 3) for RGB or (H, W) for GRAY.
secretlist of bit_length bits (0/1).
Example
# method of KODAK24
dataset.load_data(index=1)get_num_covers(self) -> int#
Returns the number of KODAK24 images loaded (typically 24).
Returns
intNumber of images.
Example
# method of KODAK24
dataset.get_num_covers()classKODAK24_AND_USC_SIPI(BaseDataset)#
A combined dataset loader that aggregates images from both the KODAK24 and USC-SIPI image databases.
This class loads RGB or grayscale images from the two datasets, filters out non-RGB or corrupted files, resizes them to a common square dimension, and generates random binary secrets for watermarking tasks. The combined image list is shuffled using a fixed random seed to ensure reproducibility.
Example
from watermarklab.datasets.datasets import KODAK24_AND_USC_SIPI
dataset = KODAK24_AND_USC_SIPI(im_size=256, bit_len=32, iter_num=1, dataset_name='KODAK24_AND_USC_SIPI', random_seed=99, local_files_only=False, color_mode='RGB')Constructor(self, im_size: int, bit_len: int, iter_num: int = 1, dataset_name: str = 'KODAK24_AND_USC_SIPI', random_seed: int = 99, local_files_only: bool = False, color_mode: str = 'RGB')#
Initializes the combined KODAK24 + USC-SIPI dataset loader.
Downloads (if needed) and loads images from both datasets, then merges their file lists. Only images that can be successfully opened and match the desired color mode are retained.
Parameters
im_sizeintTarget image size (height and width) after resizing. Images are center-cropped and resized to (im_size, im_size).
bit_lenintLength of the randomly generated binary secret sequence for each image.
iter_numint, optionalNumber of iterations over the dataset during evaluation. Default is 1.
dataset_namestr, optionalHuman-readable name of the dataset. Default is "KODAK24_AND_USC_SIPI".
random_seedint, optionalSeed for random number generators to ensure reproducible shuffling and secret generation. Default is 99.
local_files_onlybool, optionalIf True, skips downloading and only uses files already present locally. Default is False.
color_modestr, optionalDesired color mode for loaded images. Must be either "RGB" (3-channel) or "GRAY" (1-channel). Default is "RGB".
load_data(self, index: int) -> Tuple[np.ndarray, List[int]]#
Loads a single image by index, converts it to the specified color mode, resizes it, and generates a deterministic random secret bit sequence.
The image is opened, converted to "RGB" or "L" (grayscale) based on color_mode, then resized to (im_size, im_size) using ImageOps.fit (preserving aspect ratio via center crop). Pixel values are returned as a float32 NumPy array in the range [0.0, 255.0]. The secret is a list of bit_length bits (0/1), seeded by the sample index for reproducibility.
Parameters
indexintIndex of the image in the shuffled self.covers list.
Returns
Tuple[np.ndarray, List[int]]: A tuple containing:
coverA float32 NumPy array of shape (H, W, 3) for RGB or (H, W) for GRAY.
secretA list of bit_length integers (0 or 1).
Example
# method of KODAK24_AND_USC_SIPI
dataset.load_data(index=1)get_num_covers(self) -> int#
Returns the total number of valid cover images loaded from both KODAK24 and USC-SIPI datasets.
This count reflects only the images that passed format and color mode compatibility checks.
Returns
intNumber of usable cover images.
Example
# method of KODAK24_AND_USC_SIPI
dataset.get_num_covers()classMS_COCO_2017_VAL_IMAGES(BaseDataset)#
A dataset class that loads images from the MS-COCO 2017 validation set.
This class automatically downloads and extracts the 'val2017' subset from the Hugging Face Hub if not already present locally. It supports loading images in either RGB or grayscale mode, resizing them to a specified square dimension, and generating random binary secrets of fixed length for watermarking or steganography tasks. The image list is shuffled using a fixed random seed to ensure reproducibility. Users can optionally limit the number of images loaded via image_num.
Example
from watermarklab.datasets.datasets import MS_COCO_2017_VAL_IMAGES
dataset = MS_COCO_2017_VAL_IMAGES(im_size=256, bit_len=32, iter_num=1, image_num=-1, color_mode='RGB', dataset_name='MS-COCO 2017 VAL IMAGES', random_seed=99, local_files_only=False)Constructor(self, im_size: int, bit_len: int, iter_num: int = 1, image_num: int = -1, color_mode: str = 'RGB', dataset_name: str = 'MS-COCO 2017 VAL IMAGES', random_seed: int = 99, local_files_only: bool = False)#
Initializes the MS-COCO 2017 validation dataset loader.
Downloads and extracts the dataset from Hugging Face if not available locally (unless local_files_only=True). Sets up internal parameters including image size, secret bit length, color mode, and random seed for deterministic behavior.
Parameters
im_sizeintTarget image size (height and width) after resizing. Images are square-cropped and resized to (im_size, im_size).
bit_lenintLength of the randomly generated binary secret sequence for each image.
iter_numint, optionalNumber of iterations over the dataset during evaluation. Default is 1.
image_numint, optionalMaximum number of images to load from the validation set. If -1 or greater than available images, all images are used. Default is -1.
color_modestr, optionalColor mode for loaded images. Must be either "RGB" (3-channel) or "GRAY" (1-channel). Default is "RGB".
dataset_namestr, optionalHuman-readable name of the dataset for logging and identification. Default is "MS-COCO 2017 VAL IMAGES".
random_seedint, optionalSeed for random number generators to ensure reproducible shuffling and secret generation. Default is 99.
local_files_onlybool, optionalIf True, skips downloading and only uses files already present locally. Useful in offline environments. Default is False.
load_paths(self)#
Scans the 'val2017' directory for valid JPEG images, collects their file paths, shuffles them using the configured random seed, and trims the list according to image_num.
The method searches for files matching common JPEG extensions (e.g., .jpg, .jpeg in various cases). If no images are found or the 'val2017' folder is missing, a RuntimeError is raised. The resulting list is stored in self.covers for later access by load_data.
Example
# method of MS_COCO_2017_VAL_IMAGES
dataset.load_paths()load_data(self, index: int) -> Tuple[np.ndarray, List[int]]#
Loads and preprocesses a single image and generates a corresponding random secret bit sequence.
The image is opened using PIL, converted to the specified color mode ('RGB' or 'L' for grayscale), then center-cropped and resized to (im_size, im_size) using ImageOps.fit to preserve aspect ratio. The output image is converted to a float32 NumPy array with pixel values in [0.0, 255.0]. If loading fails (e.g., corrupted file), a random float32 image of the correct shape is used as fallback. A secret bit sequence of length bit_len is generated using random.randint(0, 1), with the random seed set to the sample index to ensure deterministic secret generation across runs.
Parameters
indexintIndex of the image in the shuffled self.covers list.
Returns
Tuple[np.ndarray, List[int]]: A tuple containing:
coverA float32 NumPy array of shape (H, W, C) or (H, W) depending on color_mode.
secretA list of bit_len integers (0 or 1) representing the random binary secret.
Example
# method of MS_COCO_2017_VAL_IMAGES
dataset.load_data(index=1)get_num_covers(self) -> int#
Returns the total number of cover images available in the dataset after filtering and sampling.
This number reflects the actual count of images that will be used during evaluation, which may be less than the full validation set if image_num was set to a positive integer.
Returns
intNumber of cover images loaded and ready for use.
Example
# method of MS_COCO_2017_VAL_IMAGES
dataset.get_num_covers()classMS_COCO_2017_VAL_PROMPTS(BaseDataset)#
Loads text prompts from MS-COCO val2017 captions. Each image has 5 captions; this class samples exactly ONE prompt per image, selected randomly but deterministically based on the seed.
The dataset zip contains 'captions_val2017.json'. By default, loads all images (5k). Can optionally load a fixed subset.
Example
from watermarklab.datasets.datasets import MS_COCO_2017_VAL_PROMPTS
dataset = MS_COCO_2017_VAL_PROMPTS(bit_len=32, iter_num=1, prompts_len=-1, dataset_name='MS-COCO 2017 VAL PROMPT', random_seed=99, local_files_only=False)Constructor(self, bit_len: int, iter_num: int = 1, prompts_len: int = -1, dataset_name: str = 'MS-COCO 2017 VAL PROMPT', random_seed: int = 99, local_files_only: bool = False)#
Initialize the MS_COCO_VAL_PROMPTS dataset.
Parameters
bit_lenintLength of watermark bits.
iter_numintNumber of iterations.
prompts_lenint, optionalNumber of image-prompt pairs to use. If None or >=5000, loads all. Otherwise, selects a fixed random subset.
dataset_namestrName of the dataset.
seedintSeed for deterministic behavior (prompt selection and secret generation).
load_data(self, index: int) -> Tuple[str, List[int]]#
Return a prompt and a random secret.
Parameters
indexintIndex of the prompt.
Returns
Tuple[str, List[int]]: Prompt and binary secret.
Example
# method of MS_COCO_2017_VAL_PROMPTS
dataset.load_data(index=1)get_num_covers(self) -> int#
Return the number of available prompts.
Returns
intNumber of prompts.
Example
# method of MS_COCO_2017_VAL_PROMPTS
dataset.get_num_covers()Batched loading
watermarklab.utils.data
watermarklab/utils/data/__init__.pyclassDataLoader#
Generic data loader for watermarking experiments that batches samples from a BaseDataset.
This class iterates over cover images or prompts and their associated secret bits in configurable batch sizes. It abstracts data access to support both:
- Post-Generation Watermarking (PGW)
- In-Generation Watermarking (IGW)
Each batch yields:
- List of cover images (as ndarray) or text prompts (as str)
- List of secret bit sequences
- List of cover indices (identifying which base image/prompt)
- List of iteration indices (identifying which run of that image)
Designed for seamless integration with BaseDataset and watermarking evaluation pipelines.
Example
from watermarklab.utils.data import DataLoader
loader = DataLoader(dataset=dataset, batch_size=1)Constructor(self, dataset: BaseDataset, batch_size: int = 1)#
Initialize the data loader.
Parameters
datasetBaseDatasetThe dataset providing cover/prompt and secret data.
batch_sizeintNumber of samples per batch. Larger batches improve throughput but consume more memory. Default: 1.
classDecodeDataLoader#
Simple image loader for decoding-only tasks.
Loads batches of stego images from disk for watermark extraction. Assumes no ground-truth secrets or cover images are needed — standalone decoding.
Example
from watermarklab.utils.data import DecodeDataLoader
loader = DecodeDataLoader(image_paths=image_paths, batch_size=1)Constructor(self, image_paths: List[str], batch_size: int = 1)#
Initialize image loader.
Parameters
image_pathsList[str]List of file paths to stego images.
batch_sizeintNumber of images per batch. Default: 1.
classAttackTestRobustnessDataLoader#
Data loader for evaluating watermark robustness under simulated attacks.
Automatically discovers and loads structured data from disk. Each sample provides:
- Original cover image
- Clean stego image (watermarked)
- Original secret message (ground truth)
- Output directory path for saving attacked/noised image
Expected directory structure:
images_dir/
image_1/
iter_1/
cover.png (or clean.png)
stego.png
secret.json
iter_2/
...
image_2/
...
noise_dir/ (output)
image_1/
iter_1/ ← where noised.png will be saved
iter_2/
...
Eliminates need to manually specify image/iteration counts — scans structure automatically.
Example
from watermarklab.utils.data import AttackTestRobustnessDataLoader
loader = AttackTestRobustnessDataLoader(noise_dir="noise_dir", images_dir="images_dir", batch_size=1)Constructor(self, noise_dir: str, images_dir: str, batch_size: int = 1)#
Initialize loader by scanning directory structure.
Parameters
noise_dirstrRoot directory to save attacked/noised images.
images_dirstrRoot directory containing original cover/stego/secret data.
batch_sizeint, optionalSamples per batch. Default: 1.
Raises
FileNotFoundErrorIf images_dir does not exist.
ValueErrorIf no valid 'image_X/iter_Y' structure found.
classAttackedImageDataLoader#
Loader for decoding watermarks from previously attacked/noised images.
Loads:
- Attacked stego images (noised.png)
- Corresponding original secrets (secret.json)
Assumes same directory structure as AttackTestRobustnessDataLoader.
Used in second phase of robustness testing: after attacks are applied and saved to disk.
Example
from watermarklab.utils.data import AttackedImageDataLoader
loader = AttackedImageDataLoader(attacked_stego_dir="attacked_stego_dir", image_dir="image_dir", batch_size=1)Constructor(self, attacked_stego_dir: str, image_dir: str, batch_size: int = 1)#
Initialize loader for attacked images.
Parameters
attacked_stego_dirstrDirectory containing 'noised.png' files.
image_dirstrDirectory containing original 'secret.json' files.
batch_sizeintSamples per batch. Default: 1.
Raises
FileNotFoundErrorIf attacked_stego_dir not found.
ValueErrorIf no valid 'image_X/iter_Y' structure found.
classDecodeCleanCoverDataLoader#
Data loader for evaluating watermark extraction on clean (unattacked) cover images.
Loads:
- Clean/cover images (cover.png or clean.png)
- Corresponding original secrets (secret.json)
Purpose:
- Establish baseline performance of watermark decoder on pristine images
- Compute metrics like BER, accuracy without noise/attacks
- Used in robustness testing as reference point
Assumes directory structure:
Example
from watermarklab.utils.data import DecodeCleanCoverDataLoader
loader = DecodeCleanCoverDataLoader(cover_dir="cover_dir", img_len=1, iter_len=1, batch_size=1)Constructor(self, cover_dir: str, img_len: int, iter_len: int, batch_size: int = 1)#
Initialize loader for clean cover images.
Parameters
cover_dirstrRoot directory containing image folders.
img_lenintNumber of distinct images to process.
iter_lenintNumber of iterations per image.
batch_sizeintSamples per batch. Default: 1.
laboratories
The evaluation platform for PGW and IGW methods, together with the base interfaces you implement to plug in your own model, attacker or metric.
Evaluation entry points
watermarklab.laboratories.IGW_func
watermarklab/laboratories/IGW_func.pyclassIGWLab#
Evaluation laboratory for In-Generation Watermarking (IGW) models.
This class orchestrates a comprehensive evaluation pipeline for watermarking models that embed watermarks during image generation (e.g., diffusion models, GANs).
Key capabilities:
- Watermark embedding during image generation
- Visual quality assessment (PSNR, SSIM, LPIPS, FID)
- Robustness testing under various noise attacks
- Baseline extraction performance on clean images
- Structured JSON reporting with Base64 visualizations
- Support for both text-to-image and image-to-image watermarking
Designed for research, benchmarking, and reproducible evaluation of IGW techniques.
Example
from watermarklab.laboratories.IGW_func import IGWLab
lab = IGWLab(save_path="save_results", noise_models=attackers, vqmetrics=None, robustnessmetrics=None, noise_save=False)Constructor(self, save_path: str, noise_models: List[AttackerWithFactors], vqmetrics: List[BaseMetric] = None, robustnessmetrics: List[BaseMetric] = None, noise_save: bool = False)#
Initialize the IGW evaluation lab.
Parameters
save_pathstrRoot directory for saving all experiment outputs.
noise_modelsList[AttackerWithFactors]List of noise attack configurations to test robustness.
vqmetricsList[BaseMetric], optionalVisual quality metrics. Defaults to [PSNR(), SSIM(), LPIPS()].
robustnessmetricsList[BaseMetric], optionalRobustness metrics. Defaults to [BER(), EA()].
noise_savebool, optionalIf True, preserves intermediate noised images. Otherwise, deletes them after decoding. Defaults to False.
Notes
test(self, watermark_model: BaseWatermarkModel, dataloader: DataLoader, fid_dataset: str = 'MS-COCO-2017-VAL', fid_batchsize: int = 32, device: torch.device = 'cuda', need_cover: bool = False) -> dict#
Execute full evaluation pipeline for PGW model. Generates comprehensive JSON report with all metrics and visualizations.
Parameters
watermark_modelBaseWatermarkModelModel to evaluate.
dataloaderDataLoaderData provider.
fid_batchsizeint, optionalBatch size for FID computation. Default: 32.
devicetorch.device, optionalDevice for computations. Default: "cpu".
Returns
dictComprehensive evaluation results including:
- Model metadata
- Dataset and environment info
- Timing statistics
- Visual quality metrics
- Robustness metrics
- Base64 visualizations
Example
# method of IGWLab
lab.test(watermark_model=model, dataloader=dataloader, fid_dataset='MS-COCO-2017-VAL', fid_batchsize=32, device='cuda', need_cover=False)watermarklab.laboratories.PGW_func
watermarklab/laboratories/PGW_func.pyclassPGWLab#
Laboratory for comprehensive evaluation of Post-Generation Watermarking (PGW) models.
This class orchestrates a full evaluation pipeline for watermarking models that embed watermarks into pre-generated images. It supports:
- Watermark embedding and visual quality assessment (PSNR, SSIM, LPIPS, FID)
- Robustness testing under various noise attacks (JPEG, blur, crop, etc.)
- Extraction performance evaluation on both attacked and clean images
- Baseline FPR measurement via clean image decoding
- Structured JSON report generation with Base64 visualizations
Modular design allows easy extension with custom metrics and attack models. Supports both full evaluation ("encode") and decoding-only ("decode") modes.
Example
from watermarklab.laboratories.PGW_func import PGWLab
lab = PGWLab(save_path="save_results", noise_models=attackers, vqmetrics=None, robustnessmetrics=None, noise_save=False)Constructor(self, save_path: str, noise_models: List[AttackerWithFactors], vqmetrics: List[BaseMetric] = None, robustnessmetrics: List[BaseMetric] = None, noise_save: bool = False)#
Initialize the PGW evaluation lab.
Parameters
save_pathstrRoot directory for saving all results, images, and logs.
noise_modelsList[AttackerWithFactors]List of noise attack configurations to test robustness.
vqmetricsList[BaseMetric], optionalVisual quality metrics. Defaults to [PSNR(), SSIM(), LPIPS()].
robustnessmetricsList[BaseMetric], optionalRobustness metrics. Defaults to [BER(), EA()].
noise_savebool, optionalIf True, saves noised images to disk. Otherwise, deletes after extraction. Defaults to False.
Notes
test(self, watermark_model: BaseWatermarkModel, dataloader: DataLoader, fid_batchsize: int = 32, device: torch.device = 'cuda') -> dict#
Execute full evaluation pipeline for PGW model. Generates comprehensive JSON report with all metrics and visualizations.
Parameters
watermark_modelBaseWatermarkModelModel to evaluate.
dataloaderDataLoaderData provider.
fid_batchsizeint, optionalBatch size for FID computation. Default: 32.
devicetorch.device, optionalDevice for computations. Default: "cpu".
Returns
dictComprehensive evaluation results including:
- Model metadata
- Dataset and environment info
- Timing statistics
- Visual quality metrics
- Robustness metrics
- Base64 visualizations
Example
# method of PGWLab
lab.test(watermark_model=model, dataloader=dataloader, fid_batchsize=32, device='cuda')watermarklab.laboratories.func
watermarklab/laboratories/func.pyfunctionevaluate(save_path: str, watermark_model: BaseWatermarkModel, noise_models: List[AttackerWithFactors], dataloader: DataLoader, vqmetrics: List[BaseMetric] = None, robustnessmetrics: List[BaseMetric] = None, fid_dataset: str = 'MS-COCO-2017-VAL', fid_batchsize: int = 32, fid_device: str = 'cuda', noise_save: bool = False, need_cover: bool = False) -> dict#
Unified entry point for evaluating both Post-Generation (PGW) and In-Generation (IGW) watermarking models.
This function:
- Automatically detects whether the model is PGW or IGW based on dataloader input type.
- Initializes the appropriate evaluation lab (PGWLab or IGWLab).
- Executes the full evaluation pipeline: embedding → visual quality → noise attacks → extraction → metrics.
- Generates stylized terminal banner for user experience.
- Returns structured, JSON-serializable results with embedded Base64 visualizations.
Ideal for benchmarking, research reproducibility, and automated testing pipelines.
Parameters
save_pathstrRoot directory to save all evaluation outputs (organized by model name).
watermark_modelBaseWatermarkModelWatermarking model to evaluate.
noise_modelsList[AttackerWithFactors]List of noise attack configurations with intensity factors.
dataloaderDataLoaderProvides input data — images for PGW, prompts for IGW — and secret bits.
vqmetricsList[BaseMetric], optionalVisual quality metrics. Defaults to [PSNR(), SSIM()].
robustnessmetricsList[BaseMetric], optionalRobustness metrics. Defaults to [TPR_AT_N_PERCENT_FPR(), EA()].
fid_datasetstr, optionalName of real image dataset for FID comparison (IGW only). Default: "MS-COCO-2017-VAL".
fid_batchsizeint, optionalBatch size for FID computation. Larger = faster but more VRAM. Default: 32.
fid_devicestr, optionalDevice for FID computation ("cuda" or "cpu"). Default: "cuda".
noise_savebool, optionalIf True, preserves intermediate noised images. Otherwise, deletes them after extraction. Default: False.
need_coverbool, optionalIf True, uses clean images as reference for visual metrics in IGW. Default: False.
Returns
dictComprehensive evaluation report with keys:
- modelname, modeltype, imagesize, payload
- testdataset, envinfo (hardware/software environment)
- time_cost: {'embed': [...], 'extract': [...]}
- visualqualityresult: PSNR, SSIM, LPIPS, FID scores
- robustnessresult: BER, EA, TPR@FPR per attack type/factor
- visualcompare: Base64-encoded images for stego and noise samples
Example
import watermarklab as wl
from watermarklab.utils.data import DataLoader
from watermarklab.datasets import MS_COCO_2017_VAL_IMAGES
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
from watermarklab.watermarks.PGWs import rivaGAN
dataset = MS_COCO_2017_VAL_IMAGES(im_size=256, bit_len=32)
dataloader = DataLoader(dataset, batch_size=32)
model = rivaGAN(bits_len=32, img_size=256)
attackers = AttackersWithFactorsModel()
report = wl.evaluate(
"save_results/PGWs", # everything for this run is written here
model, # the watermark to benchmark
attackers, # the attack sweep
dataloader, # images + secret bits
noise_save=True, # keep the attacked images
)classWLab#
Unified orchestrator for evaluating both Post-Generation (PGW) and In-Generation (IGW) watermarking models.
This class:
- Abstracts away the differences between PGW and IGW evaluation pipelines.
- Automatically selects the correct lab (PGWLab or IGWLab) based on input data type.
- Ensures consistent configuration (metrics, noise models, save paths) across evaluations.
- Returns standardized result format regardless of model type.
Enables a single, clean interface for evaluating any watermarking model in the framework.
Example
import watermarklab as wl
from watermarklab.attackers.attackerloader import AttackersWithFactorsModel
lab = wl.WLab(
save_path="save_results",
noise_models=AttackersWithFactorsModel(),
noise_save=True,
)
# Either benchmark a model directly, or reuse the same lab for several models:
report = lab.test(watermark_model=model, dataloader=dataloader)Constructor(self, save_path: str, noise_models: List[AttackerWithFactors], vqmetrics: List[BaseMetric] = None, robustnessmetrics: List[BaseMetric] = None, noise_save: bool = False)#
Initialize the unified watermarking evaluation framework.
Sets up both PGW and IGW evaluation labs with shared configuration. The correct lab is selected automatically at runtime based on the input dataloader's data type.
Parameters
save_pathstrRoot directory for saving all evaluation results.
noise_modelsList[AttackerWithFactors]List of noise attack configurations to test robustness.
vqmetricsList[BaseMetric], optionalVisual quality metrics. Defaults to [PSNR(), SSIM()].
robustnessmetricsList[BaseMetric], optionalRobustness metrics. Defaults to [TPR_AT_N_PERCENT_FPR(), EA()].
noise_savebool, optionalIf True, preserves intermediate noised images after extraction. Defaults to False.
test(self, watermark_model: BaseWatermarkModel, dataloader: DataLoader, fid_dataset: str = 'MS-COCO-2017-VAL', fid_batchsize: int = 32, device: torch.device = 'cuda', need_cover: bool = False) -> dict#
Execute full evaluation pipeline for the specified watermarking model.
Automatically determines whether the model is PGW or IGW by inspecting the first batch from the dataloader, then delegates evaluation to the appropriate lab.
Parameters
watermark_modelBaseWatermarkModelWatermarking model to evaluate.
dataloaderDataLoaderProvides input data (images for PGW, prompts for IGW) and secret bits.
fid_datasetstr, optionalName of real dataset for FID comparison (IGW only). Default: "MS-COCO-2017-VAL".
fid_batchsizeint, optionalBatch size for FID computation. Default: 32.
devicetorch.device, optionalDevice for metric computations (e.g., CUDA for FID). Default: "cuda".
need_coverbool, optionalIf True, uses clean images as reference for visual metrics in IGW. Default: False.
Returns
dictStandardized evaluation report containing:
- Model metadata (name, type, image size, payload)
- Dataset and environment information
- Timing statistics (embedding and extraction)
- Visual quality results (PSNR, SSIM, LPIPS, FID)
- Robustness results under various attacks
- Base64-encoded visual comparisons
Raises
RuntimeErrorIf dataloader type cannot be determined (neither image nor prompt detected).
AssertionErrorIf mode is not "encode" or "decode".
Example
# method of WLab
lab.test(watermark_model=model, dataloader=dataloader, fid_dataset='MS-COCO-2017-VAL', fid_batchsize=32, device='cuda', need_cover=False)watermarklab.laboratories.utils
watermarklab/laboratories/utils.pyfunctionlightweight_json_result(final_report: Dict[str, Any]) -> Dict[str, Any]#
Process the complete evaluation report to lightweight format by converting all numeric lists in robustness results to mean values.
This function takes the complete evaluation report and transforms the robustness results section by replacing all numeric value lists with their mean values in single-element lists. This significantly reduces file size while preserving the essential statistical information.
Parameters
final_reportDict[str, Any]Complete evaluation report dictionary containing model metadata, visual quality results, robustness results, and other evaluation metrics.
Returns
Dict[str, Any]Lightweight evaluation report with robustness results converted to mean values format, reducing file size significantly.
Example
from watermarklab.laboratories.utils import lightweight_json_result
report = lightweight_json_result(final_report=final_report)Base interfaces & configuration
watermarklab.utils.basemodel
watermarklab/utils/basemodel/__init__.pyclassResult#
Container class for storing results of watermarking operations.
This class holds outputs from embedding, extraction, and recovery processes, including processed images, extracted bits, and auxiliary metrics. Designed for structured return values across the framework.
Attributes
stego_imgOptional[List[Any]]Watermarked images (output of embedding).
clean_imgOptional[List[Any]]Original unwatermarked images (for IGW models).
emb_bitsOptional[List[List[Any]]]Embedded secret bits (before embedding).
ext_bitsOptional[List[List[Any]]]Extracted secret bits (after decoding).
rec_imgOptional[List[Any]]Recovered cover images (if model supports reversible watermarking).
other_resultDict[str, Any]Additional metadata (e.g., timing, intermediate outputs).
Example
from watermarklab.utils.basemodel import Result
model = Result(stego_img=None, clean_img=None, emb_bits=None, ext_bits=None, rec_img=None, other_result=None)Constructor(self, stego_img: Optional[List[Any]] = None, clean_img: Optional[List[Any]] = None, emb_bits: Optional[List[List[Any]]] = None, ext_bits: Optional[List[List[Any]]] = None, rec_img: Optional[List[Any]] = None, other_result: Optional[Dict[str, Any]] = None)#
Initializes the Result container.
Parameters
stego_imgOptional[List[Any]]List of stego images.
clean_imgOptional[List[Any]]List of clean (generated) images (IGW only).
emb_bitsOptional[List[List[Any]]]Embedded bit sequences.
ext_bitsOptional[List[List[Any]]]Extracted bit sequences.
rec_imgOptional[List[Any]]Recovered cover images (for reversible watermarking).
other_resultOptional[Dict[str, Any]]Additional key-value data (e.g., timing, losses).
classBaseWatermarkModel(ABC, nn.Module)#
Abstract base class for all watermarking models (both PGW and IGW).
Defines the core interface:
embed: Embed secret bits into image/promptextract: Decode watermark from stego imagerecover: Reconstruct cover (optional, for reversible watermarking)
All methods are decorated with @timing_decorator to auto-record execution time.
Example
from watermarklab.utils.basemodel import BaseWatermarkModel
model = BaseWatermarkModel(bits_len=32, img_size=256, modelname="MyModel", description=None)Constructor(self, bits_len: int, img_size: int, modelname: str, description: str = None)#
Initializes the watermarking model.
Parameters
bits_lenintNumber of bits in the watermark payload.
img_sizeintInput image resolution (assumed square: img_size × img_size).
modelnamestrUnique name for the model (e.g., "HiNet", "StegaStamp").
abstractembed(self, cover_list: List[Any], secrets: List[Any]) -> Result#
Embeds a secret watermark into cover content, which can be either existing images (PGW) or text prompts (IGW). This is the core method for watermark insertion.
The framework automatically distinguishes between PGW and IGW based on the type of elements in cover_list:
- If elements are image-like (e.g., numpy.ndarray) → PGW
- If elements are strings (text prompts) → IGW
The returned Result object must contain specific fields depending on the model type:
For PGW (Post-Generation Watermarking):
- Operates on pre-existing cover images.
- Does not generate new clean images; the input images are already available to the caller.
- Required fields in
Result: stego_img: List of watermarked images (same length ascover_list).emb_bits: List of bit sequences that were embedded.- The
clean_imgfield is optional and typically omitted (the framework already has the cover images).
For IGW (In-Generation Watermarking):
- Generates images from text prompts, producing both clean and stego versions.
- Must return the generated clean images to enable detection evaluation (e.g., TPR@x%FPR).
- Required fields in
Result: stego_img: List of stego images.clean_img: List of corresponding clean images generated from the same prompts.emb_bits: List of bit sequences that were embedded.- Omitting
clean_imgwill raise a runtime validation error.
Parameters
cover_listList[Any]- For PGW: List of existing images (e.g., List[numpy.ndarray]), the pixel range from 0 to 255.
- For IGW: List of text prompts (List[str]).
secretsList[Any]List of secret bit sequences to embed (e.g., List[List[int]] of 0s and 1s).
Returns
ResultA structured container with the following guaranteed fields based on model type:
stego_img(List[Any]): Watermarked output images (required for both PGW and IGW).clean_img(List[Any], required only for IGW): Generated clean images.emb_bits(List[List[Any]]): The actual bit sequences embedded (required for both).other_result(Dict[str, Any], optional): Additional metadata (e.g., losses, intermediate tensors).
Examples
# PGW example: watermarking existing images
cover_images = [img1, img2] # each is ndarray or Tensor
secrets = [[1,0,1], [0,1,0]]
result = model.embed(cover_images, secrets)
# result must have: stego_img, emb_bits
# result.clean_img is ignored (usually None)Example
# method of BaseWatermarkModel
model.embed(cover_list=cover_images, secrets=secrets)abstractextract(self, stego_list: List[ndarray]) -> Result#
Extracts watermark bits from stego images.
Decodes the embedded secret from one or more watermarked images.
Parameters
stego_listList[ndarray]List of stego images (H×W×C, float32).
Returns
ResultObject containing:
- ext_bits: Extracted bit sequences
- other_result: Timing, confidence scores, etc.
Example
# method of BaseWatermarkModel
model.extract(stego_list=stego_images)abstractrecover(self, stego_list: List[ndarray]) -> Result#
Recovers the original cover image from a stego image (reversible watermarking).
Only applicable to reversible or semi-reversible watermarking schemes. For irreversible methods, this may return the stego image or raise NotImplementedError.
Parameters
stego_listList[ndarray]List of stego images.
Returns
ResultObject containing:
- rec_img: Reconstructed cover images
Example
# method of BaseWatermarkModel
model.recover(stego_list=stego_images)classBaseDataset(ABC)#
Abstract base class for datasets used in watermarking evaluation.
Provides a unified interface for loading:
- Cover images (PGW) or text prompts (IGW)
- Secret bit sequences
Supports multiple iterations per cover/prompt (e.g., test robustness across N runs).
Example
from watermarklab.utils.basemodel import BaseDataset
model = BaseDataset(img_size=256, bit_len=32, iter_num=1, dataset_name="dataset_name")Constructor(self, img_size: int, bit_len: int, iter_num: int, dataset_name: str)#
Initializes the dataset.
Parameters
iter_numintNumber of times to reuse each cover/prompt (e.g., 3 runs per image).
dataset_namestrName of the dataset (e.g., "KODAK24", "MS-COCO-2017-VAL").
abstractload_data(self, index: int) -> Tuple[Any, List[int]]#
Loads a single cover/prompt and generates a secret bit sequence.
Must be implemented by subclasses.
Parameters
indexintIndex of the cover/prompt (not experiment).
Returns
Tuple[Any, List[int]]: (cover/prompt, secret_bits)
Example
# method of BaseDataset
model.load_data(index=1)abstractget_num_covers(self) -> int#
Gets the number of unique covers/prompts in the dataset.
Required for __len__ and indexing.
Returns
intNumber of cover images or prompts.
Example
# method of BaseDataset
model.get_num_covers()classBaseDiffAttackModel(nn.Module)#
Base class for attacker models used in diffusion-based watermarking (IGW).
These models modify the denoising process in diffusion models (e.g., Stable Diffusion). Not used in standard PGW evaluation.
Example
from watermarklab.utils.basemodel import BaseDiffAttackModel
model = BaseDiffAttackModel(noise_name="noise_name")Constructor(self, noise_name: str)#
Initializes the diffusion noise model.
Parameters
noise_namestrDescriptive name of the noise type.
abstractforward(self, stego_img: torch.Tensor, cover_img: torch.Tensor, now_step: int = 0) -> torch.Tensor#
Applies noise during the diffusion process.
Parameters
stego_imgtorch.TensorCurrent noisy latent.
cover_imgtorch.TensorOriginal latent (reference).
now_stepintCurrent denoising step.
Returns
torch.TensorModified latent.
Example
# method of BaseDiffAttackModel
model.forward(stego_img=stego_image, cover_img=cover_image, now_step=0)classBaseTestAttackModel(ABC)#
Abstract base class for image noise and distortion models used in watermark robustness evaluation.
This class defines a standardized interface for applying various real-world image degradations (e.g., compression, noise, geometric transforms) to stego images. It enables systematic testing of how well a watermark survives common signal processing operations.
Subclasses must implement the test method to define the specific distortion behavior. The class supports both intensity-proportional and inverse-intensity distortions via the factor_inversely_related flag.
Examples of supported distortions:
- Lossy compression (JPEG, WebP)
- Additive noise (Gaussian, Poisson)
- Filtering (Blur, Median)
- Geometric attacks (Resize, Rotate)
- Learned attacks (Neural compression, Diffusion regeneration)
Attributes
noisenamestrHuman-readable name of the noise model (e.g., "Gaussian Blur").
factor_inversely_relatedboolIndicates the relationship between factor and distortion strength.
- True: Higher factor → less distortion (e.g., JPEG quality: 90 > 30 → less compression)
- False: Higher factor → more distortion (e.g., noise σ: 10 > 1 → more noise)
Example
from watermarklab.utils.basemodel import BaseTestAttackModel
model = BaseTestAttackModel(noisename="MyAttack", factor_inversely_related=False)Constructor(self, noisename: str, factor_inversely_related: bool = False)#
Initializes the noise model with a display name and distortion semantics.
Parameters
noisenamestrThe name used in reports and logs (e.g., "Salt & Pepper Noise").
factor_inversely_relatedbool, optionalWhether a higher factor value corresponds to weaker distortion. Defaults to False. Used for sorting and visualization.
abstractattack(self, stego_img: List[ndarray], cover_img: List[ndarray], factor: float) -> List[ndarray]#
Alias for the test method, provided for semantic clarity in robustness testing pipelines.
Some frameworks prefer the term "attack" over "test" when evaluating watermark resilience. This method delegates directly to test.
Parameters
stego_imgList[ndarray]Watermarked image(s) to be attacked.
cover_imgList[ndarray]Original cover image(s), if required by the attack.
factorfloatIntensity or quality parameter of the attack.
Returns
List[ndarray]Attacked (distorted) stego image(s).
Notes
Example
# method of BaseTestAttackModel
model.attack(stego_img=stego_image, cover_img=cover_image, factor=0.5)print_params(self) -> Dict[str, Any]#
Returns a dictionary representation of the instance's attributes for logging and debugging.
This is useful for recording experimental configurations in JSON reports or logs.
Returns
Dict[str, Any]A nested dictionary with the class name as the key and all instance attributes (including noisename, factor_inversely_related) as values.
Examples
Example
# method of BaseTestAttackModel
model.print_params()classBaseMetric(ABC)#
Abstract base class for all evaluation metrics in WatermarkLab.
Includes:
- Visual quality metrics (PSNR, SSIM, LPIPS, FID)
- Robustness metrics (BER, EA, TPR@FPR)
- Structural similarity and correlation measures
Example
from watermarklab.utils.basemodel import BaseMetric
model = BaseMetric(metric_name="metric_name")Constructor(self, metric_name: str)#
Initializes the metric.
Parameters
metric_namestrHuman-readable name (e.g., "PSNR", "BER").
abstracttest(self, cover, stego) -> float#
Computes the metric value by comparing two images.
Parameters
coverOriginal image (cover).
stegoWatermarked/distorted image.
Returns
floatMetric value (range depends on metric).
Example
# method of BaseMetric
model.test(cover=cover, stego=stego)get_params(self) -> Dict[str, Any]#
Returns a copy of all instance attributes.
Used for logging and reproducibility.
Returns
Dict[str, Any]Parameter dictionary.
Example
# method of BaseMetric
model.get_params()classAttackerWithFactors#
Wrapper that combines a noise model with its test factors and display symbol.
Used to define a full attack configuration for robustness testing.
Example
from watermarklab.utils.basemodel import AttackerWithFactors
model = AttackerWithFactors(attacker=attacker, attackername="MyAttack", factors=[1, 2, 3, 4, 5], factorsymbol="factorsymbol")Constructor(self, attacker: BaseTestAttackModel, attackername: str, factors: List[Any], factorsymbol: str)#
Initializes the noise model wrapper.
Parameters
attackerBaseTestAttackModelInstance of a noise model.
attackernamestrDisplay name (e.g., "JPEG").
factorsList[float]List of distortion levels to test (e.g., [75, 50, 25]).
factorsymbolstrLaTeX-style symbol for plotting (e.g., "$Q$", "$\sigma$").
watermarklab.utils.parameters
watermarklab/utils/parameters.pyfunctionset_load_from_local(load_param: bool)#
Set the module-level `LOAD_FROM_LOCAL` flag.
Parameters
load_paramboolNew value for the module-level `LOAD_FROM_LOCAL flag (declared False` at the top of this module).
Notes
Example
from watermarklab.utils.parameters import set_load_from_local
set_load_from_local(load_param=False)draw
Visualization and interactive analysis: robustness curves, model and attacker rankings, visual-quality plots and stego / attack comparisons.
Visualization
watermarklab.draw.func
watermarklab/draw/func.pyWatermarkLab: Visualization and Analysis Module
This module provides functions to generate publication-quality plots for watermarking research, including visual comparisons, quality metrics, and robustness analysis.
functionplot_stego_visualization(input_results: List[Union[str, Dict[str, Any]]], save_path: str) -> None#
Plot stego visualization for all models in horizontal layout.
This function generates a comprehensive horizontal visualization showing the cover/clean image, stego image, and residual image for each model. It intelligently handles different model types (PGW/IGW) and avoids duplicate cover images for PGW models.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing visual comparison data.
save_pathstrDirectory where the generated PDF plot will be saved.
Example
from watermarklab.draw.func import plot_stego_visualization
plot_stego_visualization(input_results=result_paths, save_path="save_results")functionplot_attack_visualization(input_results: List[Union[str, Dict[str, Any]]], save_path: str) -> None#
Plot noise visualization for each model separately.
This function generates a separate PDF for each model, showing all available noise attack visualizations in a grid layout.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing noise visualization data.
save_pathstrDirectory where the generated PDF plots will be saved.
Example
from watermarklab.draw.func import plot_attack_visualization
plot_attack_visualization(input_results=result_paths, save_path="save_results")functionplot_visualization_comparison(input_results: List[Union[str, Dict[str, Any]]], save_path: str) -> None#
Plot all visual comparisons including stego and noise visualizations.
This function orchestrates the generation of both stego visualization (horizontal layout) and noise visualization (per-model PDFs).
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing visualization data.
save_pathstrDirectory where the generated PDF plots will be saved.
Example
from watermarklab.draw.func import plot_visualization_comparison
plot_visualization_comparison(input_results=result_paths, save_path="save_results")functionplot_multi_value_metrics(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (6, 3), style: str = 'whitegrid', xtick_rotation: bool = True) -> None#
Plot multi-value visual quality metrics using violin plots.
This function generates violin plots for metrics like PSNR, SSIM, and LPIPS. Each model's distribution of metric values is visualized with consistent coloring across plots.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing visual quality data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height). Defaults to (12, 8).
stylestr, optionalSeaborn style for the plot appearance. Defaults to 'whitegrid'.
xtick_rotationbool, optionalWhether to rotate x-axis labels by 45 degrees for better readability. Defaults to True.
Example
from watermarklab.draw.func import plot_multi_value_metrics
plot_multi_value_metrics(input_results=result_paths, save_path="save_results", figsize=(6, 3), style='whitegrid', xtick_rotation=True)functionplot_fid_metrics(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (6, 3), style: str = 'whitegrid', xtick_rotation: bool = True, show_dataset_name: bool = True) -> None#
Plot FID metrics using a grouped bar chart for IGW models only.
This function creates a grouped bar chart comparing Stego FID and Clean FID scores for each IGW model. It uses consistent coloring and adds dataset names on the bars for clarity.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing FID data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height). Defaults to (14, 8).
stylestr, optionalSeaborn style for the plot appearance. Defaults to 'whitegrid'.
xtick_rotationbool, optionalWhether to rotate x-axis labels by 45 degrees for better readability. Defaults to True.
Example
from watermarklab.draw.func import plot_fid_metrics
plot_fid_metrics(input_results=result_paths, save_path="save_results", figsize=(6, 3), style='whitegrid', xtick_rotation=True, show_dataset_name=True)functionplot_visual_quality(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (6, 2), style: str = 'whitegrid', xtick_rotation: bool = True, show_dataset_name: bool = True) -> None#
Plot all visual quality metrics.
This function orchestrates the generation of two types of plots: 1. Violin plots for multi-value metrics (PSNR, SSIM, LPIPS) 2. Grouped bar chart for FID metrics
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing visual quality data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height). Defaults to (12, 8).
stylestr, optionalSeaborn style for the plot appearance. Defaults to 'whitegrid'.
xtick_rotationbool, optionalWhether to rotate x-axis labels by 45 degrees for better readability. Defaults to True.
Example
from watermarklab.draw.func import plot_visual_quality
plot_visual_quality(input_results=result_paths, save_path="save_results", figsize=(6, 2), style='whitegrid', xtick_rotation=True, show_dataset_name=True)functionplot_model_robustness_under_single_attack(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (5, 4), style: str = 'darkgrid', shadow: bool = False, rotation_45: bool = True, columnspacing: float = 4.0) -> None#
Plot robustness comparison for watermark models.
This function creates two types of plots: 1. For each noise type with multiple factors: line plots comparing models
- PGW models use solid lines, IGW models use dashed lines
- One PDF per noise type and metric
2. For noise types with single factor: bar charts comparing models
- One PDF per noise type and metric
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing robustness data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height) tuple. Defaults to (8, 6).
stylestr, optionalSeaborn style ('whitegrid', 'darkgrid', 'white', 'dark', 'ticks'). Defaults to 'darkgrid'.
shadowbool, optionalWhether to add variance shadow to lines. Defaults to False.
rotation_45bool, optionalWhether to rotate x-axis labels 45 degrees for bar charts. Defaults to True.
need_legendbool, optionalWhether to include legend in individual plots. Defaults to False.
columnspacingtuple, optionalFigure size for legend PDF as width. Defaults to 2..
y_limtuple, optionalY-axis limits for accuracy metrics. Defaults to (45, 105).
Example
from watermarklab.draw.func import plot_model_robustness_under_single_attack
plot_model_robustness_under_single_attack(input_results=result_paths, save_path="save_results", figsize=(5, 4), style='darkgrid', shadow=False, rotation_45=True, columnspacing=4.0)functionplot_model_robustness_under_all_attack(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (5, 4), style: str = 'whitegrid', max_legend_per_row: int = 8) -> None#
Plot attacker performance visualization for watermark models.
This function creates line plots showing the trade-off between visual quality (PSNR) and robustness metrics (TPR@N%FPR, Extraction Accuracy) for different attack types. For each model and each combination of visual quality and robustness metrics, a separate PDF is generated. Each PDF contains multiple lines, one for each noise type.
The plots help visualize the attacker performance curve - how much visual quality is sacrificed for a given level of robustness degradation across different attack types.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing robustness and visual quality data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height) tuple. Defaults to (12, 10).
stylestr, optionalSeaborn style ('whitegrid', 'darkgrid', 'white', 'dark', 'ticks'). Defaults to 'darkgrid'.
Example
from watermarklab.draw.func import plot_model_robustness_under_all_attack
plot_model_robustness_under_all_attack(input_results=result_paths, save_path="save_results", figsize=(5, 4), style='whitegrid', max_legend_per_row=8)functionplot_model_robustness_ranking_by_attacker_group(input_results: List[Union[str, Dict[str, Any]]], save_path: str, attacker_groups: Dict[str, List[str]], model_names: List[str] = None, figsize: tuple = (10, 6), style: str = 'whitegrid', xtick_rotation: bool = True) -> None#
Plot model robustness ranking for each attacker group based on AUC of TPR-PSNR curves. Generates two plots for each group: one using sum of AUC, one using ranking points.
Example
from watermarklab.draw.func import plot_model_robustness_ranking_by_attacker_group
plot_model_robustness_ranking_by_attacker_group(input_results=result_paths, save_path="save_results", attacker_groups=attacker_groups, model_names=None, figsize=(10, 6), style='whitegrid', xtick_rotation=True)functionplot_model_robustness_scores_under_all_attacks(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (12, 5), style: str = 'whitegrid', xtick_rotation: bool = True, max_items_per_row: int = 8) -> None#
Plot single model robustness across all attack types based on RQ-AUC scores. For each model, creates a bar chart showing AUC scores for different noise types. Shows ranking numbers inside bars and scores above bars.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing robustness data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height) tuple. Defaults to (12, 6).
stylestr, optionalSeaborn style. Defaults to 'whitegrid'.
xtick_rotationbool, optionalWhether to rotate x-axis labels 45 degrees. Defaults to True.
max_items_per_rowint, optionalMaximum number of items per row in legend. Defaults to 6.
Example
from watermarklab.draw.func import plot_model_robustness_scores_under_all_attacks
plot_model_robustness_scores_under_all_attacks(input_results=result_paths, save_path="save_results", figsize=(12, 5), style='whitegrid', xtick_rotation=True, max_items_per_row=8)functiontest_compute_overall_robustness_scores(input_results: List[Union[str, Dict[str, Any]]]) -> Dict[str, float]#
Test function to compute and print overall robustness scores (sum of RQ-AUCs) for each model across all valid noise types, mirroring the logic in plot_model_overall_robustness_ranking.
This function loads results, computes AUCs, sums them per model, and prints the results in descending order of the total score.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing robustness data.
Returns
Dict[str, float]A dictionary of {model_name: total_auc_score}.
Example
from watermarklab.draw.func import test_compute_overall_robustness_scores
report = test_compute_overall_robustness_scores(input_results=result_paths)functionplot_model_robustness_ranking_under_single_attack(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (5, 4), style: str = 'whitegrid', xtick_rotation: bool = True) -> None#
Plot model robustness ranking for each noise type based on AUC of TPR-PSNR curves. For each noise type (excluding 'No Attacking'), creates a bar chart showing AUC scores for different models. The AUC is calculated from the TPR-PSNR curve, including baseline points (0,0) and (1, TPR_NoAttack). Shows ranking numbers inside bars and scores above bars.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing robustness data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height) tuple. Defaults to (12, 8).
stylestr, optionalSeaborn style. Defaults to 'whitegrid'.
xtick_rotationbool, optionalWhether to rotate x-axis labels 45 degrees. Defaults to True.
Example
from watermarklab.draw.func import plot_model_robustness_ranking_under_single_attack
plot_model_robustness_ranking_under_single_attack(input_results=result_paths, save_path="save_results", figsize=(5, 4), style='whitegrid', xtick_rotation=True)functionplot_model_overall_robustness_ranking(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (9, 3), style: str = 'whitegrid', xtick_rotation: bool = True) -> None#
Plot overall model robustness ranking using two methods: 1. Sum of AUC across all noise types 2. Ranking-based points (N - r + 1 for each noise type)
Example
from watermarklab.draw.func import plot_model_overall_robustness_ranking
plot_model_overall_robustness_ranking(input_results=result_paths, save_path="save_results", figsize=(9, 3), style='whitegrid', xtick_rotation=True)functionplot_all_attack_ranking(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (10, 3), style: str = 'whitegrid') -> None#
Plot attack effectiveness ranking (vertical bar chart) based on ARQ-AUC metric.
Effectiveness is measured by ARQ-AUC: for each noise type (attack), we sum its RQ-AUC values across all models. LOWER ARQ-AUC indicates a STRONGER attack (more effective at reducing watermark robustness across models).
Parameters
input_resultsList[Union[str, Dict[str, Any]]]A list of file paths (str) or result dictionaries containing robustness data.
save_pathstrDirectory where the generated PDF plots will be saved.
figsizetuple, optionalFigure size as (width, height) tuple. Defaults to (12, 5).
stylestr, optionalSeaborn style. Defaults to 'whitegrid'.
Example
from watermarklab.draw.func import plot_all_attack_ranking
plot_all_attack_ranking(input_results=result_paths, save_path="save_results", figsize=(10, 3), style='whitegrid')functionplot_attack_effectiveness_at_tpr_levels(input_results: List[Union[str, Dict[str, Any]]], save_path: str, figsize: tuple = (6, 5), style: str = 'whitegrid', tpr_levels: List[float] = None) -> None#
Plot attack effectiveness ranking at several fixed TPR levels.
For each model the attacks are ranked by how much distortion is needed to push the watermark detection rate (TPR@N%FPR) down to a fixed target TPR: an attack that still reaches the target only at a high PSNR is ranked as less effective, while an attack that reaches it at a low PSNR is ranked as more effective. Attacks that never reach the target TPR are omitted from that level's chart. One horizontal bar chart PDF is written per model and TPR level, together with a separate legend PDF.
Parameters
input_resultsList[Union[str, Dict[str, Any]]]Result JSON paths (str) or already-loaded result dictionaries.
save_pathstrDirectory receiving the generated PDF plots, one sub-directory per model.
figsizetuple, optionalFigure size as (width, height). Defaults to (6, 5).
stylestr, optionalSeaborn style name. Defaults to 'whitegrid'.
tpr_levelsList[float], optionalTarget true-positive-rate levels, each strictly between 0.0 and 1.0. Defaults to [0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1].
Example
from watermarklab.draw.func import plot_attack_effectiveness_at_tpr_levels
plot_attack_effectiveness_at_tpr_levels(input_results=result_paths, save_path="save_results", figsize=(6, 5), style='whitegrid', tpr_levels=None)steganography
iSteganoGAN, an improved SteganoGAN model that uses L-BFGS for more accurate and stable watermark extraction. It ships alongside the seven core modules and subclasses BaseWatermarkModel.
Steganography models
watermarklab.steganography.isteganogan
watermarklab/steganography/isteganogan.pyclassiSteganoGAN(BaseWatermarkModel)#
improved SteganoGAN (iSteganoGAN) via enhanced optimization (Author: Jiale Chen et.al. <chenoly@outlook.com>). Furthermore, For the extract accuracy. it uses L-BFGS for more accurate and stable watermark extraction, just like following methods:
Outperforms L-BFGS-based steganography methods such as:
- FNNS (Fixed Neural Network Steganography): https://openreview.net/pdf?id=hcMvApxGSzZ
- LISO (Learning Iterative Neural Optimizers for Image Steganography): https://arxiv.org/abs/2303.16206
iSteganoGAN achieves superior extraction accuracy and visual quality.
Example
from watermarklab.steganography import iSteganoGAN
model = iSteganoGAN(bpp=1, modelname='iSteganoGAN', device='cuda')Constructor(self, bpp: int = 1, modelname: str = 'iSteganoGAN', device: str = 'cuda')#
Initialize the iSteganoGAN model.
Parameters
bppintBits per pixel (1, 2, or 3).
modelnamestrModel identifier.
devicestrDevice to run on ('cpu' or 'cuda').
LBFGS_optimize(self, stego_image: torch.Tensor, secret: torch.Tensor, epsilon: float = 0.3, steps: int = 2000, max_iterations: int = 10, learning_rate: float = 1.0, quantize: bool = True) -> torch.Tensor#
Optimize stego image using L-BFGS for better extraction accuracy.
Parameters
stego_imagetorch.TensorInitial stego image.
secrettorch.TensorSecret to embed.
epsilonfloatMax perturbation.
stepsintTotal optimization steps.
max_iterationsintMax iterations per L-BFGS step.
learning_ratefloatL-BFGS learning rate.
quantizeboolWhether to quantize output.
Returns
torch.TensorOptimized stego image.
Example
# method of iSteganoGAN
model.LBFGS_optimize(stego_image=stego_image, secret=secret, epsilon=0.3, steps=2000, max_iterations=10, learning_rate=1.0, quantize=True)embed(self, cover_list: List[ndarray], secrets: List[List[Any]], steps: int = 2000) -> Result#
Embed message into cover images.
Parameters
cover_listList[ndarray]List of RGB images [H, W, 3], uint8 [0,255].
secretsList[List[int]]List of binary watermarks.
stepsintNumber of L-BFGS optimization steps.
Returns
ResultWatermarked images and embedded bits.
Example
# method of iSteganoGAN
model.embed(cover_list=cover_images, secrets=secrets, steps=2000)extract(self, stego_list: List[ndarray]) -> Result#
Extract watermarks from stego images.
Parameters
stego_listList[ndarray]Watermarked images [H, W, 3], uint8.
Returns
ResultExtracted binary watermarks.
Example
# method of iSteganoGAN
model.extract(stego_list=stego_images)recover(self, stego_list: List[ndarray]) -> Result#
Recover original image (not supported).
Parameters
stego_listList[ndarray]Watermarked images.
Returns
ResultNotImplemented.
Raises
NotImplementedErrorRecovery not supported.
Example
# method of iSteganoGAN
model.recover(stego_list=stego_images)Generated by static AST analysis of the source tree — every signature, default value and description is reproduced verbatim from the code's own annotations and docstrings.