Skip to content

Instantly share code, notes, and snippets.

@bobpoekert
Created April 7, 2012 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bobpoekert/2325005 to your computer and use it in GitHub Desktop.
Save bobpoekert/2325005 to your computer and use it in GitHub Desktop.
Monte Carlo noise effect
import Image
import random
target = Image.open('target.png').convert('RGB')
target_distance = 10
def make_image():
return Image.new('RGB', target.size)
def random_pixel():
return tuple(int(random.random() * 255) for i in xrange(3))
def distance(a, b):
assert len(a) == len(b)
accum = 0
for i in xrange(len(a)):
accum += b[i] - a[i]
return accum / len(a)
i = 0
last_frame = make_image()
good_enough = set([])
def write_image(image):
global i
image.save('%d.bmp' % i)
i += 1
for y in xrange(last_frame.size[1]):
for x in xrange(last_frame.size[0]):
last_frame.putpixel((x, y), random_pixel())
write_image(last_frame)
while 1:
max_distance = 0
next_frame = last_frame.copy()
for y in xrange(last_frame.size[1]):
for x in xrange(last_frame.size[0]):
if (x, y) in good_enough:
continue
contender = random_pixel()
target_pixel = target.getpixel((x, y))
contender_distance = distance(contender, target_pixel)
if contender_distance < distance(next_frame.getpixel((x, y)), target_pixel):
next_frame.putpixel((x, y), contender)
if contender_distance <= target_distance:
good_enough.add((x, y))
current_distance = distance(next_frame.getpixel((x, y)), target_pixel)
if current_distance > max_distance:
max_distance = current_distance
write_image(next_frame)
last_frame = next_frame
print max_distance
if max_distance <= target_distance:
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment