Lines 51
##### Keywords
image (5) noise (2) perlin (2) texture (1)
##### Permissions
Owner: midorikid
Viewable by Everyone
Editable by All Siafoo Users
Know what you're getting – Unlike many sites, all our code is clearly licensed.

# 2D Improved Perlin Noise 1

 In Brief Produces one octave of improved Perlin noise.... more
 Language Python
# '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)1112def dot(A, B):13    return A[0]*B[0] + A[1]*B[1] 1415class Noise2d(object):1617    def noise(self, x, y):1819        cell = (floor(x), floor(y))2021        sum = 0.022        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)) 2930        return max(min(sum, 1.0),-1.0)3132    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 im4041    def drawIt(self, fileName, scale=32.0, size=None):42        im = self.getImage(scale, size)43        im.save(fileName)4445    def __init__(self, ):46        47        self.G = []48        length = None49        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: break55            # Normalize56            self.G[-1][0] /= length57            self.G[-1][1] /= length5859        self.P = range(256)60        shuffle(self.P)6162if __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