License Public Domain
Lines 51
Keywords
image (5) noise (2) perlin (2) texture (1)
Permissions
Owner: midorikid
Viewable by Everyone
Editable by All Siafoo Users
Hide
Meet people who work on similar things as you – get help if you need it Join Siafoo Now or Learn More

2D Improved Perlin Noise Atom Feed 1

In Brief Produces one octave of improved Perlin noise.... more
# 's
 1from math import *
2from random import random, shuffle
3import Image
4
5def drop(t):
6 t = abs(t)
7 return 1.0 - t*t*t*(t*(t*6-15)+10)
8
9def Q(u, v):
10 return drop(u) * drop(v)
11
12def dot(A, B):
13 return A[0]*B[0] + A[1]*B[1]
14
15class Noise2d(object):
16
17 def noise(self, x, y):
18
19 cell = (floor(x), floor(y))
20
21 sum = 0.0
22 for n in ((0,0), (0,1), (1,0), (1,1)):
23 i,j = (cell[0] + n[0], cell[1] + n[1])
24 u,v = (x-i, y-j)
25 index = self.P[int(i)]
26 index = self.P[(index + int(j))%len(self.P)]
27 grad = self.G[index % len(self.G)]
28 sum += Q(u, v) * dot(grad, (u, v))
29
30 return max(min(sum, 1.0),-1.0)
31
32 def getImage(self, scale=32.0, size=None):
33 size = size if size else (256, 256)
34 im = Image.new('L', size)
35 for x in range(size[0]):
36 for y in range(size[1]):
37 im.putpixel((x,y), int((self.noise(x/scale,y/scale)+1)*128))
38
39 return im
40
41 def drawIt(self, fileName, scale=32.0, size=None):
42 im = self.getImage(scale, size)
43 im.save(fileName)
44
45 def __init__(self, ):
46
47 self.G = []
48 length = None
49 while len(self.G) < 256:
50 self.G.append(None)
51 while True:
52 self.G[-1] = [random()*2-1, random()*2-1]
53 length = sqrt(self.G[-1][0]**2 + self.G[-1][1]**2)
54 if length < 1: break
55 # Normalize
56 self.G[-1][0] /= length
57 self.G[-1][1] /= length
58
59 self.P = range(256)
60 shuffle(self.P)
61
62if __name__ == "__main__":
63 n = Noise2d()
64 n.drawIt('perlinNoise.png', size=(512, 512))

Produces one octave of improved Perlin noise.

Implemented as described in [Perlin2003].

The function drop(t) is based on Perlin's improved interpolation polynomial . Because this function is called so frequently, factoring to results in a 40% improvement in speed when profiled with cProfile.

[Perlin2003]Ken Perlin, et al. Texturing & Modeling: A Procedural Approach, 2003
http://www.siafoo.net/image/61