Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to generate images from regular expressions (http://jackm.co.uk/posts/2014/03/25/Using-Regular-Expressions-To-Generate-Images/)
import sys
import re
from PIL import Image
def get_region_identifier(x, y, resolution):
""" Return the region identifier string for a specific co-ordinate and resolution """
region_identifier = ""
for i in range(resolution):
r = int((y % 2**(resolution-i)) / 2**(resolution-1-i))
c = int((x % 2**(resolution-i)) / 2**(resolution-1-i))
region_identifier += chr(int((1-r)*c + r*(3-c)) + 48)
return region_identifier
def generate(regex, resolution, size=0, output_file='output.png'):
""" Generate an image using 'regex' over 'resolution', outputting to 'output_file' at the desired 'size' """
# Strip '' and "" from 'regex' and 'out' (in case user has added them).
regex = regex.replace('\'', '').replace('\"', '')
output_file = output_file.replace('\'', '').replace('\"', '')
# Ensure ^ and $ bound regex.
regex = re.sub(r'[\^\$]', '', regex)
regex = '^' + regex + '$'
regex_obj = re.compile(regex)
# Populate data array.
data = [0]*(2**resolution)**2
index = 0
for y in range(2**resolution):
for x in range(2**resolution):
position_string = get_region_identifier(x, y, resolution)
data[index] = 255 if regex_obj.match(position_string) is None else 0
index += 1
# Load data into image.
im = Image.new('L', (2**resolution, 2**resolution), 255)
im.putdata(data)
if size > 0:
im = im.resize((size, size), resample=Image.ANTIALIAS)
im.save(output_file)
if __name__ == '__main__':
generate(sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), sys.argv[4])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment