Files
CyberGril/samples/bedroom/tools/stabilize_loop.py
T
2026-10-20 16:14:20 +08:00

147 lines
6.8 KiB
Python

"""Assemble the generated forward/return clips and stabilize only the hand/book matte.
Run with the existing ComfyUI environment; no models or dependencies are fetched.
Optical flow aligns neighbouring masks; only alpha changes, never source RGB.
"""
import json
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import av
import numpy as np
import torch
from extract_layers import load_sam, segment
from PIL import Image
from scipy.ndimage import distance_transform_edt, gaussian_filter, label, map_coordinates
from skimage.color import rgb2gray
from skimage.registration import optical_flow_tvl1
ROOT = Path('/media/lucian/Downloads/ComfyUI')
TASK = ROOT / 'output/hel712-task'
BASE = ROOT / 'output/hel711-task'
Y0, Y1 = round(175 * 552 / 512), round(330 * 552 / 512)
def decode_alpha(path):
with av.open(str(path)) as source:
decoder = av.CodecContext.create('libvpx-vp9', 'r')
return [f.to_ndarray(format='rgba') for p in source.demux(video=0)
for f in decoder.decode(p)]
def encode(path, frames, alpha):
with av.open(str(path), 'w') as output:
stream = output.add_stream('libvpx-vp9', rate=16)
stream.width = stream.height = frames[0].shape[0]
stream.pix_fmt = 'yuva420p' if alpha else 'yuv420p'
stream.options = {'crf': '10', 'b': '0', 'auto-alt-ref': '0'}
for frame in frames:
for packet in stream.encode(av.VideoFrame.from_ndarray(
frame, format='rgba' if alpha else 'rgb24')):
output.mux(packet)
for packet in stream.encode():
output.mux(packet)
def signed(mask):
binary = mask > 127
return distance_transform_edt(binary) - distance_transform_edt(~binary)
def stabilize(images, masks):
# Padding supplies flow context, but edits are restricted to the specified band.
top, bottom = Y0 - 24, Y1 + 24
gray = [rgb2gray(im[top:bottom]).astype(np.float32) for im in images]
distances = [signed(m[top:bottom]) for m in masks]
rows, cols = np.meshgrid(np.arange(bottom-top), np.arange(552), indexing='ij')
def one(i):
mask = masks[i]
aligned = [distances[i]]
for offset in [-2, -1, 1, 2]:
j = (i + offset) % len(masks)
flow = optical_flow_tvl1(gray[i], gray[j], attachment=15,
num_warp=5, num_iter=10)
aligned.append(map_coordinates(distances[j], [rows+flow[0], cols+flow[1]],
order=1, mode='nearest'))
# Trim the most extreme masks; averaging the remaining three signed
# distances also avoids a majority-vote jump at the two clip joins.
consensus = np.sort(aligned, axis=0)[1:-1].mean(axis=0)
# A narrow spatial regularization removes single-pixel segmentation teeth.
stable = gaussian_filter(consensus, 0.65)
current = distances[i]
stable = np.where(np.abs(current) <= 6, stable, current)
alpha = np.clip(127.5 + stable * 127.5, 0, 255)
# Blend the first/last 8 rows back to the unchanged matte.
weight = np.ones(Y1-Y0)
weight[:8] = np.linspace(0, 1, 8)
weight[-8:] = np.linspace(1, 0, 8)
new = mask.copy()
roi = alpha[Y0-top:Y1-top]
new[Y0:Y1] = np.rint(roi*weight[:, None] + mask[Y0:Y1]*(1-weight[:, None])).astype(np.uint8)
return new, int(np.count_nonzero((new>127) != (mask>127)))
output, changes = [], []
with ThreadPoolExecutor(max_workers=4) as executor:
for i, (mask, change) in enumerate(executor.map(one, range(len(masks)))):
output.append(mask)
changes.append(change)
if i % 8 == 0:
print(f'Flow-aligned matte {i}/{len(masks)}', flush=True)
return output, changes
def main():
torch.set_num_threads(8)
cache = TASK / 'segmentation-v2.npz'
if cache.exists():
data = np.load(cache)
images, masks = list(data['images']), list(data['masks'])
else:
# Preserve original matte outside the hand/book band without rerunning it.
original = decode_alpha(BASE / 'reading-alpha.webm')
with av.open(str(BASE / 'reading_00001_.webm')) as source:
images = [np.array(f.to_image().resize((552, 552), Image.Resampling.LANCZOS))
for f in source.decode(video=0)]
masks = [f[:, :, 3] for f in original]
model = load_sam(ROOT / 'custom_nodes/was-node-suite-comfyui/repos/SAM/segment_anything',
ROOT / 'models/sams/sam_vit_b_01ec64.pth').to('cuda')
with av.open(str(TASK / 'return_00001_.webm')) as source:
for i, frame in enumerate(source.decode(video=0)):
image = frame.to_image().resize((552, 552), Image.Resampling.LANCZOS)
images.append(np.array(image))
alpha = np.array(segment(model, image, extra_positive=(
(245, 258), (280, 275), (360, 245), (365, 295))))
components, count = label(alpha > 127)
sizes = np.bincount(components.ravel())
sizes[0] = 0
keep = components == sizes.argmax()
# Retain feather next to the connected subject; discard isolated sofa specks.
from scipy.ndimage import binary_dilation
alpha[~binary_dilation(keep, iterations=3)] = 0
masks.append(alpha)
if i % 8 == 0:
print(f'Segmented return frame {i}', flush=True)
np.savez_compressed(cache, images=np.array(images), masks=np.array(masks))
del model
torch.cuda.empty_cache()
stable, changes = stabilize(images, masks)
np.savez_compressed(TASK / 'mattes.npz', before=np.array(masks), after=np.array(stable))
encode(TASK / 'loop-source.webm', images, False)
frames = [np.dstack((rgb, a)) for rgb, a in zip(images, stable, strict=True)]
encode(TASK / 'reading-alpha.webm', frames, True)
(TASK / 'stabilization.json').write_text(json.dumps({
'frames': len(images), 'fps': 16, 'join_pairs': [[48,49],[97,0]],
'source_map': [{'frames':[0,48], 'source':'reading_00001_.webm'},
{'frames':[49,97], 'source':'return_00001_.webm'}],
'band_512': [175,330], 'band_552': [Y0,Y1],
'flow': 'TV-L1, four neighbours, cyclic trimmed signed-distance mean, 6px uncertainty band',
'changed_binary_pixels_per_frame': changes,
'rgb': 'Original RGB retained; no temporal RGB blending or frame replacement',
'outside_band_unchanged': all(np.array_equal(a[:Y0],b[:Y0]) and np.array_equal(a[Y1:],b[Y1:])
for a,b in zip(masks,stable,strict=True))}, indent=2))
print('Encoded 98-frame forward/return candidate, not yet accepted.', flush=True)
if __name__ == '__main__':
main()