Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os, random, sys
- # if you're using Pillow use this
- from PIL import Image
- # if you're using PIL you can just import Image
- from collections import defaultdict
- # Build a table keyed by rgb tuples and returning a list of tuples consisting of the
- # color of each neighboring pixel and its relative position. For example ((39, 20, 13), (-1, -1))
- def buildTable( imageFilename ):
- im = Image.open(imageFilename)
- table = defaultdict(list)
- w, h = im.size
- print w*h
- for x in xrange(w):
- for y in xrange(h):
- p = im.getpixel((x, y))
- # for each of the pixel's neighbors
- for x2 in xrange(-1, 2):
- for y2 in xrange(-1, 2):
- if x2 == 0 and y2 == 0:
- continue
- pn = im.getpixel( ((x+x2)%w, (y+y2)%h) )
- table[p].append((pn, (x2, y2)))
- print len(table)
- #im.close()
- return table
- # Draw in the pixel and all of its neighbors, choose a random neighbor, repeat
- def markovImage4( imageFilename, width=512, height=512, table=None ):
- if not table:
- table = buildTable(imageFilename)
- x = width/2
- y = height/2
- color = random.choice(table.keys())
- im = Image.new("RGB", (width, height), color)
- # This is a random walk so you're not guaranteed to hit every pixel
- # but doing w*h iterations is enough to get most of them
- for i in xrange( width*height ):
- im.putpixel((x, y), color)
- neighbors = table[color]
- n_neighbors = len(neighbors)
- # Just grab a random point in the list of neighbors and take it
- # and the next 7. They probably won't all be original neighbors.
- start = random.randint(0, n_neighbors-1)
- for j in xrange(start, start+8):
- n = neighbors[j%n_neighbors]
- color = n[0]
- offset = n[1]
- xo = (x+offset[0])%width
- yo = (y+offset[1])%height
- im.putpixel((xo, yo), color)
- # Since we picked a random neighbor to start with we can just use
- # j to pick the next point
- n = neighbors[j%n_neighbors]
- color = n[0]
- # using a multiplier of 4 creates a grid
- x = (x+3*n[1][0]) % width
- y = (y+3*n[1][1]) % height
- outFilename = "markovImage4 - %s.png" % (imageFilename.split(".")[0])
- out = open(outFilename, 'wb')
- im.save(out, "PNG")
- out.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement