gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
用python实现一个可传参frequency、lacunarity、persistence、octaves、seed的2D柏林噪声
- User
用python实现一个可传参frequency、lacunarity、persistence、octaves、seed的2D柏林噪声
- Assistant
以下是一个实现可传参 frequency、lacunarity、persistence、octaves 和 seed 的2D柏林噪声的Python代码:
import numpy as np def perlin(x, y, frequency=2, lacunarity=2, persistence=0.5, octaves=6, seed=None): """Generate 2D Perlin noise.""" # Set random seed if seed is not None: np.random.seed(seed) # Initialize variables amplitude = 1 total = 0 max_value = 0 offset = 10000 # Generate octaves of noise for i in range(octaves): # Calculate coordinates and frequency for this octave freq = frequency * lacunarity ** i xi = x * freq + offset yi = y * freq + offset # Generate noise for this octave noise = np.random.normal(0, 1, (xi.shape[0], yi.shape[1])) # Add noise to total total += amplitude * noise # Update max_value and amplitude max_value += amplitude amplitude *= persistence # Normalize the result result = total / max_value return result该函数的输入为x和y坐标(0到1之间),以及可选的频率、锯齿率、持久性、八度数和种子。它返回一个二维NumPy数组,表示柏林噪声图像。下面是一个例子,展示如何使用该函数生成一个1024x1024的柏林噪声图像:
- User
xi.shape报错
- Assistant
非常对不起,我在上一条回答中犯了一个错误。xi和yi应该是一维数组而不是二维数组,所以在使用它们的形状时应将"1"改为"-1"。以下是修改后的函数:
import numpy as np def perlin(x, y, frequency=2, lacunarity=2, persistence=0.5, octaves=6, seed=None): """Generate 2D Perlin noise.""" # Set random seed if seed is not None: np.random.seed(seed) # Initialize variables amplitude = 1 total = 0 max_value = 0 offset = 10000 # Generate octaves of noise for i in range(octaves): # Calculate coordinates and frequency for this octave freq = frequency * lacunarity ** i xi = x * freq + offset yi = y * freq + offset # Generate noise for this octave noise = np.random.normal(0, 1, (len(xi), len(yi))) # Add noise to total total += amplitude * noise # Update max_value and amplitude max_value += amplitude amplitude *= persistence # Normalize the result result = total / max_value return result请注意,我还将xi和yi的长度传递给了np.random.normal()函数,从而生成正确尺寸的噪声。感谢您指出这个错误。
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.