import numpy as np
import random
def noise2d(x, y, frequency=0.0625, lacunarity=2.0, persistence=0.5, octaves=6, seed=0):
random.seed(seed)
total = 0.0
amplitude = 1.0
max_value = 0.0
for i in range(octaves):
noise_value = noise(x*frequency, y*frequency)
total += noise_value * amplitude
frequency *= lacunarity
amplitude *= persistence
max_value += amplitude
return total / max_value
def noise(x, y):
x_int = int(x)
y_int = int(y)
corner_values = []
for corner_x in range(x_int, x_int+2):
for corner_y in range(y_int, y_int+2):
corner_values.append(random_noise(corner_x, corner_y))
x_decimal = x - x_int
y_decimal = y - y_int
weight_values = []
for index in range(3):
weight_values.append(interpolate(x_decimal, y_decimal, index))
x_weights = np.array([1.0, x_decimal, 1.0-x_decimal])
interpolated = np.dot(x_weights, np.transpose(weight_values))
return interpolated
def random_noise(x, y):
random.seed(x*9873 + y*5687)
return random.uniform(-1.0, 1.0)
def interpolate(x, y, index):
if index == 0:
return x
elif index == 1:
return y
else:
return x + y - x*y
# test the function
import matplotlib.pyplot as plt
freq = 0.0625
lacun = 2.0
pers = 0.5
oct = 6
seed = 0
N = 128
scale = 6.0
image = np.zeros((N, N))
for i in range(N):
for j in range(N):
image[i][j] = noise2d(i/scale, j/scale, freq, lacun, pers, oct, seed)
plt.imshow(image, cmap='gray', interpolation='bicubic')
plt.show()