From acb7c76382ac307b063f1af4ec4a5059f55f9397 Mon Sep 17 00:00:00 2001
From: Ivan Chekanov <78589729+ichekanov@users.noreply.github.com>
Date: Mon, 3 Feb 2025 20:25:50 +0300
Subject: [PATCH] :bug: Fix code

---
 lab-4/task_3_1.py          | 30 ++++++++++++----------------
 lab-4/task_3_2.py          | 40 +++++++++++++++++++++++++++-----------
 lab-4/task_3_2_results.csv | 20 +++++++++----------
 3 files changed, 51 insertions(+), 39 deletions(-)

diff --git a/lab-4/task_3_1.py b/lab-4/task_3_1.py
index 44e3e8f..f89201e 100644
--- a/lab-4/task_3_1.py
+++ b/lab-4/task_3_1.py
@@ -15,6 +15,7 @@ CACHE_FILE = "lab-4/task_3_1_cache/embeddings_cache.pkl"
 DIR_HASH_FILE = "lab-4/task_3_1_cache/dir_hash.txt"
 THRESHOLD = 0.1  # Порог косинусного сходства
 FRAME_SKIP = 50  # Каждый 50-й кадр
+FRAME_LIMIT = 20 * FRAME_SKIP  # Ограничение на количество кадров
 
 video_files = [f for f in os.listdir(VIDEO_DIR) if f.endswith((".mp4", ".avi", ".mov"))]
 print("Доступные видео:")
@@ -65,24 +66,16 @@ def load_reference_embeddings():
             for img_name in os.listdir(person_dir):
                 img_path = os.path.join(person_dir, img_name)
                 try:
-                    # Сначала извлекаем лицо
-                    faces = DeepFace.extract_faces(
-                        img_path=img_path,
-                        detector_backend="opencv",
-                        enforce_detection=False,
-                    )
-                    if faces:  # Если лицо найдено
-                        # Получаем эмбеддинг для найденного лица
-                        embedding = normalize_embedding(
-                            DeepFace.represent(
-                                img_path=faces[0][
-                                    "face"
-                                ],  # Используем извлеченное лицо
+                    image_embeddings = [
+                            normalize_embedding(emb["embedding"])
+                            for emb in DeepFace.represent(
+                                img_path=img_path,
                                 model_name="Facenet",
-                                detector_backend="opencv",
+                                detector_backend="retinaface",
                                 enforce_detection=False,
-                            )[0]["embedding"]
-                        )
+                            )
+                        ]
+                    for embedding in image_embeddings:
                         if person not in embeddings:
                             embeddings[person] = []
                         embeddings[person].append(embedding)
@@ -119,6 +112,7 @@ print("\nИнициализация видео...")
 cap = cv2.VideoCapture(VIDEO_PATH)
 fps = cap.get(cv2.CAP_PROP_FPS)
 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
+total_frames = min(total_frames, FRAME_LIMIT) if FRAME_LIMIT else total_frames
 print(f"FPS: {fps:.2f}")
 print(f"Всего кадров: {total_frames}")
 print(f"Длительность видео: {total_frames/fps:.2f} секунд")
@@ -151,7 +145,7 @@ for frame_num in tqdm(range(0, total_frames, FRAME_SKIP)):
     try:
         # Обнаружение лиц
         detected_faces = DeepFace.extract_faces(
-            frame, detector_backend="opencv", enforce_detection=False
+            frame, detector_backend="retinaface", enforce_detection=False
         )
     except Exception as exc:
         print(f"Поиск на кадре {frame_num} не удался: {exc=}")
@@ -166,7 +160,7 @@ for frame_num in tqdm(range(0, total_frames, FRAME_SKIP)):
                 DeepFace.represent(
                     img_path=face["face"],
                     model_name="Facenet",
-                    detector_backend="opencv",
+                    detector_backend="retinaface",
                     enforce_detection=False,
                 )[0]["embedding"]
             )
diff --git a/lab-4/task_3_2.py b/lab-4/task_3_2.py
index 79ebec4..de9ba56 100644
--- a/lab-4/task_3_2.py
+++ b/lab-4/task_3_2.py
@@ -200,37 +200,47 @@ def test_transformations(image_paths):
         )
 
         print("Обработка изображений с шумом...")
-        noisy_embeddings = []
-        res = process_dataset(
+        noisy_embeddings = process_dataset(
             image_paths,
             model_name=model_name,
             transform=add_noise,
             transform_name="Изображение с шумом",
         )
-        noisy_embeddings.extend(res)
-        res = process_dataset(
+        results[model_name]["Изображение с шумом"] = calculate_recall(
+            reference_embedding, noisy_embeddings
+        )
+
+        print("Обработка изображений с уменьшенной яркостью...")
+        low_brightness_embeddings = process_dataset(
             image_paths,
             model_name=model_name,
             transform=lambda img: adjust_brightness(img, 0.5),
             transform_name="Изображение с уменьшенной яркостью",
         )
-        noisy_embeddings.extend(res)
-        res = process_dataset(
+        results[model_name]["Изображение с уменьшенной яркостью"] = calculate_recall(
+            reference_embedding, low_brightness_embeddings
+        )
+
+        print("Обработка изображений с увеличенной яркостью...")
+        high_brightness_embeddings = process_dataset(
             image_paths,
             model_name=model_name,
             transform=lambda img: adjust_brightness(img, 1.5),
             transform_name="Изображение с увеличенной яркостью",
         )
-        noisy_embeddings.extend(res)
-        res = process_dataset(
+        results[model_name]["Изображение с увеличенной яркостью"] = calculate_recall(
+            reference_embedding, high_brightness_embeddings
+        )
+
+        print("Обработка изображений с размытием...")
+        blurred_embeddings = process_dataset(
             image_paths,
             model_name=model_name,
             transform=apply_blur,
             transform_name="Размытие",
         )
-        noisy_embeddings.extend(res)
-        results[model_name]["Изображение с шумом"] = calculate_recall(
-            reference_embedding, noisy_embeddings
+        results[model_name]["Размытие"] = calculate_recall(
+            reference_embedding, blurred_embeddings
         )
 
     return results
@@ -283,6 +293,14 @@ def create_results_table(results):
         "Изображение с шумом": [
             results[model]["Изображение с шумом"] for model in results
         ],
+        "Изображение с уменьшенной яркостью": [
+            results[model]["Изображение с уменьшенной яркостью"]
+            for model in results
+        ],
+        "Изображение с увеличенной яркостью": [
+            results[model]["Изображение с увеличенной яркостью"] for model in results
+        ],
+        "Размытие": [results[model]["Размытие"] for model in results],
     }
 
     results_df = pd.DataFrame(data)
diff --git a/lab-4/task_3_2_results.csv b/lab-4/task_3_2_results.csv
index 7ca691b..9964072 100644
--- a/lab-4/task_3_2_results.csv
+++ b/lab-4/task_3_2_results.csv
@@ -1,10 +1,10 @@
-Метод,Исходный датасет,Поворот на 45°,Поворот на 90°,Изображение с шумом
-Facenet,1.0,1.0,1.0,4.0
-VGG-Face,0.0,0.0,0.0,0.0
-Facenet512,1.0,1.0,1.0,4.0
-OpenFace,1.0,1.0,1.0,4.0
-DeepID,0.95,0.95,0.95,3.8
-ArcFace,1.0,1.0,1.0,4.0
-Dlib,1.0,1.0,1.0,4.0
-SFace,1.0,1.0,1.0,3.4
-GhostFaceNet,0.95,0.65,0.5,3.65
+Метод,Исходный датасет,Поворот на 45°,Поворот на 90°,Изображение с шумом,Изображение с уменьшенной яркостью,Изображение с увеличенной яркостью,Размытие
+Facenet,1.0,1.0,1.0,1.0,1.0,1.0,1.0
+VGG-Face,0.0,0.0,0.0,0.0,0.0,0.0,0.0
+Facenet512,1.0,1.0,1.0,1.0,1.0,1.0,1.0
+OpenFace,1.0,1.0,1.0,1.0,1.0,1.0,1.0
+DeepID,0.95,0.95,0.95,1.0,1.0,0.85,0.95
+ArcFace,1.0,1.0,1.0,1.0,1.0,1.0,1.0
+Dlib,1.0,1.0,1.0,1.0,1.0,1.0,1.0
+SFace,1.0,1.0,1.0,1.0,1.0,0.4,1.0
+GhostFaceNet,0.95,0.65,0.5,0.9,0.95,0.85,0.9
-- 
GitLab