WpythonW commited on
Commit
8ae97f5
·
verified ·
1 Parent(s): 1253ac4

Upload 6 files

Browse files
VideoProcessor.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import torch
4
+ import pandas as pd
5
+ from tqdm import tqdm
6
+ from ultralytics import YOLO
7
+ from PIL import Image
8
+ import pillow_heif
9
+ import numpy as np
10
+
11
+ class MediaProcessor:
12
+ def __init__(self, output_path, model_path, batch_size=16):
13
+ self.output_path = output_path
14
+ self.model_path = model_path
15
+ self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
16
+ self.model = YOLO(self.model_path).to(self.device)
17
+ self.colors = {
18
+ 0: (255, 0, 0), # quadrotor - красный
19
+ 1: (0, 255, 0), # airplane - зеленый
20
+ 2: (0, 0, 255), # helicopter - синий
21
+ 3: (255, 255, 0), # bird - желтый
22
+ 4: (255, 0, 255) # uav-plane - фиолетовый
23
+ }
24
+ self.batch_size = batch_size
25
+
26
+ def process_single_video(self, video_path):
27
+ cap = cv2.VideoCapture(video_path)
28
+ output_video_path = os.path.join(self.output_path, os.path.basename(video_path))
29
+ fourcc = cv2.VideoWriter_fourcc(*'avc1')#*'avc1')
30
+ fps = cap.get(cv2.CAP_PROP_FPS)
31
+ out = cv2.VideoWriter(output_video_path, fourcc, fps, (int(cap.get(3)), int(cap.get(4))))
32
+
33
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
34
+ frames = []
35
+
36
+ columns = ['frame_num', 'timestamp', 'class', 'confidence', 'x1', 'y1', 'x2', 'y2']
37
+ data = []
38
+
39
+ frame_num = 0
40
+
41
+ with tqdm(total=total_frames, desc=f"Processing Video {os.path.basename(video_path)}", position=0, leave=True) as pbar:
42
+ while cap.isOpened():
43
+ ret, frame = cap.read()
44
+ if not ret:
45
+ break
46
+
47
+ frames.append(frame)
48
+ frame_num += 1
49
+
50
+ if len(frames) == self.batch_size or frame_num == total_frames:
51
+ results = self.model(frames, verbose=False)
52
+
53
+ for i, result in enumerate(results):
54
+ current_frame_num = frame_num - len(frames) + i + 1
55
+ timestamp = current_frame_num / fps
56
+ for box in result.boxes:
57
+ x1, y1, x2, y2 = box.xyxy[0].tolist()
58
+ conf = box.conf[0].item()
59
+ cls = box.cls[0].item()
60
+ label = f'{self.model.names[int(cls)]} {conf:.2f}'
61
+ color = self.colors.get(int(cls), (0, 255, 0))
62
+ cv2.rectangle(frames[i], (int(x1), int(y1)), (int(x2), int(y2)), color, 1)
63
+ cv2.putText(frames[i], label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 1)
64
+
65
+ data.append([current_frame_num, timestamp, self.model.names[int(cls)], conf, int(x1), int(y1), int(x2), int(y2)])
66
+
67
+ out.write(frames[i])
68
+ pbar.update(1)
69
+
70
+ frames = []
71
+
72
+ cap.release()
73
+ out.release()
74
+ cv2.destroyAllWindows()
75
+
76
+ df = pd.DataFrame(data, columns=columns)
77
+ df.to_csv(os.path.join('metadata', f"{os.path.basename(video_path)}_detection_results.csv"), index=False)
78
+ print(df)
79
+ return output_video_path
80
+
81
+ def load_image(self, path):
82
+ if path.lower().endswith('.heic'):
83
+ heif_file = pillow_heif.open_heif(path)
84
+ image = Image.frombytes(
85
+ heif_file.mode,
86
+ heif_file.size,
87
+ heif_file.data,
88
+ "raw",
89
+ heif_file.mode,
90
+ heif_file.stride,
91
+ )
92
+ return cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
93
+ else:
94
+ return cv2.imread(path)
95
+
96
+ def process_images(self, input_paths):
97
+ images = [self.load_image(path) for path in input_paths]
98
+ results = self.model(images, verbose=False)
99
+ #print(results)
100
+ processed_images = []
101
+
102
+ for i, result in enumerate(results):
103
+ for box in result.boxes:
104
+ x1, y1, x2, y2 = box.xyxy[0].tolist()
105
+ conf = box.conf[0].item()
106
+ cls = box.cls[0].item()
107
+ label = f'{self.model.names[int(cls)]} {conf:.2f}'
108
+ color = self.colors.get(int(cls), (0, 255, 0))
109
+ cv2.rectangle(images[i], (int(x1), int(y1)), (int(x2), int(y2)), color, 2)
110
+ cv2.putText(images[i], label, (int(x1), int(y1) - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
111
+
112
+ # Сохраняем все изображения в формате PNG
113
+ processed_image_path = os.path.join(self.output_path, str(os.path.splitext(os.path.basename(input_paths[i]))[0]) + '.png')
114
+ print(f"Сохранение изображения по пути: {processed_image_path}")
115
+ processed_image = Image.fromarray(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))
116
+ processed_image.save(processed_image_path, format='PNG')
117
+ processed_images.append(processed_image_path)
118
+
119
+ return processed_images
120
+
121
+ def process_videos(self, input_paths):
122
+ vids = []
123
+ for video_path in input_paths:
124
+ output_video_path = self.process_single_video(video_path)
125
+ vids.append(output_video_path)
126
+ return vids
127
+
128
+ def process_media(input_paths, processor):
129
+ image_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff', '.heic', '.heif', '.webp')
130
+ video_extensions = ('.mp4', '.avi', '.mov', '.mkv', '.flv', '.wmv', '.webm')
131
+
132
+ image_paths = [path for path in input_paths if path.lower().endswith(image_extensions)]
133
+ video_paths = [path for path in input_paths if path.lower().endswith(video_extensions)]
134
+
135
+ imgs, vids = [], []
136
+
137
+ if image_paths:
138
+ imgs = processor.process_images(image_paths)
139
+ if video_paths:
140
+ vids = processor.process_videos(video_paths)
141
+ return imgs, vids
app.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import os
3
+ import cv2
4
+ import torch
5
+ from tqdm import tqdm
6
+ from ultralytics import YOLO
7
+ import pandas as pd
8
+ import numpy as np
9
+ from PIL import Image
10
+ from VideoProcessor import MediaProcessor, process_media
11
+
12
+ # Создание папок для загрузки и обработки файлов
13
+ def create_folders(upload_folder="uploaded_files", processed_folder="processed_files"):
14
+ if not os.path.exists(upload_folder):
15
+ os.makedirs(upload_folder)
16
+ if not os.path.exists(processed_folder):
17
+ os.makedirs(processed_folder)
18
+
19
+ # Функция для загрузки файлов
20
+ def save_uploaded_file(uploaded_file, folder_name="uploaded_files"):
21
+ file_path = os.path.join(folder_name, uploaded_file.name)
22
+ with open(file_path, "wb") as f:
23
+ f.write(uploaded_file.getbuffer())
24
+ return file_path
25
+
26
+ # Функция для получения списка всех файлов в папке
27
+ def get_all_files(folder_name="processed_files"):
28
+ return os.listdir(folder_name)
29
+
30
+ # Функция для отображения файлов с центровкой
31
+ def display_file(selected_file, folder_name="processed_files"):
32
+ file_path = os.path.join(folder_name, selected_file)
33
+ if selected_file.endswith('.mp4'):
34
+ st.video(file_path)
35
+ else:
36
+ st.image(file_path, use_column_width=True)
37
+
38
+ def exclude_processed_files(file_list, processed_files):
39
+ return [file for file in file_list if os.path.basename(file.name) not in processed_files]
40
+
41
+ # Основная функция приложения
42
+ def main(processor):
43
+ variants = []
44
+ processed_files = [] # Массив для хранения уже обработанных файлов
45
+
46
+ # Создание папок для загрузки и обработки файлов
47
+ create_folders()
48
+
49
+ # Заголовок приложения
50
+ st.title("Загрузите фото и видео, затем выберите файл из списка")
51
+
52
+ # Загрузка файлов
53
+ uploaded_files = st.file_uploader("Загрузите фото и видео", accept_multiple_files=True)
54
+ if uploaded_files:
55
+ input_paths = []
56
+ # Исключение уже обработанных файлов
57
+ new_files = exclude_processed_files(uploaded_files, processed_files)
58
+ for uploaded_file in new_files:
59
+ file_path = save_uploaded_file(uploaded_file)
60
+ input_paths.append(file_path)
61
+
62
+ if input_paths:
63
+ st.toast(f"Файлы загружены", icon="🟢")
64
+ imgs, vids = process_media(input_paths, processor)
65
+ # Получение реальных названий файлов с расширениями, но без папки
66
+ variants.extend([os.path.basename(i) for i in imgs])
67
+ variants.extend([os.path.basename(i) for i in vids])
68
+ st.toast(f"Файлы обработаны", icon="🟢")
69
+
70
+ # Добавление обработанных файлов в processed_files
71
+ processed_files.extend([os.path.basename(i) for i in imgs])
72
+ processed_files.extend([os.path.basename(i) for i in vids])
73
+
74
+ # Поле для выбора файла из выпадающего списка
75
+ selected_file = st.selectbox("Выберите файл", variants)
76
+ # Центровка и отображение выбранного файла
77
+ if selected_file:
78
+ st.markdown(
79
+ """
80
+ <style>
81
+ .centered {
82
+ display: flex;
83
+ justify-content: center;
84
+ }
85
+ </style>
86
+ """,
87
+ unsafe_allow_html=True
88
+ )
89
+ st.markdown('<div class="centered">', unsafe_allow_html=True)
90
+ display_file(selected_file)
91
+ st.markdown('</div>', unsafe_allow_html=True)
92
+
93
+ # Запуск приложения
94
+ if __name__ == "__main__":
95
+ model_path = 'trained_y8m.pt' # Укажите путь к модели
96
+ processor = MediaProcessor('processed_files', model_path, batch_size=16)
97
+
98
+ main(processor)
metadata/.DS_Store ADDED
Binary file (6.15 kB). View file
 
processed_files/.DS_Store ADDED
Binary file (6.15 kB). View file
 
trained_y8m.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ad5f0e0a3bfd6fb1c130c24ff9a7b785343330e508f1d2ff287eaee693bf949d
3
+ size 52004865
uploaded_files/.DS_Store ADDED
Binary file (6.15 kB). View file