Created
April 7, 2012 04:20
-
-
Save bobpoekert/2325005 to your computer and use it in GitHub Desktop.
Monte Carlo noise effect
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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