dev: Добавлен скрипт points_generator.py, который генерирует исходные файлы

Дополнительно был проведён некоторый рефактор основных скриптов
This commit is contained in:
Павел Набока 2023-09-11 16:26:22 +03:00
parent c10873e19f
commit b7c35336d3
4 changed files with 53 additions and 5 deletions

2
.gitignore vendored
View File

@ -1 +1,3 @@
poetry.lock
/expected_points.txt
/actual_points.txt

16
main.py
View File

@ -3,7 +3,7 @@ from pathlib import Path
import numpy
from matplotlib import pyplot
from transformations import centroid, calculate_rotation_matrix, convert_rotation_matrix_to_angles
from transformations import calculate_rotation_matrix, centroid, convert_rotation_matrix_to_angles
expected_points_file_path = Path('expected_points.txt')
actual_points_file_path = Path('actual_points.txt')
@ -21,6 +21,11 @@ if __name__ == '__main__':
expected_points = read_points_from_file(expected_points_file_path)
actual_points = read_points_from_file(actual_points_file_path)
plot_3d.plot(expected_points[:, 0], expected_points[:, 1], expected_points[:, 2],
'o-', markersize=12, linewidth=3, label='Expected Points')
plot_3d.plot(actual_points[:, 0], actual_points[:, 1], actual_points[:, 2],
'o-', markersize=12, linewidth=3, label='Actual Points')
rotation_matrix = calculate_rotation_matrix(actual_points, expected_points)
angles = convert_rotation_matrix_to_angles(rotation_matrix)
@ -30,10 +35,13 @@ if __name__ == '__main__':
actual_points_converted = actual_points_rotated - offset
print(f"{angles = }")
print(f"{offset = }")
plot_3d.plot(actual_points_converted[:, 0], actual_points_converted[:, 1], actual_points_converted[:, 2], 'o-', markersize=12, linewidth=3)
plot_3d.plot(expected_points[:, 0], expected_points[:, 1], expected_points[:, 2], 'o-', markersize=12, linewidth=3)
print(f"offset = {tuple(offset)}")
plot_3d.plot(actual_points_converted[:, 0], actual_points_converted[:, 1], actual_points_converted[:, 2],
'o-', markersize=12, linewidth=3, label='Transformed actual points')
plot_3d.grid(True)
plot_3d.tick_params(labelsize=15)
pyplot.legend()
pyplot.show()

35
points_generator.py Normal file
View File

@ -0,0 +1,35 @@
#!/usr/bin/env python
from pathlib import Path
import numpy as np
def rotation_matrix(sigma: float) -> np.ndarray:
radians = sigma * np.pi / 180.0
r11 = np.cos(radians)
r12 = -np.sin(radians)
r21 = np.sin(radians)
r22 = np.cos(radians)
R = np.array([[r11, r12, 0], [r21, r22, 0], [0, 0, 1]])
return R
A = np.array([[1.0, 1.0, 0.0], [1.0, 2.0, 1.0], [2.0, 1.5, 2.0], [0.0, 0.5, 3.0]])
with Path('expected_points.txt').open('w') as actual_points_output_file:
for line in A:
actual_points_output_file.write(' '.join((str(number) for number in line)) + '\n')
B = A.copy()
B *= 1.4
B -= 3
B = np.dot(B, rotation_matrix(90))
with Path('actual_points.txt').open('w') as actual_points_output_file:
for line in B:
actual_points_output_file.write(' '.join((str(number) for number in line)) + '\n')

View File

@ -13,9 +13,11 @@ def calculate_rotation_matrix(actual_points: numpy.ndarray,
expected_points: numpy.ndarray) -> numpy.ndarray:
"""
Вычисление матрицы поворота, который необходим для приближения текущих точек к ожидаемым, на основе алгоритма Кабша
:param actual_points: массив текущих точек
:param expected_points: массив ожидаемых точек
:return: Матрица поворотов
"""
# Для применения алгоритма Кабша необходимо,
# чтобы центроиды обрабатываемых массивов точек совпадали с началом координат
@ -39,10 +41,11 @@ def calculate_rotation_matrix(actual_points: numpy.ndarray,
def convert_rotation_matrix_to_angles(rotation_matrix: numpy.ndarray) -> Tuple[float, float, float]:
"""
Вычисление углов поворота модели на основе применяемой к ней матрицы поворота
:param rotation_matrix: матрица поворота
:return: Кортеж из трёх углов - угол поворота вокруг оси X, угол поворота вокруг оси Y, угол поворота вокруг оси Z
"""
# TODO Требует доработки, так как иногда может всплывать деление на 0
alpha = numpy.arccos(rotation_matrix[2, 2] / (1 - rotation_matrix[0, 2] ** 2) ** 0.5)
beta = numpy.arcsin(rotation_matrix[0, 2])
gamma = numpy.arccos(rotation_matrix[0, 0] / (1 - rotation_matrix[0, 2] ** 2) ** 0.5)