"""Register generated material art to the original native tile edge topology. This is binary-asset fitting, not illustration: preserve the original index masks at tile boundaries and flat fills, using colors sampled from the generated art. Equivalent original edge pixels receive one shared generated material color. """ from PIL import Image from collections import defaultdict,Counter from statistics import median def register_atlas(image,original,width=256): pixels=list(image.getdata());samples=defaultdict(list) for color,index in zip(pixels,original): if index:samples[index].append(color) colors={i:tuple(round(median(c[k] for c in values)) for k in range(3)) for i,values in samples.items()} colors[0]=(0,0,0) # A tile that was a flat fill must remain a flat fill. ImageGen's repeated # cloud/lighting gradients in these slots caused the visible square bands. flat=set() for y in range(0,image.height,16): for x in range(0,width,16): values={original[(y+dy)*width+x+dx] for dy in range(16) for dx in range(16)} if len(values)==1:flat.update(values) out=[] for pos,(color,index) in enumerate(zip(pixels,original)): x=pos%width;y=pos//width;distance=min(x%16,15-x%16,y%16,15-y%16) base=colors[index] if index in flat or not index:out.append(base) else: weight=min(1,distance/4) out.append(tuple(round(base[k]*(1-weight)+color[k]*weight) for k in range(3))) result=Image.new('RGB',image.size);result.putdata(out) return result