from djitellopy import Tello
import cv2
from ultralytics import YOLO
import time
# Загружаем модель
model = YOLO('yolov8n.pt')
# Подключаем дрон
tello = Tello()
tello.connect()
print(f"Батарея: {tello.get_battery()}%")
# Включаем видео
tello.streamon()
time.sleep(2)
# Взлетаем
tello.takeoff()
time.sleep(3)
# Параметры слежения
frame_width = 640
frame_height = 480
center_x = frame_width // 2
tolerance = 80 # зона нечувствительности (пикселей)
print("Слежение активно. Нажмите 'q' для посадки и выхода.")
while True:
# Получаем кадр
frame = tello.get_frame_read().frame
if frame is None:
continue
frame = cv2.resize(frame, (frame_width, frame_height))
# Детектируем людей (класс 0)
results = model(frame, classes=[0], verbose=False, conf=0.5)
person_detected = False
for r in results:
if r.boxes is not None:
for box in r.boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0])
person_center_x = (x1 + x2) // 2
# Рисуем рамку и центр
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2)
cv2.circle(frame, (person_center_x, frame_height//2), 5, (0, 0, 255), -1)
# Управление дроном
if person_center_x < center_x - tolerance:
print("Лечу влево")
tello.move_left(30)
elif person_center_x > center_x + tolerance:
print("Лечу вправо")
tello.move_right(30)
else:
print("В центре, зависаю")
person_detected = True
break # берём первого найденного
if not person_detected:
print("Человек не найден, ищу поворотом")
tello.rotate_clockwise(20)
# Показываем видео
cv2.imshow("Follow Me", frame)
# Выход по клавише 'q'
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Посадка и завершение
tello.land()
tello.streamoff()
cv2.destroyAllWindows()