Add 16-bit PNG support to Python package - #36
Open
yoraiyanivbria wants to merge 2 commits into
Open
Conversation
PIL.Image.open silently flattens 16-bit-per-channel PNGs to 8-bit on load, so any high-bit-depth source already loses precision before TrustMark.encode() ever runs. TrustMark.encode_high_bit_depth() reads the true 16-bit pixels directly (OpenImageIO for RGB, pypng for RGBA, avoiding OpenImageIO's PNG writer premultiplying alpha on write), runs the real encoder on a throwaway 8-bit copy, and adds back only the watermark's own perturbation onto the untouched full-precision pixels before re-encoding as 16-bit. Both codecs are gated behind the new optional `trustmark[highbitdepth]` extra and lazily imported, so the base package gains no new hard dependency. Decode is intentionally out of scope: PIL's implicit 8-bit flatten on read doesn't materially affect watermark detection, only encode-side precision.
pypng raises (e.g. ChunkError) on malformed input that still passes the cheap PNG-header sniff, unlike OpenImageIO which reports decode failures via has_error/return codes rather than a Python exception. Wrap the pypng decode so corrupt-but-header-valid bytes return None like every other non-applicable input, instead of letting the exception escape. Also convert the RGBA writer's pixel array to a plain list before handing it to pypng.Writer.write(), for portability across pypng versions.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
PIL.Image.opensilently flattens a 16-bit-per-channel PNG to 8-bit on load (no error, no signal anything was lost) — and no TrustMark model is trained on more than 8-bit input anyway. Sotm.encode()alone can never deliver a genuinely 16-bit result: the source has already lost its extra precision before it reaches PIL.TrustMark.encode_high_bit_depth(raw_png_bytes, string_secret, ...): reads the true 16-bit pixels directly (bypassing PIL entirely), runs the real encoder on a throwaway 8-bit copy, and adds back only the watermark's own perturbation onto the untouched full-precision pixels before re-encoding as a 16-bit PNG. Unlike the rest of the class, it takes/returns raw PNG bytes rather than aPIL.Image, since PIL can't represent the data being preserved.copy_metadata); RGBA goes throughpypnginstead, since OpenImageIO's PNG writer unconditionally premultiplies RGB by alpha on write with no way to disable it (PNG itself only ever stores straight alpha, so that would be non-conformant output). Alpha is carried through byte-exact and untouched — the model never sees or affects it.pip install trustmark[highbitdepth]extra (pyproject.tomlandsetup.py, kept in sync) and lazily imported only once a cheap, dependency-free PNG header sniff (_png_header) confirms they're actually needed — so the base package gains no new hard dependency, and an RGBA-only caller is never forced to have OpenImageIO installed (or vice versa).ValueErrorpointing atTrustMark.encode()instead — no silent fallback to a lossy 8-bit path.decode_high_bit_depth. PIL's implicit 8-bit flatten on read doesn't materially affect watermark detection, only the delivered pixel precision on encode, so the ordinarytm.decode()is documented as the correct way to read back a high-bit-depth watermarked image.python/CLAUDE.md(styled like the existing encode/decode sections) and a short pointer frompython/README.md.Test plan
python/test.py(this repo's existing example/smoke-test convention) with a 16-bit section: pure I/O round trip for RGB and RGBA (byte-exact within uint16 quantization, gamma preserved), a real end-to-endencode_high_bit_depth→ PIL-flatteneddecode()round trip confirming the watermark survives and the output PNG header still reports 16-bit, and a negative check that ordinary 8-bit PNG bytes are rejected withValueError. Ran successfully against a realmodel_type='P'instance.import trustmarkstill works withOpenImageIO/pypngnot installed, and thatencode_high_bit_depthraises the actionableImportError(pointing at the extra) only when a genuinely high-bit-depth input actually needs the missing codec — an 8-bit input still raises the ordinaryValueErrorwithout ever touching the optional imports.WM_STRENGTHthreading is correct for themodel_type='P'variant, whereencode()already applies an internal 1.25× multiplier — the new residual helper passesWM_STRENGTHstraight through rather than re-applying it.