我正在尝试重写这篇文章:我们通过编程绘画。机器生成的矢量场中的艺术图案(俄语),从Python的伪代码开始。我对机器学习是新手,因此产生了以下问题:如何构建一个角度网格并通过PyCharm输出它?我目前处于这个阶段:
import numpy as npimport mathimport matplotlib.pyplot as pltwidth = 100height = 100left_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。
回答:
你需要采取几个步骤来重新创建这个效果:
- 基于某个函数或方程创建矢量场
- 标准化箭头以正确显示
- 绘制线条3.1. 设置起始参数3.2. 设置
while
循环的结束条件3.3. 根据起始点的角度计算新位置3.4. 获取新位置的索引 –> 获取新的角度3.5. 更新起始位置 - 绘制矢量场和线条
import numpy as np import matplotlib.pyplot as plt
size = 50X = 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 fielddata = []for i in np.linspace(0, 180, Y.shape[0]): data.append([i]*X.shape[0])angle = np.array(data)# set starting parametersx_start_position = 2y_start_position = 2step_length = 1.0point_angle = angle[x_start_position, y_start_position]line_coordinates = [[x_start_position, y_start_position]]# collect line points for each stepwhile 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 coordinatesline_data = np.array(line_coordinates)x_line = line_data[:,0]y_line = line_data[:,1]# plot fieldplt.quiver(X, Y, U, V, color='black', angles=angle, width=0.005)# plot lineplt.plot(x_line, y_line, '-', color='red')plt.show()
输出: