/
ParaD
/
Server
Обзор
Документация
Войти
/
ParaD
/
Server
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
frontend_deviant.py
169 строк
8 KB
Rayfaga
first_commit
01 мар 2025, 20:02
01 мар 2025, 20:02
c75de2b
Код
Авторство
О чём код?
import cv2 import time import sys import os import pygame from fight_detection import Fight_utils from multiprocessing import Process # Константы для записи видео VIDEO_DURATION = 5 # длительность записи в секундах FRAME_WIDTH = 1280 FRAME_HEIGHT = 720 FPS = 20 def analyze_video(video_path, camera_index): """ Анализирует видео на наличие драки. Если обнаружена – запускается окно Pygame для отображения видео и реакции пользователя. """ result = Fight_utils.fightDetection(video_path, 20, 1, './', True) # Предполагается, что если в результате содержится "noFight" – это означает обнаружение проблемы if "fight" in result: print(f"[Камера {camera_index}] Обнаружена драка!") show_video_pygame(video_path, camera_index) else: print(f"[Камера {camera_index}] Драка не обнаружена.") def show_video_pygame(video_path, camera_index): """ Отображает видео в Pygame-окне и ждёт нажатия одной из кнопок. Окно остается открытым до тех пор, пока пользователь его не закроет. """ # Получаем размеры экрана pygame.init() screen = pygame.display.set_mode((pygame.display.Info().current_w, pygame.display.Info().current_h)) screen_info = pygame.display.Info() screen_width, screen_height = screen_info.current_w, screen_info.current_h pygame.display.set_caption(f"Камера {camera_index}: Обнаружена драка") background_color = (221, 250, 221) button_color = (200, 200, 200) button_hover_color = (150, 150, 150) text_color = (0, 0, 0) font = pygame.font.SysFont("Arial", 24, bold = True) # Определяем размеры и позицию кнопок (отображаются внизу экрана) button_width = 300 button_height = 50 left_button_rect = pygame.Rect(50, screen_height - button_height - 50, button_width, button_height) right_button_rect = pygame.Rect(screen_width - button_width - 50, screen_height - button_height - 50, button_width, button_height) cap = cv2.VideoCapture(video_path) clock = pygame.time.Clock() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.MOUSEBUTTONDOWN: if left_button_rect.collidepoint(event.pos): print("Спасибо! Угроза устранена.") running = False elif right_button_rect.collidepoint(event.pos): print("Ошибка! Будь внимательнее!") running = False screen.fill(background_color) ret, frame = cap.read() if not ret: # Если видео закончилось, начинаем воспроизведение сначала cap.set(cv2.CAP_PROP_POS_FRAMES, 0) continue # Поворачиваем и зеркально отражаем кадр (при необходимости) frame = cv2.rotate(frame, cv2.ROTATE_90_CLOCKWISE) frame = cv2.flip(frame, 2) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame_surface = pygame.surfarray.make_surface(frame) # Центрируем видео на экране x_offset = (screen_width - FRAME_WIDTH) // 2 y_offset = (screen_height - FRAME_HEIGHT - 100) // 2 # резервируем место для кнопок внизу screen.blit(frame_surface, (x_offset, y_offset)) # Отрисовка кнопок с эффектом наведения mouse_pos = pygame.mouse.get_pos() left_color = button_hover_color if left_button_rect.collidepoint(mouse_pos) else button_color right_color = button_hover_color if right_button_rect.collidepoint(mouse_pos) else button_color pygame.draw.rect(screen, left_color, left_button_rect) pygame.draw.rect(screen, right_color, right_button_rect) left_text = font.render("Спасибо! Угроза устранена", True, text_color) right_text = font.render("Ошибка! Будь внимательнее!", True, text_color) screen.blit(left_text, left_text.get_rect(center=left_button_rect.center)) screen.blit(right_text, right_text.get_rect(center=right_button_rect.center)) pygame.display.flip() clock.tick(30) cap.release() pygame.quit() def process_camera(camera_input, camera_index): """ Запускает цикл записи и анализа видео для одной камеры. Определяет тип входных данных: если число – USB-камера, иначе – IP-камера. """ # Если строка состоит только из цифр – это индекс USB-камеры if camera_input.isdigit(): source = int(camera_input) else: # Если протокол не указан, формируем URL для IP-камеры if "://" not in camera_input: source = f"http://{camera_input}/video" else: source = camera_input while True: print(f"[Камера {camera_index}] Начало записи (источник: {source})") cap = cv2.VideoCapture(source) if not cap.isOpened(): print(f"[Камера {camera_index}] Не удалось подключиться к источнику: {source}") time.sleep(5) continue # Создаем каталог для сохранения видео и формируем имя файла с отметкой времени os.makedirs('./for_video', exist_ok=True) timestamp = int(time.time()) video_path = f"./for_video/camera_{camera_index}_{timestamp}.mp4" fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(video_path, fourcc, FPS, (FRAME_WIDTH, FRAME_HEIGHT)) start_time = time.time() while time.time() - start_time < VIDEO_DURATION: ret, frame = cap.read() if not ret: print(f"[Камера {camera_index}] Не удалось получить кадр. Пропуск...") continue frame = cv2.resize(frame, (FRAME_WIDTH, FRAME_HEIGHT)) out.write(frame) out.release() cap.release() # Анализируем записанное видео (данный процесс работает параллельно для каждой камеры) analyze_video(video_path, camera_index) # Небольшая задержка между циклами записи time.sleep(1) def main(): """ Основная функция: - Считывает список камер из файла (каждая строка – либо числовой индекс, либо IP:порт); - Запускает отдельный процесс для каждой камеры. """ # Чтение входных данных (убираем пустые строки) with open('./variable_txt/camers.txt', 'r') as f: camera_lines = [line.strip() for line in f if line.strip()] processes = [] for index, cam in enumerate(camera_lines, start=1): p = Process(target=process_camera, args=(cam, index)) p.start() processes.append(p) # Ожидаем завершения всех процессов (на практике процессы могут работать бесконечно) for p in processes: p.join() if __name__ == "__main__": main()