<s> import math <EOL> import os <EOL> import random <EOL> import sys <EOL> from PIL import Image <EOL> def distance ( a , b ) : <EOL> def _difference ( a , b ) : <EOL> if a > b : return a - b <EOL> elif b > a : return b - a <EOL> else : return <NUM_LIT:0> <EOL> assert len ( a ) == len ( b ) <EOL> dist = <NUM_LIT:0> <EOL> for i in range ( <NUM_LIT:0> , len ( a ) ) : <EOL> dist += _difference ( a [ i ] , b [ i ] ) <EOL> return dist <EOL> def average_colour ( pixels ) : <EOL> channels = len ( pixels [ <NUM_LIT:0> , <NUM_LIT:0> ] ) <EOL> colours = [ <NUM_LIT:0> ] * channels <EOL> for x in range ( <NUM_LIT:0> , image . width ) : <EOL> for y in range ( <NUM_LIT:0> , image . height ) : <EOL> for channel in range ( <NUM_LIT:0> , channels ) : <EOL> colours [ channel ] += pixels [ x , y ] [ channel ] <EOL> colours = list ( map ( lambda x : int ( x / ( image . width * image . height ) ) , colours ) ) <EOL> return colours <EOL> if __name__ == "<STR_LIT:__main__>" : <EOL> PIXEL_SIZE = <NUM_LIT:64> <EOL> images = [ ] <EOL> image_dir = sys . argv [ <NUM_LIT:1> ] <EOL> for name in os . listdir ( image_dir ) : <EOL> path = os . path . join ( image_dir , name ) <EOL> image = Image . open ( path ) <EOL> image = image . resize ( ( PIXEL_SIZE , PIXEL_SIZE ) ) <EOL> pixels = image . load ( ) <EOL> images . append ( { <EOL> "<STR_LIT:image>" : image , <EOL> "<STR_LIT>" : pixels , <EOL> "<STR_LIT:path>" : path , <EOL> "<STR_LIT>" : average_colour ( pixels ) <EOL> } ) <EOL> input_image = sys . argv [ <NUM_LIT:2> ] <EOL> image = Image . open ( input_image ) <EOL> pixels = image . load ( ) <EOL> w , h = image . size <EOL> output_dims = ( w * PIXEL_SIZE , h * PIXEL_SIZE ) <EOL> output_image = Image . new ( "<STR_LIT>" , output_dims ) <EOL> pos_w = <NUM_LIT:0> <EOL> pos_h = <NUM_LIT:0> <EOL> for x in range ( <NUM_LIT:0> , w ) : <EOL> for y in range ( <NUM_LIT:0> , h ) : <EOL> for i in images : <EOL> i [ "<STR_LIT>" ] = distance ( pixels [ x , y ] , i [ "<STR_LIT>" ] ) <EOL> best_matches = sorted ( images , key = lambda a : a [ "<STR_LIT>" ] ) <EOL> choice = random . choice ( best_matches [ <NUM_LIT:0> : <NUM_LIT:5> ] ) <EOL> output_image . paste ( choice [ "<STR_LIT:image>" ] , ( pos_w , pos_h ) ) <EOL> pos_h += PIXEL_SIZE <EOL> if pos_h == output_dims [ <NUM_LIT:1> ] : <EOL> pos_h = <NUM_LIT:0> <EOL> pos_w += PIXEL_SIZE <EOL> output_image . save ( sys . argv [ <NUM_LIT:3> ] ) </s>
