Added code to analyze the relation ship between overlapping faces and objects

This commit is contained in:
2025-08-14 09:45:39 +02:00
parent 05722f60b0
commit b89eb2bce8
15 changed files with 151 additions and 64 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 362 KiB

After

Width:  |  Height:  |  Size: 362 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
+4 -4
View File
@@ -24,8 +24,8 @@ class Config:
pose_model_type="models/yolo11m-pose.pt" #"models/yolo11x-pose.pt"
face_model_type="yunet" # "retinaface"
evaluation_results_directory = "evaluation_results/evaluation_results_90_with_correct_acc_deid/"
visual_results_directory = "visual_results/visual_results_90_with_correct_acc_deid/"
evaluation_results_directory = "evaluation_results/evaluation_results_90_face_object_analysis/"
visual_results_directory = "visual_results/face_object_analysis/"
verbose=True
@@ -35,10 +35,10 @@ class Config:
"obfuscation": False, # optional if already done
"post_extract": False, # optional if already done
"analysis": True, # optional if already done
"visualize": True #Should be always true, since it is the last step for reasoning
"visualize": False #Should be always true, since it is the last step for reasoning
}
bbox_matching_iou = 0.9
bbox_matching_iou = 0.90
#DEBUG
+51 -3
View File
@@ -237,7 +237,13 @@ def init_folder_insights_dict():
"before_object_count": 0,
"object_bbox_ious": [],
"object_segment_ious": [],
"found_matching_classes_count": 0
"found_matching_classes_count": 0,
###FACE-OBJECT-ANALYSIS###
"object_count_while_overlap_with_face": 0,
"found_matching_objects_count_while_overlap_with_face": 0,
"object_count_without_overlap_with_face": 0,
"found_matching_objects_count_without_overlap_with_face": 0,
###
}
return folder_insights
@@ -261,6 +267,12 @@ def write_image_results_to_folder_result_dict(image_result_dict, folder_result_d
folder_result_dict["object_bbox_ious"].extend(image_result_dict["object_bbox_ious"])
folder_result_dict["object_segment_ious"].extend(image_result_dict["object_segment_ious"])
folder_result_dict["found_matching_classes_count"] += image_result_dict["found_matching_classes_count"]
###FACE-OBJECT-ANALYSIS###
folder_result_dict["object_count_while_overlap_with_face"] += image_result_dict["object_count_while_overlap_with_face"]
folder_result_dict["found_matching_objects_count_while_overlap_with_face"] += image_result_dict["found_matching_objects_count_while_overlap_with_face"]
folder_result_dict["object_count_without_overlap_with_face"] += image_result_dict["object_count_without_overlap_with_face"]
folder_result_dict["found_matching_objects_count_without_overlap_with_face"] += image_result_dict["found_matching_objects_count_without_overlap_with_face"]
###
def compute_scores(folder_result_dict):
scores = {
@@ -277,6 +289,16 @@ def compute_scores(folder_result_dict):
"\mathrm{Acc}_\mathrm{det}": (folder_result_dict["found_matching_objects_count"] / folder_result_dict["before_object_count"]) * 100.0,
"\mathrm{mIoU}_\mathrm{seg}": np.mean(folder_result_dict["object_segment_ious"]) if len(folder_result_dict["object_segment_ious"]) > 0 else 0.0
},
###FACE-OBJECT-INSIGHTS###
"face-object-insights":{
"object_count_while_overlap_with_face": folder_result_dict["object_count_while_overlap_with_face"],
"found_matching_objects_count_while_overlap_with_face": folder_result_dict["found_matching_objects_count_while_overlap_with_face"],
"object_count_without_overlap_with_face": folder_result_dict["object_count_without_overlap_with_face"],
"found_matching_objects_count_without_overlap_with_face": folder_result_dict["found_matching_objects_count_without_overlap_with_face"],
"\mathrm{Acc}_{\mathrm{det}}^{\mathrm{with\,overlap}}": (folder_result_dict["found_matching_objects_count_while_overlap_with_face"] / folder_result_dict["object_count_while_overlap_with_face"]),
"\mathrm{Acc}_{\mathrm{det}}^{\mathrm{without\,overlap}}": (folder_result_dict["found_matching_objects_count_without_overlap_with_face"] / folder_result_dict["object_count_without_overlap_with_face"])
},
###
"meta": {
"person": {
"found_matching_persons_count": folder_result_dict["found_matching_persons_count"],
@@ -526,6 +548,13 @@ class Comparator:
object_bbox_ious = []
object_segment_ious = []
###FACE-OBJECT-ANALYSIS###
object_count_while_overlap_with_face = 0
found_matching_objects_count_while_overlap_with_face = 0
object_count_without_overlap_with_face = 0
found_matching_objects_count_without_overlap_with_face = 0
###
for before_person in before_meta["persons"]:
result = _find_best_matching_object(before_person, after_meta["persons"], Config.bbox_matching_iou)
if result is None:
@@ -560,11 +589,23 @@ class Comparator:
same_emotion_count += 1
emotion_vector_similarities.append(_emotion_cosine_similarity(before_person["emotion_vector"], after_person["emotion_vector"]))
_, face_point_position_similarities = _compute_face_keypoint_similarity(before_person["face_keypoints"], after_person["face_keypoints"], before_person["face_bbox"], after_person["face_bbox"])
face_keypoint_position_similarities.extend(face_point_position_similarities)
for before_object in before_meta["objects"]:
result = _find_best_matching_object(before_object, after_meta["objects"], Config.bbox_matching_iou)
###FACE-OBJECT-ANALYSIS###
if _bbox_iou(before_person["face_bbox"], before_object["bbox"]) > 0:
object_count_while_overlap_with_face += 1
if result is not None:
found_matching_objects_count_while_overlap_with_face += 1
else:
object_count_without_overlap_with_face += 1
if result is not None:
found_matching_objects_count_without_overlap_with_face += 1
###
if result is None:
continue
after_object, bbox_iou, segment_iou = result
@@ -574,6 +615,7 @@ class Comparator:
if before_object["label"] == after_object["label"]:
found_matching_classes_count += 1
#For Each Before-Person; Check identifitcation
for before_person in before_meta["persons"]:
before_face_crop = before_img[before_person["face_bbox"][1]:before_person["face_bbox"][3], before_person["face_bbox"][0]:before_person["face_bbox"][2]]
@@ -603,6 +645,12 @@ class Comparator:
"before_object_count": before_object_count,
"object_bbox_ious": object_bbox_ious,
"object_segment_ious": object_segment_ious,
"found_matching_classes_count": found_matching_classes_count
"found_matching_classes_count": found_matching_classes_count,
###FACE-OBJECT-ANALYSIS###
"object_count_while_overlap_with_face": object_count_while_overlap_with_face,
"found_matching_objects_count_while_overlap_with_face": found_matching_objects_count_while_overlap_with_face,
"object_count_without_overlap_with_face": object_count_without_overlap_with_face,
"found_matching_objects_count_without_overlap_with_face": found_matching_objects_count_without_overlap_with_face
###
}
return image_insights
+59
View File
@@ -0,0 +1,59 @@
import os
import json
import re
import matplotlib.pyplot as plt
from collections import defaultdict
# Ordner mit JSON-Dateien
input_dir = "./json_results"
# Regex um dataset und technik aus Dateinamen zu extrahieren
filename_pattern = re.compile(r"results_(.+?)_(.+?)\.json")
# Datenstruktur: {dataset: {technik: (with_overlap, without_overlap)}}
data = defaultdict(dict)
# Alle JSON-Dateien einlesen
for filename in os.listdir(input_dir):
if filename.endswith(".json"):
match = filename_pattern.match(filename)
if not match:
continue
dataset, technik = match.groups()
filepath = os.path.join(input_dir, filename)
with open(filepath, "r", encoding="utf-8") as f:
content = json.load(f)
# Werte extrahieren
face_obj = content.get("face-object-insights", {})
with_overlap = face_obj.get(r"\mathrm{Acc}_{\mathrm{det}}^{\mathrm{with\,overlap}}")
without_overlap = face_obj.get(r"\mathrm{Acc}_{\mathrm{det}}^{\mathrm{without\,overlap}}")
data[dataset][technik] = (with_overlap, without_overlap)
# Für jedes Dataset ein Grouped Bar Chart erstellen
for dataset, technik_data in data.items():
techniken = list(technik_data.keys())
with_vals = [technik_data[t][0] for t in techniken]
without_vals = [technik_data[t][1] for t in techniken]
x = range(len(techniken))
bar_width = 0.35
fig, ax = plt.subplots(figsize=(10, 6))
ax.bar([i - bar_width/2 for i in x], with_vals, width=bar_width, label="mit overlap")
ax.bar([i + bar_width/2 for i in x], without_vals, width=bar_width, label="ohne overlap")
ax.set_xticks(x)
ax.set_xticklabels(techniken, rotation=45, ha="right")
ax.set_ylabel("Accuracy")
ax.set_title(f"Ergebnisse für Dataset: {dataset}")
ax.legend()
ax.grid(axis='y', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.savefig(f"plot_{dataset}.png")
plt.close()
print("Fertig! Plots gespeichert als 'plot_<dataset>.png'")
+1 -1
View File
@@ -148,7 +148,7 @@ def plot_dataset_scope(thresholds, dataset, scope, techniques_dict, out_dir: Pat
# Create figure/axes
if len(metrics_present) == 1:
fig, ax = plt.subplots(figsize=(5, 5))
fig, ax = plt.subplots(figsize=(5, 3))
axes = [ax] # list for uniform handling
else:
fig, axes = plt.subplots(
+36 -56
View File
@@ -1,27 +1,7 @@
#!/usr/bin/env python3
"""
Grouped bar chart for a single metric at one IoU threshold.
Layout expected:
root/
evaluation_results_50/
result_{datasetA}_{tech1}.json
result_{datasetA}_{tech2}.json
result_{datasetB}_{tech1}.json
result_{datasetB}_{tech2}.json
...
Each JSON has keys like:
{
"face": {
"\\mathrm{Acc}_\\mathrm{deID}": 83.2
},
...
}
Usage example:
python grouped_metric_bar.py --root /path/to/root --threshold 50 \
--metric-latex "\\mathrm{Acc}_\\mathrm{deID}" --scope face --out ./plots
[... docstring unchanged ...]
"""
import argparse
@@ -40,6 +20,15 @@ import math
HATCHES = ['x', 'o', 'O', '-', '+', 'O', '.', '*']
# --- NEW: enforce preferred technique order
PREFERRED_TECHNIQUE_ORDER = ["Black", "Random", "Blur", "Pixel", "Style", "Swap", "Synthetic"]
def order_techniques(techniques):
order_map = {name.lower(): i for i, name in enumerate(PREFERRED_TECHNIQUE_ORDER)}
# Known items keep specified order; unknowns come after, alphabetically
return sorted(techniques, key=lambda t: (order_map.get(t.lower(), len(PREFERRED_TECHNIQUE_ORDER)), t.lower()))
def parse_args():
p = argparse.ArgumentParser(description="Grouped bar chart for one metric at one IoU threshold.")
p.add_argument("--root", type=str, required=True, help="Root folder containing evaluation_results_{thr}.")
@@ -52,13 +41,11 @@ def parse_args():
return p.parse_args()
def sanitize_filename(s: str) -> str:
# Allow letters, digits, dot, underscore, plus, hyphen; replace everything else with "_"
s = re.sub(r'[^A-Za-z0-9._+\-]+', '_', s)
s = re.sub(r'_+', '_', s).strip('._ ')
return s
def rsplit_dataset_technique(filename: str):
# Given 'results_{dataset}_{technique}.json' -> (dataset, technique)
if not (filename.startswith("results_") and filename.endswith(".json")):
return None, None
stem = filename[len("results_"):-len(".json")]
@@ -68,18 +55,13 @@ def rsplit_dataset_technique(filename: str):
return dataset, technique
def load_values_for_threshold(root: Path, threshold: int, scope: str, metric_latex: str):
"""Return:
datasets: sorted list
techniques: sorted list
values[technique][dataset] = number (0..100) or math.nan if missing
"""
folder = root / f"evaluation_results_{threshold}"
if not folder.is_dir():
raise FileNotFoundError(f"Folder not found: {folder}")
scope_keys = {scope, scope.lower(), scope.capitalize()} # be tolerant about case
scope_keys = {scope, scope.lower(), scope.capitalize()}
techniques_set, datasets_set = set(), set()
values = defaultdict(dict) # technique -> dataset -> value
values = defaultdict(dict)
for fname in os.listdir(folder):
dataset, technique = rsplit_dataset_technique(fname)
@@ -93,7 +75,6 @@ def load_values_for_threshold(root: Path, threshold: int, scope: str, metric_lat
print(f"[WARN] Skipping {fpath}: {e}")
continue
# find scope block (prefer exact, but allow simple case variations)
scope_block = None
for k in obj.keys():
if k in scope_keys:
@@ -115,29 +96,34 @@ def load_values_for_threshold(root: Path, threshold: int, scope: str, metric_lat
values[technique][dataset] = v
datasets = sorted(datasets_set)
techniques = sorted(techniques_set)
techniques = order_techniques(sorted(techniques_set))
# Ensure every (technique, dataset) has an entry
for t in techniques:
for d in datasets:
values[t].setdefault(d, math.nan)
return datasets, techniques, values
# Distinct hatch patterns for datasets (cycled if there are many datasets)
# --- NEW: pretty names for datasets for legend display
def pretty_dataset_label(name: str) -> str:
low = name.lower()
if low == "celeba":
return "CelebA*"
if low == "wider":
return "WIDER*"
return name
def grouped_bar_chart(datasets, techniques, values, scope, threshold, metric_latex, out_dir: Path, dpi=140):
if not techniques or not datasets:
print("[WARN] Nothing to plot (no techniques or datasets discovered).")
return False
# dynamic width for readability
#fig_w = max(8, 0.8 * len(techniques) + 3)
fig, ax = plt.subplots(figsize=(5.5, 4)) # a touch taller to make room for legend
fig, ax = plt.subplots(figsize=(5.5, 2.5))
n_groups = len(techniques)
n_bars = len(datasets)
group_x = list(range(n_groups))
total_width = 0.8 # fraction of space per group occupied by bars
total_width = 0.8
bar_w = total_width / max(1, n_bars)
offsets = [(i - (n_bars - 1) / 2) * bar_w for i in range(n_bars)]
@@ -145,9 +131,8 @@ def grouped_bar_chart(datasets, techniques, values, scope, threshold, metric_lat
for j, dataset in enumerate(datasets):
heights = [values[t][dataset] for t in techniques]
x_pos = [x + offsets[j] for x in group_x]
bars = ax.bar(x_pos, heights, width=bar_w, label=dataset)
bars = ax.bar(x_pos, heights, width=bar_w, label=pretty_dataset_label(dataset))
# Apply hatch pattern + clearer edges for visibility
hatch = HATCHES[j % len(HATCHES)]
rects = bars.patches if hasattr(bars, "patches") else list(bars)
for r in rects:
@@ -155,7 +140,6 @@ def grouped_bar_chart(datasets, techniques, values, scope, threshold, metric_lat
r.set_edgecolor("black")
r.set_linewidth(0.6)
# Labels on bars (percentages), version-safe
labels = [f"{h:.0f}" if not math.isnan(h) else "" for h in heights]
if hasattr(ax, "bar_label") and isinstance(bars, BarContainer):
ax.bar_label(bars, labels=labels, padding=2, fontsize=8)
@@ -172,37 +156,33 @@ def grouped_bar_chart(datasets, techniques, values, scope, threshold, metric_lat
fontsize=8,
)
# X axis: technique names at group centers
ax.set_xticks(group_x)
ax.set_xticklabels(techniques)
# Y axis: 0–100 with % labels
ax.set_ylim(0, 105)
ax.set_ylim(0, 109)
ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f"{y:.0f}%"))
# Labels (y uses the LaTeX metric key)
ax.set_ylabel(f"${metric_latex}$", fontsize=14)
ax.set_ylabel(f"${metric_latex}$", fontsize=10)
ax.grid(axis="y", linestyle="--", alpha=0.4)
# --- Legend BELOW the plot ---
# --- Legend INSIDE, centered at the top ---
handles, labels = ax.get_legend_handles_labels()
ncols = min(len(datasets), 4) if len(datasets) > 1 else 1
#ncols = min(len(datasets), 4) if len(datasets) > 1 else 1
leg = ax.legend(
handles,
labels,
loc="upper center",
bbox_to_anchor=(0.5, -0.06), # push below axes
ncol=ncols,
loc="lower left",
#bbox_to_anchor=(0.5, 0.98), # inside the axes near the top edge
#ncol=ncols,
frameon=True,
framealpha=1
#borderaxespad=0.4,
)
# Make some extra bottom space for the legend
fig.subplots_adjust(bottom=0.22)
# No extra bottom space needed; tighten a bit at the top so legend doesn't clip
fig.tight_layout()
out_dir.mkdir(parents=True, exist_ok=True)
outfile = out_dir / sanitize_filename(f"grouped_{scope}_IoU{threshold}_{metric_latex}.pdf")
fig.tight_layout()
fig.savefig(outfile, dpi=dpi, bbox_inches="tight")
plt.close(fig)
print(f"[OK] Saved {outfile}")