107 lines
5.9 KiB
Python
107 lines
5.9 KiB
Python
"""Measure all joins and before/after hand mattes; export reviewable frame evidence."""
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import av
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw
|
|
from scipy.ndimage import binary_erosion, map_coordinates
|
|
from skimage.color import rgb2gray
|
|
from skimage.registration import optical_flow_tvl1
|
|
|
|
TASK = Path('/media/lucian/Downloads/ComfyUI/output/hel712-task')
|
|
|
|
|
|
def summary(values):
|
|
a = np.array(values)
|
|
return dict(min=float(a.min()), median=float(np.median(a)),
|
|
p95=float(np.percentile(a, 95)), max=float(a.max()))
|
|
|
|
|
|
def panel(images, labels, path, size=(256, 256), columns=6):
|
|
width, height = size
|
|
board = Image.new('RGB', (columns*width, ((len(images)+columns-1)//columns)*(height+22)), '#202020')
|
|
draw = ImageDraw.Draw(board)
|
|
for i, (image, label) in enumerate(zip(images, labels, strict=True)):
|
|
x, y = i % columns*width, i // columns*(height+22)
|
|
board.paste(image.resize(size), (x, y))
|
|
draw.text((x+3, y+height+3), label, fill='white')
|
|
board.save(path)
|
|
|
|
|
|
def main():
|
|
data = np.load(TASK/'segmentation-v2.npz')
|
|
mattes = np.load(TASK/'mattes.npz')
|
|
rgb = data['images']
|
|
# All measurement uses 512px source coordinates. The head box is fixed for both clips.
|
|
images = [np.array(Image.fromarray(x).resize((512,512))) for x in rgb]
|
|
before, after = [[np.array(Image.fromarray(x).resize((512,512))) > 127
|
|
for x in mattes[key]] for key in ['before','after']]
|
|
head = [x[50:180,230:340].astype(float) for x in images]
|
|
pairs = [(i, i+1) for i in range(97)] + [(97,0)]
|
|
head_diff = [float(np.abs(head[a]-head[b]).mean()) for a,b in pairs]
|
|
ordinary = [d for i,d in enumerate(head_diff) if i not in [48,97]]
|
|
report = {'coordinates':'512x512, head x230:340 y50:180, book/hand all x y175:330',
|
|
'original_head_adjacent':summary(head_diff[:48]),
|
|
'original_head_seam':float(np.abs(head[48]-head[0]).mean()),
|
|
'loop_ordinary_head':summary(ordinary),
|
|
'joins':[{'pair':[48,49],'head_mae':head_diff[48]},
|
|
{'pair':[97,0],'head_mae':head_diff[97]}],
|
|
'head_mae_all_pairs':head_diff}
|
|
for name, masks in [('before',before),('after',after)]:
|
|
edge = [int((m & ~binary_erosion(m))[175:330].sum()) for m in masks]
|
|
switches = [int((masks[a]^masks[b])[175:330].sum()) for a,b in pairs]
|
|
report[name] = {'boundary_pixels': edge, 'switch_pixels':switches,
|
|
'original49_boundary':summary(edge[:49]),
|
|
'original49_boundary_jump':summary(np.abs(np.diff(edge[:49]))),
|
|
'original49_switch':summary(switches[:48]),
|
|
'all_boundary':summary(edge), 'all_boundary_jump':summary(np.abs(np.diff(edge + [edge[0]]))),
|
|
'all_switch':summary(switches),
|
|
'joins_switch':[switches[48],switches[97]]}
|
|
# Warp both alpha candidates with the same image motion. Residuals separate
|
|
# mask switching from unaligned silhouette motion (not an anatomy metric).
|
|
compensated = {'before':[], 'after':[]}
|
|
rows, cols = np.meshgrid(np.arange(155), np.arange(512), indexing='ij')
|
|
for a,b in pairs:
|
|
flow = optical_flow_tvl1(rgb2gray(images[a][175:330]).astype(np.float32),
|
|
rgb2gray(images[b][175:330]).astype(np.float32),
|
|
num_warp=3, num_iter=5)
|
|
for name,masks in [('before',before),('after',after)]:
|
|
warped = map_coordinates(masks[b][175:330].astype(float),
|
|
[rows+flow[0],cols+flow[1]], order=1, mode='nearest')>0.5
|
|
compensated[name].append(int((masks[a][175:330]^warped).sum()))
|
|
report['flow_compensated_switch']={k:{'all':summary(v), 'original49':summary(v[:48]),'per_pair':v}
|
|
for k,v in compensated.items()}
|
|
# Raw interior stays paired with alpha output; encoding error is reported separately.
|
|
with av.open(str(TASK/'reading-alpha.webm')) as src:
|
|
decoder=av.CodecContext.create('libvpx-vp9','r')
|
|
decoded=[f.to_ndarray(format='rgba') for p in src.demux(video=0) for f in decoder.decode(p)]
|
|
report['alpha_rgb_interior_mae']=summary([
|
|
float(np.abs(out[:,:,:3].astype(float)-im).mean(axis=2)[m>250].mean())
|
|
for out,im,m in zip(decoded,rgb,mattes['after'],strict=True)])
|
|
(TASK/'metrics.json').write_text(json.dumps(report,indent=2))
|
|
print(json.dumps({k:v for k,v in report.items() if k not in ['before','after','head_mae_all_pairs','flow_compensated_switch']},indent=2))
|
|
print(json.dumps({k:{x:y for x,y in v.items() if not isinstance(y,list)} for k,v in report.items() if k in ['before','after']},indent=2))
|
|
ids=[46,47,48,49,50,51,94,95,96,97,0,1]
|
|
panel([Image.fromarray(images[i]) for i in ids], [f'frame {i}' for i in ids],TASK/'join-frames.png')
|
|
panel([Image.fromarray(images[i][50:180,230:340]) for i in ids], [f'head {i}' for i in ids],TASK/'join-heads.png',size=(220,260))
|
|
ids=[0,8,16,24,32,40,47,48,49,56,64,72,80,88,96,97]
|
|
crops=[]
|
|
labels=[]
|
|
for i in ids:
|
|
for name,masks in [('before',mattes['before']),('after',mattes['after'])]:
|
|
rgba=np.dstack((rgb[i],masks[i]))
|
|
bg=Image.new('RGBA',(552,552),'#557788')
|
|
bg.alpha_composite(Image.fromarray(rgba))
|
|
crops.append(bg.convert('RGB').crop((90,189,430,356)))
|
|
labels.append(f'{name} {i}')
|
|
panel(crops,labels,TASK/'hand-before-after.png',size=(340,167),columns=4)
|
|
panel([Image.fromarray(mattes['after'][i]).convert('RGB').crop((90,189,430,356)) for i in ids],
|
|
[f'alpha {i}' for i in ids],TASK/'hand-mattes.png',size=(340,167),columns=4)
|
|
panel([Image.fromarray(images[i]) for i in range(98)], [str(i) for i in range(98)],
|
|
TASK/'all-frames.png',size=(170,170),columns=14)
|
|
|
|
|
|
if __name__=='__main__':
|
|
main()
|