问题描述
"bandDeFinitions" : [
{
"0": ["x^2 + 2*x + 5 - y","ABOVE"]
},{
"0": ["sin(6*x) - y","UNDER"]
},{
"0": ["tan(x) - y","ABOVE"]
}
]
这些函数应该生成 3 个图像。每个图像都应根据方程的解进行填充,并提供位置(下方或上方)。我需要将坐标系移动到图像的中心,所以我将 -y
添加到方程中。应填充的图像部分应为白色,另一部分应为黑色。
我正在做的是解 x in [-W/2,W/2]
的方程并将解存储到数组中,如下所示:
#Generates X axis dots and solves an expression which defines a band
#Coordinate system is moved to the center of the image
def __solveKernelDeFinition(self,f):
xAxis = range(-kernelSize,kernelSize)
dots = []
for x in xAxis:
sol = f(x,kernelSize/2)
dots.append(sol)
print(dots)
return dots
我正在测试是否应该像这样将某个像素涂成白色:
def shouldPixelGetNoise(y,x,i,currentBand):
shouldGetNoise = True
for bandKey in currentBand.bandDeFinition.keys():
if shouldGetNoise:
pixelSol = currentBand.bandDeFinition[bandKey][2](x,y)
renderPos = currentBand.bandDeFinition[bandKey][1]
bandSol = currentBand.bandDeFinition[bandKey][0]
shouldGetNoise = shouldGetNoise and pixelSol <= bandSol[i] if renderPos == Position.UNDER else pixelSol >= bandSol[i]
else:
break
return shouldGetNoise
def kernelNoise(kernelSize,num_octaves,persistence,currentBand,dimensions=2):
simplex = SimplexNoise(num_octaves,dimensions)
data = []
for i in range(kernelSize):
data.append([])
i1 = i - int(kernelSize / 2)
for j in range(kernelSize):
j1 = j - int(kernelSize / 2)
if(shouldPixelGetNoise(i1,j1,currentBand)):
noise = normalize(simplex.fractal(i,j,hgrid=kernelSize))
data[i].append(noise * 255)
else:
data[i].append(0)
我只获得了凸二次函数的良好输出。如果我尝试将它们组合起来,我会得到一个黑色图像。 Sin
根本不起作用。我看到这种蛮力方法不会将我带到任何地方,所以我想知道我应该使用什么算法来生成这些类型的图像?
解决方法
据我所知,您想绘制函数并填充这些函数的上方或下方。您可以通过在 numpy
中创建网格(即 2D 笛卡尔坐标系)并在网格上定义函数来轻松完成此操作。
import numpy as np
import matplotlib.pyplot as plt
max_ax = 100
resolution_x = max_ax/5
resolution_y = max_ax/20
y,x = np.ogrid[-max_ax:max_ax+1,-max_ax:max_ax+1]
y,x = y/resolution_y,x/resolution_x
func1 = x**2 + 2*x + 5 <= -y
resolution_x = max_ax
resolution_y = max_ax
y,x/resolution_x
func2 = np.sin(6*x) <= y
func3 = np.tan(x) <= -y
fig,ax = plt.subplots(1,3)
ax[0].set_title('f(x)=x**2 + 2*x + 5')
ax[0].imshow(func1,cmap='gray')
ax[1].set_title('f(x)=sin(6*x)')
ax[1].imshow(func2,cmap='gray')
ax[2].set_title('f(x)=tan(x)')
ax[2].imshow(func3,cmap='gray')
plt.show()
这是您要找的吗?
编辑:我调整了 x 轴和 y 轴的限制。因为,例如,sin(x)
在范围 [-1,1] 之外没有多大意义。