Машинная генерация художественных узоров в векторных полях - PullRequest
0 голосов
/ 12 февраля 2020

Я пытаюсь переписать эту статью: Рисуем, программируем. Генерируемое машиной шаблонов artisti c в векторных полях (русский язык) из псевдокода в 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.

Ответы [ 2 ]

1 голос
/ 12 февраля 2020

Полагаю, вам нужно взглянуть на сетку из numpy

из примеров документации по сетке:

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

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()
0 голосов
/ 12 февраля 2020

Вам нужно сделать несколько шагов, чтобы воссоздать это:

  1. создать векторное поле на основе некоторой функции или уравнения
  2. нормализовать стрелки для правильного отображения
  3. нарисовать линию 3.1. установить стартовые параметры 3.2. установить while выходное условие 3.3. рассчитать новую позицию на основе угла от начальной точки 3.4. получить новый индекс позиции -> net новый угол 3.5. обновить начальные позиции
  4. нарисовать векторное поле и линию

import numpy как np import 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()

Вывод:

enter image description here

...