Adapted bounding box matching logic
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""compare_json_folders.py ─ Version 3
|
||||
Vergleicht alle .json‑Dateien in zwei Verzeichnissen rekursiv auf Inhaltsunterschiede
|
||||
und gibt *sämtliche* Differenzen (alter ↔ neuer Wert) aus – **mit Ausnahme**
|
||||
aller Felder, deren Schlüssel in ``IGNORE_KEYS`` steht (standardmäßig nur
|
||||
``"image"``).
|
||||
|
||||
Aufruf:
|
||||
python compare_json_folders.py <ORDNER_1> <ORDNER_2> [--ignore key1,key2,…]
|
||||
|
||||
Ausgabeformat:
|
||||
<Dateiname>: <Anzahl> Unterschied(e)
|
||||
• <JSON‑Pfad>: <Wert1> ≠ <Wert2>
|
||||
• <JSON‑Pfad>: fehlt in Ordner 1 (Wert2=<Wert>)
|
||||
• <JSON‑Pfad>: fehlt in Ordner 2 (Wert1=<Wert>)
|
||||
|
||||
Nur Standardbibliothek erforderlich.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any, List, Set
|
||||
|
||||
MAX_LEN = 80 # Werte in der Ausgabe ggf. kürzen
|
||||
IGNORE_KEYS: Set[str] = {"image"} # Standard‑Ignoreliste
|
||||
|
||||
|
||||
def fmt(value: Any) -> str:
|
||||
"""Gibt eine kompakte Repräsentation eines JSON‑Wertes zurück."""
|
||||
text = json.dumps(value, ensure_ascii=False) if not isinstance(value, str) else repr(value)
|
||||
if len(text) > MAX_LEN:
|
||||
return text[:MAX_LEN - 1] + "…"
|
||||
return text
|
||||
|
||||
|
||||
def load_json(path: Path) -> Any:
|
||||
"""Liest eine JSON‑Datei ein."""
|
||||
with path.open("r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def compare_json(a: Any, b: Any, path: str = "") -> List[str]:
|
||||
"""Vergleicht zwei JSON‑Werte rekursiv und liefert *alle* Unterschiede als Textzeilen.
|
||||
|
||||
Pfade, die einen Schlüssel aus ``IGNORE_KEYS`` enthalten, werden übersprungen.
|
||||
"""
|
||||
diffs: List[str] = []
|
||||
|
||||
# Wenn der aktuelle Pfad bereits einen ignorierten Schlüssel enthält → keine Prüfung
|
||||
if path and any(part in IGNORE_KEYS for part in path.split(".")):
|
||||
return diffs # leer
|
||||
|
||||
# Typunterschied
|
||||
if type(a) is not type(b):
|
||||
diffs.append(f"{path or '<root>'}: Typ {type(a).__name__} ≠ {type(b).__name__}")
|
||||
return diffs
|
||||
|
||||
# Dictionaries
|
||||
if isinstance(a, dict):
|
||||
keys_a = set(a)
|
||||
keys_b = set(b)
|
||||
for key in sorted(keys_a | keys_b):
|
||||
if key in IGNORE_KEYS:
|
||||
continue # Feld explizit ignorieren
|
||||
sub_path = f"{path}.{key}" if path else key
|
||||
if key not in a:
|
||||
diffs.append(f"{sub_path}: fehlt in Ordner 1 (Wert2={fmt(b[key])})")
|
||||
elif key not in b:
|
||||
diffs.append(f"{sub_path}: fehlt in Ordner 2 (Wert1={fmt(a[key])})")
|
||||
else:
|
||||
diffs.extend(compare_json(a[key], b[key], sub_path))
|
||||
return diffs
|
||||
|
||||
# Listen/Tuples
|
||||
if isinstance(a, (list, tuple)):
|
||||
len_max = max(len(a), len(b))
|
||||
for idx in range(len_max):
|
||||
sub_path = f"{path}[{idx}]"
|
||||
diffs.extend(compare_json(a[idx] if idx < len(a) else None,
|
||||
b[idx] if idx < len(b) else None,
|
||||
sub_path)) if idx < len(a) and idx < len(b) else None
|
||||
if idx >= len(a):
|
||||
diffs.append(f"{sub_path}: fehlt in Ordner 1 (Wert2={fmt(b[idx])})")
|
||||
elif idx >= len(b):
|
||||
diffs.append(f"{sub_path}: fehlt in Ordner 2 (Wert1={fmt(a[idx])})")
|
||||
return diffs
|
||||
|
||||
# Skalare Werte
|
||||
if a != b:
|
||||
diffs.append(f"{path or '<root>'}: {fmt(a)} ≠ {fmt(b)}")
|
||||
return diffs
|
||||
|
||||
|
||||
def compare_folders(dir1: Path, dir2: Path) -> None:
|
||||
"""Vergleicht alle .json‑Dateien in dir1 und dir2 und zeigt sämtliche Unterschiede."""
|
||||
files1 = {p.name for p in dir1.glob("*.json")}
|
||||
files2 = {p.name for p in dir2.glob("*.json")}
|
||||
all_files = sorted(files1 | files2)
|
||||
|
||||
if not all_files:
|
||||
print("Keine .json‑Dateien gefunden.")
|
||||
return
|
||||
|
||||
for filename in all_files:
|
||||
p1 = dir1 / filename
|
||||
p2 = dir2 / filename
|
||||
|
||||
if not p1.exists():
|
||||
print(f"{filename}: fehlt in Ordner 1")
|
||||
continue
|
||||
if not p2.exists():
|
||||
print(f"{filename}: fehlt in Ordner 2")
|
||||
continue
|
||||
|
||||
try:
|
||||
json1 = load_json(p1)
|
||||
json2 = load_json(p2)
|
||||
except Exception as exc:
|
||||
print(f"{filename}: Fehler beim Einlesen — {exc}")
|
||||
continue
|
||||
|
||||
diffs = compare_json(json1, json2)
|
||||
if diffs:
|
||||
print(f"{filename}: {len(diffs)} Unterschied(e)")
|
||||
for d in diffs:
|
||||
print(f" • {d}")
|
||||
else:
|
||||
pass
|
||||
#print(f"{filename}: identisch")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="Vergleicht die Inhalte zweier Verzeichnisse mit JSON‑Dateien.")
|
||||
parser.add_argument("dir1", type=Path, help="Erstes Verzeichnis")
|
||||
parser.add_argument("dir2", type=Path, help="Zweites Verzeichnis")
|
||||
parser.add_argument(
|
||||
"--ignore",
|
||||
metavar="KEYS",
|
||||
help="Komma‑getrennte Liste von Schlüsseln, die ignoriert werden sollen (zusätzlich zu image)",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
global IGNORE_KEYS # pylint: disable=global‑statement
|
||||
if args.ignore:
|
||||
IGNORE_KEYS |= {k.strip() for k in args.ignore.split(",") if k.strip()}
|
||||
|
||||
if not args.dir1.is_dir() or not args.dir2.is_dir():
|
||||
parser.error("Beide Pfade müssen existierende Verzeichnisse sein.")
|
||||
|
||||
compare_folders(args.dir1, args.dir2)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except BrokenPipeError:
|
||||
sys.stderr.close()
|
||||
sys.exit(0)
|
||||
@@ -18,7 +18,7 @@ class Config:
|
||||
raw_dataset_path="datasets/raw/"
|
||||
filtered_output_directory="datasets/filtered/"
|
||||
obfuscated_output_directory="datasets/obfuscated/"
|
||||
max_images_per_dataset= 1000 # 1000
|
||||
max_images_per_dataset= 10000
|
||||
|
||||
seg_model_type="models/yolo11l-seg.pt"
|
||||
pose_model_type="models/yolo11l-pose.pt"
|
||||
@@ -33,7 +33,7 @@ class Config:
|
||||
"obfuscation": True, # optional if already done
|
||||
"post_extract": True, # 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
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -12,11 +12,19 @@ from visualization.visualizer import Visualizer
|
||||
|
||||
import random
|
||||
import torch
|
||||
|
||||
import numpy as np
|
||||
from visualization.visualizer2 import Visualizer2
|
||||
import tensorflow as tf
|
||||
|
||||
random.seed(Config.seed)
|
||||
torch.manual_seed(Config.seed)
|
||||
np.random.seed(Config.seed)
|
||||
tf.random.set_seed(Config.seed)
|
||||
tf.config.experimental.enable_op_determinism()
|
||||
|
||||
torch.use_deterministic_algorithms(True)
|
||||
torch.backends.cudnn.deterministic = True
|
||||
torch.backends.cudnn.benchmark = False
|
||||
|
||||
def main():
|
||||
print("Starting obfuscation platform")
|
||||
@@ -96,8 +104,18 @@ def main():
|
||||
)
|
||||
|
||||
|
||||
#TODO: NO-OP zum Testen
|
||||
#TODO: PNG
|
||||
#TODO: AM WIDER FACE DATENSATZ PRÜFEN, WARUM DIE SCORES SO KOMISCH SIND UND NICHT 100%
|
||||
#DIE DATEN SIND JA VORBEREITET MIT NO_OP, usw. alles prüfen
|
||||
|
||||
|
||||
|
||||
|
||||
#TODO Nur WIDER und CELEBA/UTK; wegen objektverteilung
|
||||
|
||||
#TODO: Man NO_OP; Prüfen, wegen objekt matching und klassen
|
||||
#TODO: HEATMAPS zeichnen; CELEBA, WIDER; verteilung Blau auf schwarz?
|
||||
|
||||
#TODO GAnonymization mit "normaler" kopie?
|
||||
|
||||
#TODO In paper beispiele zeigen mit den modellen
|
||||
|
||||
|
||||
@@ -82,28 +82,54 @@ def _poly_iou(poly_a, poly_b) -> float:
|
||||
print("poly_b", poly_b)
|
||||
print(pa)
|
||||
print(pb)
|
||||
exit() #TODO Möglicherweise entfernen
|
||||
iou = 0
|
||||
return iou
|
||||
|
||||
|
||||
#This function returns an object that matches the given object based on class and IoU
|
||||
#Returns None or Found Object + Bbox- and Segment-IoU
|
||||
def _find_best_matching_object(obj, other_objects, min_iou=0.5):
|
||||
if other_objects is None or len(other_objects) == 0:
|
||||
def _find_best_matching_object(obj,other_objects, min_iou: float = 0.90):
|
||||
"""
|
||||
1. Sammle alle Kandidaten, deren BBox-IoU ≥ min_iou.
|
||||
2. Bevorzuge den Kandidaten mit derselben Klasse und
|
||||
höchster IoU. Gibt es keinen, nimm einfach den Kandidaten
|
||||
mit der höchsten IoU (klasseunabhängig).
|
||||
3. Liefere [obj, bbox_iou %, seg_iou %] oder None.
|
||||
"""
|
||||
if not other_objects:
|
||||
return None
|
||||
best_match = None
|
||||
for other_obj in other_objects:
|
||||
bbox_iou = _bbox_iou(obj["bbox"], other_obj["bbox"])
|
||||
if bbox_iou > min_iou:
|
||||
segment_iou = _poly_iou(obj["segment"], other_obj["segment"])
|
||||
if best_match is None:
|
||||
best_match = (other_obj, bbox_iou * 100.0, segment_iou * 100.0)
|
||||
else:
|
||||
best_bbox_iou_so_far = best_match[1]
|
||||
if best_bbox_iou_so_far < bbox_iou:
|
||||
best_match = (other_obj, bbox_iou * 100.0, segment_iou * 100.0)
|
||||
|
||||
best_any = None # [other, bbox_iou, seg_iou]
|
||||
best_any_iou = -1.0
|
||||
best_same_class = None
|
||||
best_same_iou = -1.0
|
||||
ref_label = obj["label"]
|
||||
|
||||
for other in other_objects:
|
||||
bbox_iou = _bbox_iou(obj["bbox"], other["bbox"])
|
||||
if bbox_iou < min_iou:
|
||||
continue
|
||||
|
||||
seg_iou = _poly_iou(obj["segment"], other["segment"])
|
||||
|
||||
# Aktualisiere globalen Best-Match
|
||||
if bbox_iou > best_any_iou:
|
||||
best_any = [other, bbox_iou, seg_iou]
|
||||
best_any_iou = bbox_iou
|
||||
|
||||
# Aktualisiere Best-Match gleicher Klasse
|
||||
if other["label"] == ref_label and bbox_iou > best_same_iou:
|
||||
best_same_class = [other, bbox_iou, seg_iou]
|
||||
best_same_iou = bbox_iou
|
||||
|
||||
# Entscheide nach Priorität: erst gleiche Klasse, sonst bester beliebiger
|
||||
best_match = best_same_class if best_same_class is not None else best_any
|
||||
|
||||
if best_match:
|
||||
best_match[1] *= 100.0 # BBox-IoU in Prozent
|
||||
best_match[2] *= 100.0 # Segment-IoU in Prozent
|
||||
return best_match
|
||||
|
||||
|
||||
|
||||
def _adapt_body_keypoints(kps, bbox):
|
||||
w = bbox[2] - bbox[0]
|
||||
h = bbox[3] - bbox[1]
|
||||
@@ -326,7 +352,6 @@ class Comparator:
|
||||
img_insights = self._get_insights_from_comparison(before_meta_path, after_meta_path)
|
||||
#Aggregate meta_data into folder_result_dict
|
||||
write_image_results_to_folder_result_dict(img_insights, folder_insights)
|
||||
|
||||
scores = compute_scores(folder_insights)
|
||||
return scores
|
||||
|
||||
@@ -358,9 +383,8 @@ class Comparator:
|
||||
object_bbox_ious = []
|
||||
object_segment_ious = []
|
||||
|
||||
|
||||
for before_person in before_meta["persons"]:
|
||||
result = _find_best_matching_object(before_person, after_meta["persons"])
|
||||
result = _find_best_matching_object(before_person, after_meta["persons"], 0.90)
|
||||
if result is None:
|
||||
continue
|
||||
after_person, bbox_iou, segment_iou = result
|
||||
@@ -376,7 +400,7 @@ class Comparator:
|
||||
raise ValueError("Before person has no face", path_to_meta_before)
|
||||
if after_person["face_bbox"] is not None:
|
||||
face_iou = _bbox_iou(before_person["face_bbox"], after_person["face_bbox"]) * 100.0
|
||||
if face_iou > 50.0:
|
||||
if face_iou > 90.0:
|
||||
found_face_count += 1
|
||||
face_bbox_ious.append(face_iou)
|
||||
is_emotion_matching = before_person["dominant_emotion"] == after_person["dominant_emotion"]
|
||||
@@ -395,9 +419,8 @@ class Comparator:
|
||||
|
||||
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"])
|
||||
result = _find_best_matching_object(before_object, after_meta["objects"], 0.90)
|
||||
if result is None:
|
||||
continue
|
||||
after_object, bbox_iou, segment_iou = result
|
||||
|
||||
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 4.2 KiB After Width: | Height: | Size: 16 KiB |
@@ -77,13 +77,22 @@ class GANONYMIZATION():
|
||||
cx = np.clip(W0 // 2, new_w // 2, W0 - new_w // 2)
|
||||
cy = np.clip(H0 // 2, new_h // 2, H0 - new_h // 2)
|
||||
|
||||
result = cv2.seamlessClone(
|
||||
src = patch_bgr,
|
||||
dst = face_img,
|
||||
mask = mask,
|
||||
p = (int(cx), int(cy)),
|
||||
flags = cv2.NORMAL_CLONE,
|
||||
)
|
||||
#result = cv2.seamlessClone(
|
||||
# src = patch_bgr,
|
||||
# dst = face_img,
|
||||
# mask = mask,
|
||||
# p = (int(cx), int(cy)),
|
||||
# flags = cv2.NORMAL_CLONE,
|
||||
#)
|
||||
#return cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
|
||||
|
||||
x1 = int(cx - new_w // 2)
|
||||
y1 = int(cy - new_h // 2)
|
||||
x2 = x1 + new_w
|
||||
y2 = y1 + new_h
|
||||
|
||||
result = face_img.copy()
|
||||
result[y1:y2, x1:x2] = patch_bgr
|
||||
return cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
Before Width: | Height: | Size: 4.1 KiB After Width: | Height: | Size: 19 KiB |
|
Before Width: | Height: | Size: 2.6 KiB After Width: | Height: | Size: 6.4 KiB |
@@ -13,10 +13,10 @@ class Style(ObfuscationTechnique):
|
||||
Replace face with generated face
|
||||
"""
|
||||
def __init__(self):
|
||||
# print("Style not activated")
|
||||
self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/"
|
||||
resp = requests.get("http://127.0.0.1:8002/init", timeout=180)
|
||||
resp.raise_for_status()
|
||||
print("Style not activated")
|
||||
# self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/"
|
||||
# resp = requests.get("http://127.0.0.1:8002/init", timeout=180)
|
||||
# resp.raise_for_status()
|
||||
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||||
|
||||
@@ -12,10 +12,10 @@ class Swap(ObfuscationTechnique):
|
||||
Replace face with generated face
|
||||
"""
|
||||
def __init__(self):
|
||||
# print("epic not active")
|
||||
self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/epic/image_cache/"
|
||||
resp = requests.get(f"http://127.0.0.1:8000/init", timeout=60)
|
||||
resp.raise_for_status()
|
||||
print("epic not active")
|
||||
# self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/epic/image_cache/"
|
||||
# resp = requests.get(f"http://127.0.0.1:8000/init", timeout=60)
|
||||
# resp.raise_for_status()
|
||||
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||||
|
||||
@@ -13,10 +13,10 @@ class Synthetic(ObfuscationTechnique):
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# print("synthetic not active")
|
||||
self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/ganonymization/image_cache/"
|
||||
resp = requests.get(f"http://127.0.0.1:8003/init", timeout=120)
|
||||
resp.raise_for_status()
|
||||
print("synthetic not active")
|
||||
# self.image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/ganonymization/image_cache/"
|
||||
# resp = requests.get(f"http://127.0.0.1:8003/init", timeout=120)
|
||||
# resp.raise_for_status()
|
||||
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
heatmap_generator.py – OpenCV version
|
||||
with *multi-stop* colour scales for faces & objects.
|
||||
|
||||
• scale syntax: '#RRGGBB-#RRGGBB-...' or 'R,G,B-R,G,B-...'
|
||||
(hyphen-separated list of colours)
|
||||
• Example: black→purple→white for faces
|
||||
--face_scale "#000000-#800080-#ffffff"
|
||||
"""
|
||||
|
||||
import argparse, json, re
|
||||
from pathlib import Path
|
||||
|
||||
import cv2
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
HEX_RE = re.compile(r"^#?([0-9a-fA-F]{6})$")
|
||||
|
||||
|
||||
# ───────────────────── colour helpers ────────────────────────────────────────
|
||||
def str_to_bgr(s: str):
|
||||
"""'#RRGGBB' *or* 'R,G,B' ➜ (B,G,R) tuple of uint8."""
|
||||
if HEX_RE.fullmatch(s.strip()):
|
||||
h = HEX_RE.fullmatch(s.strip()).group(1)
|
||||
r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
|
||||
return (b, g, r)
|
||||
try:
|
||||
r, g, b = map(int, s.split(","))
|
||||
return (b, g, r)
|
||||
except Exception:
|
||||
raise argparse.ArgumentTypeError(
|
||||
f"Colour '{s}' must be '#RRGGBB' or 'R,G,B'."
|
||||
)
|
||||
|
||||
|
||||
def parse_scale(scale_str: str, default: str):
|
||||
"""
|
||||
Hyphen-separated list of colours → numpy (K,3) BGR float32.
|
||||
If scale_str is '', fall back to default.
|
||||
"""
|
||||
s = scale_str if scale_str else default
|
||||
stops = [str_to_bgr(tok) for tok in s.split("-")]
|
||||
return np.array(stops, dtype=np.float32) # shape (K,3)
|
||||
|
||||
|
||||
def apply_multistop_colormap(norm_img: np.ndarray, stops: np.ndarray):
|
||||
"""
|
||||
norm_img ∈ [0,1] → colour by linear interpolation of 'stops' (K,3).
|
||||
Returns uint8 BGR image.
|
||||
"""
|
||||
k = len(stops) - 1
|
||||
idx_float = norm_img * k
|
||||
idx0 = np.floor(idx_float).astype(np.int32)
|
||||
idx1 = np.clip(idx0 + 1, 0, k)
|
||||
frac = (idx_float - idx0)[..., None] # shape (H,W,1)
|
||||
|
||||
col = (1 - frac) * stops[idx0] + frac * stops[idx1]
|
||||
return col.astype(np.uint8)
|
||||
|
||||
|
||||
# ───────────────────── heat-map utilities ────────────────────────────────────
|
||||
def centre(b, w, h):
|
||||
x1, y1, x2, y2 = b
|
||||
return (x1 + x2) / (2 * w), (y1 + y2) / (2 * h)
|
||||
|
||||
|
||||
def add_points(pts, grid):
|
||||
for x, y in pts:
|
||||
ix = min(grid.shape[1] - 1, max(0, int(x * grid.shape[1])))
|
||||
iy = min(grid.shape[0] - 1, max(0, int(y * grid.shape[0])))
|
||||
grid[iy, ix] += 1.0
|
||||
|
||||
|
||||
def normalise(arr):
|
||||
m = arr.max()
|
||||
return (arr / m) if m else arr
|
||||
|
||||
|
||||
# ───────────────────── main ──────────────────────────────────────────────────
|
||||
def main():
|
||||
ap = argparse.ArgumentParser("Heat-map with custom colour scales.")
|
||||
ap.add_argument("--input_dir", required=True)
|
||||
ap.add_argument("--output_dir", required=True)
|
||||
ap.add_argument("--grid_size", type=int, default=100)
|
||||
|
||||
ap.add_argument("--face_scale", default="", help="e.g. '#000-#800080-#fff'")
|
||||
ap.add_argument("--object_scale", default="")
|
||||
ap.add_argument("--bg_color", default="#ffffff")
|
||||
|
||||
args = ap.parse_args()
|
||||
|
||||
face_stops = parse_scale(args.face_scale,
|
||||
default="#ffffff-#800080")
|
||||
object_stops = parse_scale(args.object_scale,
|
||||
default="#ffffff-#ffff00")
|
||||
bg_bgr = str_to_bgr(args.bg_color)
|
||||
|
||||
out_dir = Path(args.output_dir)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
data_set = Path(args.input_dir).resolve().name
|
||||
|
||||
Hf = np.zeros((args.grid_size, args.grid_size), np.float32)
|
||||
Ho = np.zeros_like(Hf)
|
||||
|
||||
imgs = list(Path(args.input_dir).glob("*.jpg")) + \
|
||||
list(Path(args.input_dir).glob("*.png"))
|
||||
if not imgs:
|
||||
raise RuntimeError("No images found.")
|
||||
|
||||
for img_path in imgs:
|
||||
meta = img_path.with_suffix(".json")
|
||||
if not meta.exists():
|
||||
print(f"[warn] no JSON for {img_path.name}")
|
||||
continue
|
||||
|
||||
try:
|
||||
w, h = Image.open(img_path).size
|
||||
except Exception as e:
|
||||
print(f"[warn] bad image {img_path}: {e}"); continue
|
||||
|
||||
try:
|
||||
js = json.loads(meta.read_text())
|
||||
except Exception as e:
|
||||
print(f"[warn] bad JSON {meta}: {e}"); continue
|
||||
|
||||
f_pts, o_pts = [], []
|
||||
for p in js.get("persons", []):
|
||||
bb = p.get("face_bbox") or p.get("bbox")
|
||||
if bb and len(bb) == 4: f_pts.append(centre(bb, w, h))
|
||||
for o in js.get("objects", []):
|
||||
bb = o.get("bbox")
|
||||
if bb and len(bb) == 4: o_pts.append(centre(bb, w, h))
|
||||
|
||||
add_points(f_pts, Hf)
|
||||
add_points(o_pts, Ho)
|
||||
|
||||
# ---------- single-class colourisation -----------------------------------
|
||||
f_img = apply_multistop_colormap(normalise(Hf), face_stops)
|
||||
o_img = apply_multistop_colormap(normalise(Ho), object_stops)
|
||||
|
||||
|
||||
# choose your final resolution here
|
||||
OUT_SHAPE = (256, 256) # (width, height)
|
||||
|
||||
# ---------- single-class maps ----------------------------------------------
|
||||
f_img = cv2.resize(
|
||||
apply_multistop_colormap(normalise(Hf), face_stops),
|
||||
OUT_SHAPE, interpolation=cv2.INTER_CUBIC
|
||||
)
|
||||
o_img = cv2.resize(
|
||||
apply_multistop_colormap(normalise(Ho), object_stops),
|
||||
OUT_SHAPE, interpolation=cv2.INTER_CUBIC
|
||||
)
|
||||
|
||||
cv2.imwrite(str(out_dir / f"{data_set}_faces_heatmap.png"), f_img)
|
||||
cv2.imwrite(str(out_dir / f"{data_set}_objects_heatmap.png"), o_img)
|
||||
|
||||
# ---------- combined overlay -----------------------------------------------
|
||||
comb = cv2.addWeighted(f_img, 0.5, o_img, 0.5, 0)
|
||||
|
||||
# Set background pixels (where both heats are zero) to bg_color
|
||||
mask_small = cv2.resize(((Hf == 0) & (Ho == 0)).astype(np.uint8),
|
||||
OUT_SHAPE, interpolation=cv2.INTER_NEAREST).astype(bool)
|
||||
comb[mask_small] = bg_bgr
|
||||
|
||||
cv2.imwrite(str(out_dir / f"{data_set}_combined_heatmap.png"), comb)
|
||||
|
||||
print("[info] heat-maps written to", out_dir)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,167 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
heatmap_generator.py – BOUNDING‑BOX VERSION
|
||||
|
||||
Visualise the spatial distribution of **entire bounding boxes**
|
||||
rather than just their centres.
|
||||
|
||||
• faces → purple (red + blue channels)
|
||||
• objects → yellow (red + green channels)
|
||||
• background → white
|
||||
|
||||
Outputs
|
||||
-------
|
||||
<dataset>_faces_heatmap.png
|
||||
<dataset>_objects_heatmap.png
|
||||
<dataset>_combined_heatmap.png
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib.colors import LinearSegmentedColormap
|
||||
from PIL import Image
|
||||
|
||||
# ---------- colour utilities -------------------------------------------------
|
||||
PURPLE_CMAP = LinearSegmentedColormap.from_list(
|
||||
"white_to_purple", ["#ffffff", "#800080"]
|
||||
)
|
||||
YELLOW_CMAP = LinearSegmentedColormap.from_list(
|
||||
"white_to_yellow", ["#ffffff", "#ffff00"]
|
||||
)
|
||||
|
||||
# ---------- drawing helpers --------------------------------------------------
|
||||
def _save_single_heatmap(H: np.ndarray, path: Path, cmap):
|
||||
plt.figure(figsize=(6, 6))
|
||||
plt.imshow(H, origin="lower", cmap=cmap, interpolation="bilinear")
|
||||
plt.axis("off")
|
||||
plt.tight_layout()
|
||||
plt.savefig(path, dpi=300, bbox_inches="tight")
|
||||
plt.close()
|
||||
print(f"[INFO] Wrote {path}")
|
||||
|
||||
|
||||
def _save_combined_heatmap(H_faces: np.ndarray, H_objs: np.ndarray, path: Path):
|
||||
f_norm = H_faces / (H_faces.max() or 1.0)
|
||||
o_norm = H_objs / (H_objs.max() or 1.0)
|
||||
|
||||
rgb = np.zeros((*H_faces.shape, 3), dtype=np.float32)
|
||||
rgb[..., 0] = f_norm + o_norm # red – faces + objects
|
||||
rgb[..., 1] = o_norm # green – objects only
|
||||
rgb[..., 2] = f_norm # blue – faces only
|
||||
rgb = np.clip(rgb, 0.0, 1.0)
|
||||
|
||||
plt.figure(figsize=(6, 6))
|
||||
plt.imshow(rgb, origin="lower", interpolation="bilinear")
|
||||
plt.axis("off")
|
||||
plt.tight_layout()
|
||||
plt.savefig(path, dpi=300, bbox_inches="tight")
|
||||
plt.close()
|
||||
print(f"[INFO] Wrote {path}")
|
||||
|
||||
# ---------- core accumulation logic ------------------------------------------
|
||||
def accumulate_heatmaps(img_files, grid_size):
|
||||
"""Return two (grid_size × grid_size) arrays: faces_heat, objects_heat."""
|
||||
faces_heat = np.zeros((grid_size, grid_size), dtype=np.float32)
|
||||
objects_heat = np.zeros_like(faces_heat)
|
||||
|
||||
for img_path in img_files:
|
||||
meta_path = img_path.with_suffix(".json")
|
||||
if not meta_path.exists():
|
||||
print(f"[WARN] Missing metadata: {meta_path}")
|
||||
continue
|
||||
|
||||
# read size
|
||||
try:
|
||||
with Image.open(img_path) as im:
|
||||
w, h = im.size
|
||||
except Exception as e:
|
||||
print(f"[WARN] Cannot open {img_path}: {e}")
|
||||
continue
|
||||
|
||||
# read JSON
|
||||
try:
|
||||
data = json.loads(meta_path.read_text())
|
||||
except Exception as e:
|
||||
print(f"[WARN] Cannot parse {meta_path}: {e}")
|
||||
continue
|
||||
|
||||
# ------- helper: paint one box ---------------------------------------
|
||||
def paint_box(bbox, target):
|
||||
if not bbox or len(bbox) != 4:
|
||||
return
|
||||
x1, y1, x2, y2 = bbox
|
||||
if x2 <= x1 or y2 <= y1:
|
||||
return # malformed box
|
||||
|
||||
# normalise to [0,1]
|
||||
x1n, x2n = x1 / w, x2 / w
|
||||
y1n, y2n = y1 / h, y2 / h
|
||||
|
||||
# convert to grid indices
|
||||
ix1 = int(np.clip(np.floor(x1n * grid_size), 0, grid_size - 1))
|
||||
ix2 = int(np.clip(np.ceil( x2n * grid_size), 0, grid_size - 1))
|
||||
iy1 = int(np.clip(np.floor(y1n * grid_size), 0, grid_size - 1))
|
||||
iy2 = int(np.clip(np.ceil( y2n * grid_size), 0, grid_size - 1))
|
||||
|
||||
# increment every cell the box covers
|
||||
target[iy1:iy2 + 1, ix1:ix2 + 1] += 1.0
|
||||
|
||||
# faces
|
||||
for person in data.get("persons", []):
|
||||
paint_box(person.get("face_bbox") or person.get("bbox"), faces_heat)
|
||||
|
||||
# objects
|
||||
for obj in data.get("objects", []):
|
||||
paint_box(obj.get("bbox"), objects_heat)
|
||||
|
||||
return faces_heat, objects_heat
|
||||
|
||||
# ---------- main -------------------------------------------------------------
|
||||
def main(args):
|
||||
input_dir = Path(args.input_dir)
|
||||
output_dir = Path(args.output_dir)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
prefix = input_dir.resolve().name # e.g. "holiday_photos"
|
||||
|
||||
img_files = list(input_dir.glob("*.jpg")) + list(input_dir.glob("*.png"))
|
||||
if not img_files:
|
||||
raise RuntimeError(f"No *.jpg or *.png files found in {input_dir}")
|
||||
|
||||
faces_H, objs_H = accumulate_heatmaps(img_files, args.grid_size)
|
||||
|
||||
# separate maps
|
||||
_save_single_heatmap(
|
||||
faces_H,
|
||||
output_dir / f"{prefix}_faces_heatmap.png",
|
||||
cmap=PURPLE_CMAP,
|
||||
)
|
||||
_save_single_heatmap(
|
||||
objs_H,
|
||||
output_dir / f"{prefix}_objects_heatmap.png",
|
||||
cmap=YELLOW_CMAP,
|
||||
)
|
||||
|
||||
# combined map
|
||||
_save_combined_heatmap(
|
||||
faces_H,
|
||||
objs_H,
|
||||
output_dir / f"{prefix}_combined_heatmap.png",
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
p = argparse.ArgumentParser(
|
||||
description="Generate heat‑maps of **whole bounding boxes** for faces & objects."
|
||||
)
|
||||
p.add_argument("--input_dir", required=True,
|
||||
help="Directory with images (*.jpg/*.png) and matching *.json files")
|
||||
p.add_argument("--output_dir", required=True,
|
||||
help="Directory to store heat‑maps")
|
||||
p.add_argument("--grid_size", type=int, default=100,
|
||||
help="Number of histogram bins per axis (default: 100)")
|
||||
main(p.parse_args())
|
||||