-1

我正在尝试重写这篇文章:我们画画,编程。从 Python 中的伪代码机器生成向量场(俄语)中的艺术图案。我是 ML 新手,因此出现以下问题:如何构建角度网格并通过 PyCharm 输出?我在这个阶段:

import numpy as np
import math
import matplotlib.pyplot as plt

width = 100
height = 100

left_x = int(width * -0.5)
right_x = int(width * 1.5)
top_y = int(height * -0.5)
bottom_y = int(height * 1.5)

resolution = int(width * 0.01)

num_columns = int((right_x - left_x) / resolution)
num_rows = int((bottom_y - top_y) / resolution)

grid=np.ndarray((num_columns, num_rows))
grid[:,:]=math.pi * 0.25

在这段代码中,我创建了一个 200 行和 200 列的网格数组,其中插入了角度“default_angle”。请告诉我我是否朝着正确的方向前进以及如何“绘制”网格,如附加链接中所示。到目前为止,我认为我需要使用 matplotlib。

4

2 回答 2

1

我相信你需要看看 numpy 的 meshgrid

来自 meshgrid 文档示例:

x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
h = plt.contourf(x,y,z)

编辑。看到你链接后,一个更好的资源是matplotlib quiver demo

import matplotlib.pyplot as plt
import numpy as np

X = np.arange(-10, 10, 1)
Y = np.arange(-10, 10, 1)
U, V = np.meshgrid(X, Y)

fig, ax = plt.subplots()
q = ax.quiver(X, Y, U, V)
ax.quiverkey(q, X=0.3, Y=1.1, U=10,
             label='Quiver key, length = 10', labelpos='E')

plt.show()
于 2020-02-12T08:36:56.820 回答
0

您需要执行几个步骤来重新创建它:

  1. 基于某些函数或方程创建向量场
  2. 标准化箭头以正确显示
  3. 画线 3.1。3.2. 设置启动参数 列出while条件 3.3。根据起点的角度计算新位置 3.4。获得新的位置索引-> 净新角度 3.5。更新起始位置
  4. 绘制矢量场和线

将 numpy 导入为 np 将 matplotlib.pyplot 导入为 plt

size = 50
X = np.arange(1, size, 1)
Y = np.arange(1, size, 1)
U, V = np.meshgrid(X, Y)

# Normalize the arrows:
U = U / np.sqrt(U**2 + V**2)
V = V / np.sqrt(U**2 + V**2)

# create angles field
data = []
for i in np.linspace(0, 180, Y.shape[0]):
    data.append([i]*X.shape[0])

angle = np.array(data)

# set starting parameters
x_start_position = 2
y_start_position = 2
step_length = 1.0
point_angle = angle[x_start_position, y_start_position]
line_coordinates = [[x_start_position, y_start_position]]

# collect line points for each step
while x_start_position >= 2:

    # calculate tep based on angle
    x_step = step_length * np.cos(point_angle*np.pi/180)
    y_step = step_length * np.sin(point_angle*np.pi/180)

    # calculate new position
    x_new_position = x_start_position + x_step
    y_new_position = y_start_position + y_step

    # get array index of new position
    x_new_index = int(x_new_position)
    y_new_index = int(y_new_position)

    # get new angle
    point_angle = angle[y_new_index, x_new_index]

    # update start position
    x_start_position = x_new_position
    y_start_position = y_new_position

    # collect results
    line_coordinates.append([x_new_position, y_new_position])

# set line coordinates
line_data = np.array(line_coordinates)
x_line = line_data[:,0]
y_line = line_data[:,1]

# plot field
plt.quiver(X, Y, U, V, color='black', angles=angle, width=0.005)
# plot line
plt.plot(x_line, y_line, '-', color='red')
plt.show()

输出:

在此处输入图像描述

于 2020-02-12T11:11:53.223 回答