#!/usr/bin/env python3
"""Create zero-threshold amplified and thresholded W1 still differences."""
import sys,pathlib,json,datetime
import numpy as np
from PIL import Image
root=pathlib.Path(sys.argv[3]) if len(sys.argv)>3 else pathlib.Path('.')
run=root/('diff-'+datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%SZ'));run.mkdir()
a=np.asarray(Image.open(sys.argv[1]).convert('RGB')).astype('int32')
b=np.asarray(Image.open(sys.argv[2]).convert('RGB')).astype('int32')
assert a.shape==b.shape==a.shape and a.ndim==3
d=np.abs(a-b);maximum=d.max(axis=2)
# Multiply by 255: even a one-level channel difference becomes fully visible.
Image.fromarray(np.minimum(d*255,255).astype('uint8')).save(run/'diff0-amplified.png')
threshold=16
out=np.zeros_like(a,dtype='uint8');out[maximum>threshold]=[255,80,120]
Image.fromarray(out).save(run/'diff16.png')
(run/'metrics.json').write_text(json.dumps({'threshold0':0,'amplification':255,'thresholdT':threshold,'thresholdUnits':'maximum absolute channel difference in 8-bit RGB; strict >16','pixelsChangedAtZero':int((maximum>0).sum()),'pixelsChangedAboveT':int((maximum>threshold).sum()),'totalPixels':int(a.shape[0]*a.shape[1])},indent=2))
print(run)
