commit ec994e6a674a8bde924a2fc27d2a2368524efb09 Author: Ilya_Chis Date: Tue Apr 8 16:50:09 2025 +0500 YoloV8 diff --git a/YoloV8nc/.idea/.gitignore b/YoloV8nc/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/YoloV8nc/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/YoloV8nc/.idea/YOLOv8.iml b/YoloV8nc/.idea/YOLOv8.iml new file mode 100644 index 0000000..2c80e12 --- /dev/null +++ b/YoloV8nc/.idea/YOLOv8.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/YoloV8nc/.idea/inspectionProfiles/profiles_settings.xml b/YoloV8nc/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/YoloV8nc/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/YoloV8nc/.idea/misc.xml b/YoloV8nc/.idea/misc.xml new file mode 100644 index 0000000..802d73f --- /dev/null +++ b/YoloV8nc/.idea/misc.xml @@ -0,0 +1,7 @@ + + + + + + \ No newline at end of file diff --git a/YoloV8nc/.idea/modules.xml b/YoloV8nc/.idea/modules.xml new file mode 100644 index 0000000..fca4f23 --- /dev/null +++ b/YoloV8nc/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/YoloV8nc/main.py b/YoloV8nc/main.py new file mode 100644 index 0000000..c40421d --- /dev/null +++ b/YoloV8nc/main.py @@ -0,0 +1,37 @@ +import cv2 +from ultralytics import YOLO + +# Загрузим YOLOv8 модель (если ты скачал .pt файл вручную, укажи путь) +model = YOLO('yolov8n.pt') # автоматически скачается, если файла нет + +# Открываем веб-камеру +cap = cv2.VideoCapture(0) + +while True: + ret, frame = cap.read() + if not ret: + break + + # Детекция объектов + results = model(frame)[0] + + for result in results.boxes: + cls_id = int(result.cls[0]) + conf = float(result.conf[0]) + if model.names[cls_id] == 'person': + x1, y1, x2, y2 = map(int, result.xyxy[0]) + # Зелёная рамка + cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) + # Текст + label = f'{model.names[cls_id]} {conf:.2f}' + cv2.putText(frame, label, (x1, y1 - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 1) + + # Показываем результат + cv2.imshow("Detection", frame) + + # Выход — по клавише ESC + if cv2.waitKey(1) & 0xFF == 27: + break + +cap.release() +cv2.destroyAllWindows() diff --git a/YoloV8nc/recorder.py b/YoloV8nc/recorder.py new file mode 100644 index 0000000..f681cc7 --- /dev/null +++ b/YoloV8nc/recorder.py @@ -0,0 +1,99 @@ +import cv2 +import time +import os +from ultralytics import YOLO +import logging + +# Отключаем вывод ненужных логов из ultralytics +logging.getLogger('ultralytics').setLevel(logging.WARNING) + +# Загружаем модель YOLOv8 +model = YOLO('yolov8n.pt') + +# Захват видео с камеры +cap = cv2.VideoCapture(0) + +# Устанавливаем разрешение для захвата кадров +cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920) +cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080) + +# Получаем FPS из камеры +fps = cap.get(cv2.CAP_PROP_FPS) +print(f"FPS камеры: {fps}") + +# Установим FPS записи видео равным FPS камеры +record_fps = fps # Записываем с FPS, который камера реально поддерживает + +# Время между кадрами (в секундах) +frame_interval = 1 / record_fps + +recording = False +record_start_time = 0 +out = None +last_frame_time = 0 + +# Путь для сохранения видео +save_dir = r'C:\Users\ilyac\PycharmProjects\YOLOv8\.venv\video' +os.makedirs(save_dir, exist_ok=True) # Создаст папку, если не существует + +# Используем кодек MJPG для записи видео с хорошим качеством +fourcc = cv2.VideoWriter_fourcc(*'MJPG') + +while True: + ret, frame = cap.read() + if not ret: + break + + # Применяем модель YOLOv8 для обнаружения объектов + results = model(frame)[0] + person_detected = False + + # Проходим по результатам и рисуем рамки вокруг людей + for result in results.boxes: + cls_id = int(result.cls[0]) + if model.names[cls_id] == 'person': + person_detected = True + x1, y1, x2, y2 = map(int, result.xyxy[0]) + # Уменьшаем ширину рамки на 20% + width_shrink = int((x2 - x1) * 0.2) + x1 += width_shrink + x2 -= width_shrink + cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) + + # Начинаем запись, если человек был обнаружен + if person_detected and not recording: + print("🟢 Обнаружен человек — начинаю запись на 10 секунд") + record_start_time = time.time() + timestamp = time.strftime('%Y-%m-%d_%H-%M-%S') + video_path = os.path.join(save_dir, f'person_{timestamp}.avi') + out = cv2.VideoWriter(video_path, fourcc, record_fps, (frame.shape[1], frame.shape[0])) + recording = True + + # Запись видео с интервалом времени + if recording: + current_time = time.time() + + # Пишем кадр в видео, если прошло достаточно времени + if current_time - last_frame_time >= frame_interval: + out.write(frame) + last_frame_time = current_time + + # Проверяем, прошло ли 10 секунд + if current_time - record_start_time >= 10: + print("🔴 10 секунд прошло — запись завершена") + recording = False + out.release() + out = None + + # Отображаем видео в окне + cv2.imshow("Live", frame) + + # Выход по клавише ESC + if cv2.waitKey(1) & 0xFF == 27: + break + +# Завершаем работу с камерой и записывающим устройством +cap.release() +if out: + out.release() +cv2.destroyAllWindows() diff --git a/YoloV8nc/run_video.py b/YoloV8nc/run_video.py new file mode 100644 index 0000000..0feb354 --- /dev/null +++ b/YoloV8nc/run_video.py @@ -0,0 +1,33 @@ +import cv2 +import time + +# Открытие видеофайла +cap = cv2.VideoCapture(r'C:\Users\ilyac\PycharmProjects\YOLOv8\.venv\video\person_2025-04-07_23-36-45.avi') # Укажите путь к вашему видеофайлу + +if not cap.isOpened(): + print("Ошибка при открытии видео!") + exit() + +# Получаем FPS видео (кадров в секунду) +fps = cap.get(cv2.CAP_PROP_FPS) +print(f"FPS видео: {fps}") + +while cap.isOpened(): + ret, frame = cap.read() + if not ret: + break # Если не удалось прочитать кадр, завершаем + + # Отображаем кадр + cv2.imshow('Video', frame) + + # Добавляем задержку между кадрами для замедления видео + # Если FPS = 30, а мы хотим воспроизводить в 2 раза медленным темпом, ставим задержку 2x + time.sleep(1 / fps * 4) # Умножаем на 2 для замедления воспроизведения + + # Выход из программы при нажатии клавиши 'ESC' + if cv2.waitKey(1) & 0xFF == 27: + break + +# Закрываем все окна и освобождаем ресурсы +cap.release() +cv2.destroyAllWindows() diff --git a/YoloV8nc/test_cam.py b/YoloV8nc/test_cam.py new file mode 100644 index 0000000..f24fd87 --- /dev/null +++ b/YoloV8nc/test_cam.py @@ -0,0 +1,19 @@ +import cv2 +import time + +cap = cv2.VideoCapture(0) +frames = 0 +start_time = time.time() + +print("⏱️ Считаем кадры в течение 3 секунд...") + +while time.time() - start_time < 3: + ret, frame = cap.read() + if not ret: + break + frames += 1 + +cap.release() +elapsed = time.time() - start_time +fps = frames / elapsed +print(f"📸 Реальный FPS камеры: {fps:.2f}") diff --git a/YoloV8nc/yolov8n.pt b/YoloV8nc/yolov8n.pt new file mode 100644 index 0000000..0db4ca4 Binary files /dev/null and b/YoloV8nc/yolov8n.pt differ