Skip to content

Instantly share code, notes, and snippets.

@czinn
Created April 3, 2017 20:15
Show Gist options
  • Save czinn/013295fc0459dee73ce5eb4113a254f6 to your computer and use it in GitHub Desktop.
Save czinn/013295fc0459dee73ce5eb4113a254f6 to your computer and use it in GitHub Desktop.
Combiner for /r/place frames.
# Requires PyPNG (https://pypi.python.org/pypi/pypng)
import png
from collections import defaultdict
import sys
import glob
# Colour palettes are in different orders on images. Convert to standard palette.
STANDARD_PALETTE = [(0, 0, 234), (0, 131, 199), (0, 211, 221), (2, 190, 1), (34, 34, 34), (130, 0, 128), (136, 136, 136), (148, 224, 68), (160, 106, 66), (207, 110, 228), (228, 228, 228), (229, 0, 0), (229, 149, 0), (229, 217, 0), (255, 167, 209), (255, 255, 255)]
PALETTE_MAP = {x: i for i, x in enumerate(STANDARD_PALETTE)}
# Loads an image and yields 1M pixels (indexes into palette).
def loadImageToGenerator(fn):
f = open(fn, 'rb')
r = png.Reader(file=f)
width, height, pixels, metadata = r.read()
palette = metadata['palette']
for row in pixels:
for p in row:
# Standardize pixel colour palette.
yield PALETTE_MAP[palette[p]]
def mergePixels(pixels):
# Uncomment line below for desired algorithm
d = defaultdict(int)
for i, p in enumerate(pixels):
# Simple FPTP
# d[p] += 1
# Weighted towards later images
d[p] += i + 1
# In case of tie, higher index in colour palette is chosen.
return max((b, a) for a, b in d.items())[1]
def mergeFilesToIterator(fns):
fns.sort()
# FUNCTIONAL PROGRAMMING!!!
return map(mergePixels, zip(*map(loadImageToGenerator, fns)))
def iteratorToRowIterator(it, cols=1000):
while True:
yield [it.__next__() for i in range(cols)]
if __name__ == '__main__':
if len(sys.argv) < 2:
pathname = '*.png'
else:
pathname = sys.argv[1]
fns = glob.glob(pathname)
print('Combining {} files...'.format(len(fns)))
w = png.Writer(width=1000, height=1000, bitdepth=4, palette=STANDARD_PALETTE)
of = open('output.png', 'wb')
w.write(of, iteratorToRowIterator(mergeFilesToIterator(fns)))
of.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment