Skip to content

Instantly share code, notes, and snippets.

@chrisklaiber
Created August 30, 2012 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisklaiber/3541072 to your computer and use it in GitHub Desktop.
Save chrisklaiber/3541072 to your computer and use it in GitHub Desktop.
Convert an image to drawing instructions
"""
Convert an image to drawing instructions.
Dependencies:
* PIL, the Python Imaging Library
This basically write color values for each pixel, with minor cleverness to
reduce output size:
im = Image.open("file.jpg")
width, height = im.size
pix = im.load()
for x in xrange(width):
for y in xrange(height):
print "stroke(%s, %s, %s);" % pix[x, y]
print "point(%s, %s);" % (x, y)
"""
import sys
from PIL import Image
def method_a(im):
pix = im.load()
for x in xrange(width):
for y in xrange(height):
print "stroke(%s, %s, %s);" % pix[x, y]
print "point(%s, %s);" % (x, y)
def method_b(im):
pix = im.load()
colors = {}
for x in xrange(width):
for y in xrange(height):
color = pix[x, y]
if not color in colors:
colors[color] = []
colors[color].append((x,y))
for color, points in colors.iteritems():
print "stroke(%s, %s, %s);" % color
for point in points:
print "point(%s, %s);" % point
def method_c(im):
print """
var p = function() {
stroke(arguments[0], arguments[1], arguments[2]);
for (var i = arguments.length - 1; i >= 4; i -= 2) {
point(arguments[i - 1], arguments[i]);
}
};
var d = function(arr) {
for (var i = arr.length; i >= 0; i--) {
p.apply(null, arr[i]);
}
};
"""
pix = im.load()
colors = {}
for x in xrange(width):
for y in xrange(height):
color = pix[x, y]
if not color in colors:
colors[color] = []
colors[color].extend((x,y))
first = True
print "d(["
for color, coords in colors.iteritems():
if not first:
sys.stdout.write(",\n")
sys.stdout.write("[%s,%s,%s" % color)
sys.stdout.write(",%s]" % ",".join(str(coord) for coord in coords))
first = False
print "]);"
if __name__ == "__main__":
if len(sys.argv) < 1:
print >>sys.stderr, "USAGE: image_to_cs.py FILENAME"
sys.exit(-1)
filename = sys.argv[1]
im = Image.open(filename)
#im = im.resize((400, 400), Image.ANTIALIAS)
width, height = im.size
print >>sys.stderr, "width:%s height:%s" % (width, height)
method_c(im)
@decause
Copy link

decause commented Aug 31, 2012

+1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment