ref: tests

This commit is contained in:
2025-06-30 02:36:57 +03:00
parent 2c202af51f
commit 9a289bd372
4 changed files with 262 additions and 2 deletions

View File

@@ -0,0 +1,96 @@
#!/usr/bin/env python3
"""
Тестовый скрипт для проверки работы с координатами относительно центра изображения
"""
import numpy as np
from PIL import Image
import cv2
from autopilot import AutoPilot
def test_center_coordinates():
"""Тестирует работу с координатами относительно центра изображения"""
print("Тест координат относительно центра изображения...")
# Создаем тестовое изображение
width, height = 640, 480
test_image = np.zeros((height, width, 3), dtype=np.uint8)
# Добавляем некоторые объекты для отслеживания
cv2.circle(test_image, (width//2, height//2), 50, (255, 255, 255), -1) # Центр
cv2.circle(test_image, (100, 100), 20, (255, 0, 0), -1) # Левый верхний угол
cv2.circle(test_image, (width-100, height-100), 20, (0, 255, 0), -1) # Правый нижний угол
# Создаем второе изображение с небольшим смещением
test_image2 = np.zeros((height, width, 3), dtype=np.uint8)
cv2.circle(test_image2, (width//2 + 10, height//2 + 5), 50, (255, 255, 255), -1) # Смещенный центр
cv2.circle(test_image2, (110, 105), 20, (255, 0, 0), -1) # Смещенный левый верхний угол
cv2.circle(test_image2, (width-90, height-95), 20, (0, 255, 0), -1) # Смещенный правый нижний угол
# Конвертируем в PIL Image
pil_image1 = Image.fromarray(test_image)
pil_image2 = Image.fromarray(test_image2)
# Создаем автопилот
pilot = AutoPilot(initial_x=0.0, initial_y=0.0)
print(f"Размер изображения: {width}x{height}")
print(f"Ожидаемый центр: ({width//2}, {height//2})")
# Обрабатываем первое изображение
pilot.handle(pil_image1)
print(f"Центр изображения после первого кадра: {pilot.image_center}")
# Обрабатываем второе изображение
pilot.handle(pil_image2)
print(f"Центр изображения после второго кадра: {pilot.image_center}")
# Получаем состояние дрона
drone_state = pilot.get_drone_state()
print(f"Позиция дрона: ({drone_state['x']:.2f}, {drone_state['y']:.2f})")
print(f"Угол дрона: {drone_state['angle_degrees']:.1f}°")
print("\nАнализ отцентрированных координат:")
print("Ожидаемое смещение центра: (10, 5) пикселей")
print("Ожидаемое смещение левого верхнего угла: (10, 5) пикселей")
print("Ожидаемое смещение правого нижнего угла: (10, 5) пикселей")
print("Тест завершен!")
def test_keypoint_centering():
"""Тестирует отцентрирование ключевых точек"""
print("\nТест отцентрирования ключевых точек...")
# Создаем простое изображение с одной точкой
width, height = 100, 100
test_image = np.zeros((height, width, 3), dtype=np.uint8)
cv2.circle(test_image, (25, 25), 5, (255, 255, 255), -1) # Точка в (25, 25)
# Создаем второе изображение с той же точкой
test_image2 = np.zeros((height, width, 3), dtype=np.uint8)
cv2.circle(test_image2, (25, 25), 5, (255, 255, 255), -1)
# Конвертируем в PIL Image
pil_image1 = Image.fromarray(test_image)
pil_image2 = Image.fromarray(test_image2)
# Создаем автопилот
pilot = AutoPilot(initial_x=0.0, initial_y=0.0)
print(f"Размер изображения: {width}x{height}")
print(f"Центр изображения: ({width//2}, {height//2}) = (50, 50)")
print(f"Позиция точки: (25, 25)")
print(f"Ожидаемые отцентрированные координаты: (25-50, 25-50) = (-25, -25)")
# Обрабатываем изображения
pilot.handle(pil_image1)
pilot.handle(pil_image2)
drone_state = pilot.get_drone_state()
print(f"Результат: позиция дрона ({drone_state['x']:.2f}, {drone_state['y']:.2f})")
print("Тест завершен!")
if __name__ == "__main__":
test_center_coordinates()
test_keypoint_centering()

View File

@@ -1,7 +1,13 @@
#!/usr/bin/env python3
"""
Тестовый скрипт для проверки системы отслеживания траектории беспилотника
"""
import numpy as np
from PIL import Image
import cv2
from autopilot import AutoPilot
from autopilot import AutoPilot, RandomPilot
from simulator import Simulator, SimMode
import matplotlib.pyplot as plt
import time
@@ -156,6 +162,32 @@ def test_single_frame():
cv2.destroyAllWindows()
def test_trajectory_tracking():
"""Тестирует систему отслеживания траектории"""
print("Запуск теста системы отслеживания траектории...")
# Создаем пилотов
operator_pilot = RandomPilot(velocity=1.0)
autonome_pilot = AutoPilot(initial_x=0.0, initial_y=0.0)
# Создаем симулятор
simulator = Simulator(operator_pilot, autonome_pilot)
try:
# Запускаем симуляцию
simulator.loop()
print("Симуляция завершена!")
print(f"Всего точек траектории: {len(simulator.trajectory_x)}")
print(f"Режим оператора: {sum(1 for mode in simulator.trajectory_modes if mode == SimMode.OPERATOR)} точек")
print(f"Автономный режим: {sum(1 for mode in simulator.trajectory_modes if mode == SimMode.AUTONOME)} точек")
except Exception as e:
print(f"Ошибка во время симуляции: {e}")
finally:
# Закрываем браузер
simulator.driver.quit()
if __name__ == "__main__":
print("Выберите тест:")
print("1. Тест одного кадра")
@@ -166,7 +198,7 @@ if __name__ == "__main__":
if choice == "1":
test_single_frame()
elif choice == "2":
test_drone_tracking()
test_trajectory_tracking()
else:
print("Неверный выбор. Запускаю тест одного кадра...")
test_single_frame()

View File

@@ -0,0 +1,65 @@
#!/usr/bin/env python3
"""
Тестовый скрипт для проверки единой системы визуализации
"""
import numpy as np
from PIL import Image
import cv2
from autopilot import AutoPilot, RandomPilot
from simulator import Simulator
from visualization import VisualizationManager, SimMode
def test_unified_visualization():
"""Тестирует единую систему визуализации"""
print("Тест единой системы визуализации...")
# Создаем менеджер визуализации
viz_manager = VisualizationManager("Test - Unified Visualization")
# Создаем автопилот с менеджером визуализации
autonome_pilot = AutoPilot(initial_x=0.0, initial_y=0.0, viz_manager=viz_manager)
# Создаем симулятор
simulator = Simulator(RandomPilot(), autonome_pilot)
# Создаем тестовые изображения
width, height = 640, 480
test_image1 = np.zeros((height, width, 3), dtype=np.uint8)
test_image2 = np.zeros((height, width, 3), dtype=np.uint8)
# Добавляем объекты для отслеживания
cv2.circle(test_image1, (width//2, height//2), 50, (255, 255, 255), -1)
cv2.circle(test_image1, (100, 100), 20, (255, 0, 0), -1)
cv2.circle(test_image2, (width//2 + 10, height//2 + 5), 50, (255, 255, 255), -1)
cv2.circle(test_image2, (110, 105), 20, (255, 0, 0), -1)
# Конвертируем в PIL Image
pil_image1 = Image.fromarray(test_image1)
pil_image2 = Image.fromarray(test_image2)
print("Обрабатываем первое изображение...")
autonome_pilot.handle(pil_image1)
print("Обрабатываем второе изображение...")
autonome_pilot.handle(pil_image2)
# Обновляем визуализацию
viz_manager.update_display()
# Получаем состояние дрона
drone_state = autonome_pilot.get_drone_state()
print(f"Позиция дрона: ({drone_state['x']:.2f}, {drone_state['y']:.2f})")
print(f"Угол дрона: {drone_state['angle_degrees']:.1f}°")
print("Тест завершен! Окно визуализации должно показывать:")
print("- Глобальную карту с траекторией")
print("- Детекцию ключевых точек")
print("- Сопоставление точек между кадрами")
# Показываем финальное состояние
viz_manager.show_final()
if __name__ == "__main__":
test_unified_visualization()

View File

@@ -0,0 +1,67 @@
#!/usr/bin/env python3
"""
Упрощенный тест для проверки системы визуализации без браузера
"""
import numpy as np
from PIL import Image
import cv2
from autopilot import AutoPilot
from visualization import VisualizationManager, SimMode
def test_visualization_only():
"""Тестирует только систему визуализации без симулятора"""
print("Тест системы визуализации...")
# Создаем менеджер визуализации
viz_manager = VisualizationManager("Test - Visualization Only")
# Создаем автопилот с менеджером визуализации
autonome_pilot = AutoPilot(initial_x=0.0, initial_y=0.0, viz_manager=viz_manager)
# Создаем тестовые изображения
width, height = 640, 480
test_image1 = np.zeros((height, width, 3), dtype=np.uint8)
test_image2 = np.zeros((height, width, 3), dtype=np.uint8)
# Добавляем объекты для отслеживания
cv2.circle(test_image1, (width//2, height//2), 50, (255, 255, 255), -1)
cv2.circle(test_image1, (100, 100), 20, (255, 0, 0), -1)
cv2.circle(test_image1, (width-100, height-100), 20, (0, 255, 0), -1)
cv2.circle(test_image2, (width//2 + 10, height//2 + 5), 50, (255, 255, 255), -1)
cv2.circle(test_image2, (110, 105), 20, (255, 0, 0), -1)
cv2.circle(test_image2, (width-90, height-95), 20, (0, 255, 0), -1)
# Конвертируем в PIL Image
pil_image1 = Image.fromarray(test_image1)
pil_image2 = Image.fromarray(test_image2)
print("Обрабатываем первое изображение...")
autonome_pilot.handle(pil_image1)
print("Обрабатываем второе изображение...")
autonome_pilot.handle(pil_image2)
# Симулируем движение дрона
print("Симулируем движение дрона...")
for i in range(10):
# Обновляем глобальную карту
viz_manager.update_global_map(i * 10, i * 5, SimMode.OPERATOR if i < 5 else SimMode.AUTONOME)
viz_manager.update_display()
# Получаем состояние дрона
drone_state = autonome_pilot.get_drone_state()
print(f"Позиция дрона: ({drone_state['x']:.2f}, {drone_state['y']:.2f})")
print(f"Угол дрона: {drone_state['angle_degrees']:.1f}°")
print("Тест завершен! Окно визуализации должно показывать:")
print("- Глобальную карту с траекторией (синий - оператор, красный - автономный)")
print("- Детекцию ключевых точек на текущем кадре")
print("- Сопоставление точек между кадрами")
# Показываем финальное состояние
viz_manager.show_final()
if __name__ == "__main__":
test_visualization_only()