"""Build three-plane track mattes with multiscale colour extension behind the moving figure.""" from pathlib import Path from PIL import Image, ImageFilter import numpy as np root=Path(__file__).resolve().parent dst=root/'分层';dst.mkdir(exist_ok=True) for mask_path in sorted((root/'画稿').glob('*.mask.png')): base=mask_path.name.replace('.mask.png','');image=Image.open(mask_path.with_name(base+'.png')).convert('RGB') mask=Image.open(mask_path).convert('L').resize(image.size) fg=image.copy();fg.putalpha(mask);fg.save(dst/(base+'-fg.png')) # Extend colours underneath the opaque silhouette, so lateral travel never reveals an empty hole. wide=mask.filter(ImageFilter.MaxFilter(9)) keep=1-np.asarray(wide.resize((418,235)),dtype='float32')/255 rgb=np.asarray(image.resize((418,235)),dtype='float32') def resize_chan(x,size): return np.array(Image.fromarray(x.astype('float32')).resize(size,Image.Resampling.BILINEAR)) def resize_rgb(x,size): return np.stack([resize_chan(x[:,:,i],size) for i in range(3)],axis=2) levels=[] vals=rgb*keep[:,:,None];weight=keep while weight.shape[0]>1: levels.append((vals,weight)) h,w=weight.shape;new=(max(1,w//2),max(1,h//2)) vals=resize_rgb(vals,new);weight=resize_chan(weight,new) filled=vals/np.maximum(weight[:,:,None],.00001) for vals,weight in levels[::-1]: h,w=weight.shape;prior=resize_rgb(filled,(w,h)) filled=vals+(1-weight[:,:,None])*prior fill=Image.fromarray(np.uint8(np.clip(filled,0,255))).resize(image.size,Image.Resampling.BICUBIC) Image.composite(fill,image,wide).save(dst/(base+'-bg.jpg'),quality=94)