def ber_noise(x, y, octaves, persistence):
frequency = 1
amplitude = 1
noise_value = 0
for i in range(octaves):
sample_x = x * frequency
sample_y = y * frequency
# 生成4个角落点,计算插值权重
left = int(sample_x)
top = int(sample_y)
right = left + 1
bottom = top + 1
frac_x = sample_x - left
frac_y = sample_y - top
# 计算4个角落点的值
tl = generate_seed(left, top)
tr = generate_seed(right, top)
bl = generate_seed(left, bottom)
br = generate_seed(right, bottom)
# 计算插值系数
weight_tl = (1 - frac_x) * (1 - frac_y)
weight_tr = frac_x * (1 - frac_y)
weight_bl = (1 - frac_x) * frac_y
weight_br = frac_x * frac_y
# 计算插值结果
noise_value += weight_tl * tl + weight_tr * tr + weight_bl * bl + weight_br * br
# 更新幅度和频率
amplitude *= persistence
frequency *= 2
return noise_value
最后我们需要实现一个函数来生成整个矩阵的噪声值。代码如下:
python
def generate_noise(width, height, octaves, persistence):
matrix = []
for y in range(height):
row = []
for x in range(width):
noise = ber_noise(x, y, octaves, persistence)
row.append(noise)
matrix.append(row)
return matrix
现在我们可以生成任意大小的柏林噪声图像了。只需要调整函数的参数即可。
一个完整的代码例子如下:
python
import random
def generate_seed(x, y):
seed = x * 283 + y * 57
seed = (seed << 13) ^ seed
return (seed * (seed * seed * 15731 + 789221) + 1376312589) & 0x7fffffff
def ber_noise(x, y, octaves, persistence):
frequency = 1
amplitude = 1
noise_value = 0
for i in range(octaves):
sample_x = x * frequency
sample_y = y * frequency
# 生成4个角落点,计算插值权重
left = int(sample_x)
top = int(sample_y)
right = left + 1
bottom = top + 1
frac_x = sample_x - left
frac_y = sample_y - top
# 计算4个角落点的值
tl = generate_seed(left, top)
tr = generate_seed(right, top)
bl = generate_seed(left, bottom)
br = generate_seed(right, bottom)
# 计算插值系数
weight_tl = (1 - frac_x) * (1 - frac_y)
weight_tr = frac_x * (1 - frac_y)
weight_bl = (1 - frac_x) * frac_y
weight_br = frac_x * frac_y
# 计算插值结果
noise_value += weight_tl * tl + weight_tr * tr + weight_bl * bl + weight_br * br
# 更新幅度和频率
amplitude *= persistence
frequency *= 2
return noise_value
def generate_noise(width, height, octaves, persistence):
matrix = []
for y in range(height):
row = []
for x in range(width):
noise = ber_noise(x, y, octaves, persistence)
row.append(noise)
matrix.append(row)
return matrix
# 生成一个10x10的柏林噪声图像
noise = generate_noise(10, 10, 6, 0.5)
# 打印噪声图像
for row in noise:
print(row)