60 lines
2.2 KiB
Python
60 lines
2.2 KiB
Python
"""Per-frame real SAM segmentation, then VP9 alpha encoding with existing PyAV."""
|
|
import json
|
|
from pathlib import Path
|
|
|
|
import av
|
|
import numpy as np
|
|
import torch
|
|
from extract_layers import load_sam, segment
|
|
from PIL import Image
|
|
|
|
ROOT = Path('/media/lucian/Downloads/ComfyUI')
|
|
TASK = ROOT / 'output/hel711-task'
|
|
|
|
|
|
def main():
|
|
torch.set_num_threads(8)
|
|
model = load_sam(
|
|
ROOT / 'custom_nodes/was-node-suite-comfyui/repos/SAM/segment_anything',
|
|
ROOT / 'models/sams/sam_vit_b_01ec64.pth').to('cuda')
|
|
output = av.open(str(TASK / 'reading-alpha.webm'), 'w')
|
|
stream = output.add_stream('libvpx-vp9', rate=16)
|
|
stream.width = 552
|
|
stream.height = 552
|
|
stream.pix_fmt = 'yuva420p'
|
|
stream.options = {'crf': '20', 'b': '0', 'auto-alt-ref': '0'}
|
|
metrics = []
|
|
previews = []
|
|
source = av.open(str(TASK / 'reading_00001_.webm'))
|
|
previous = None
|
|
first = None
|
|
for index, decoded in enumerate(source.decode(video=0)):
|
|
image = decoded.to_image().resize((552, 552), Image.Resampling.LANCZOS)
|
|
mask = segment(model, image)
|
|
frame = image.convert('RGBA')
|
|
frame.putalpha(mask)
|
|
pixels = np.array(image).astype(float)
|
|
if first is None:
|
|
first = pixels
|
|
metrics.append(dict(frame=index, mask_pixels=int((np.array(mask) > 127).sum()),
|
|
mean_absolute_rgb_change=0 if previous is None else float(np.abs(pixels-previous).mean())))
|
|
previous = pixels
|
|
if index in [0, 16, 32, 48]:
|
|
previews.append(frame)
|
|
frame.save(TASK / f'matted-{index:02}.png')
|
|
for packet in stream.encode(av.VideoFrame.from_ndarray(np.array(frame), format='rgba')):
|
|
output.mux(packet)
|
|
if index % 16 == 0:
|
|
print(f'Matted frame {index}', flush=True)
|
|
for packet in stream.encode():
|
|
output.mux(packet)
|
|
output.close()
|
|
source.close()
|
|
(TASK / 'frame-metrics.json').write_text(json.dumps(dict(
|
|
frames=metrics, loop_rgb_difference=float(np.abs(previous-first).mean()),
|
|
interpretation='Real generated frames; RGB differences alone are not proof of valid anatomy or identity.'), indent=2))
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|