Files

322 lines
10 KiB
Python

#!/usr/bin/env python3
import argparse
import base64
import json
from pathlib import Path
from typing import Optional, Tuple, Dict, Any, List
import cv2
import numpy as np
# ------------------------- Decoding & placement -------------------------
def decode_base64_png_to_mask(b64_png: Optional[str]) -> Optional[np.ndarray]:
"""
Decode base64-encoded PNG into a boolean mask (HxW), where any non-zero pixel is True.
Returns None if input is missing or invalid.
"""
if not b64_png or not isinstance(b64_png, str):
return None
if b64_png.startswith("data:"): # allow data URLs
parts = b64_png.split(",", 1)
b64_png = parts[1] if len(parts) == 2 else b64_png
try:
buf = base64.b64decode(b64_png, validate=False)
except Exception:
return None
arr = np.frombuffer(buf, dtype=np.uint8)
img = cv2.imdecode(arr, cv2.IMREAD_UNCHANGED)
if img is None:
return None
if img.ndim == 3:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
return img > 0
def place_mask_on_full_image(
mask: np.ndarray,
bbox: Tuple[int, int, int, int],
image_hw: Tuple[int, int],
) -> Optional[np.ndarray]:
"""
Place a bbox-local mask into a full-image boolean canvas using bbox coords.
- mask: HxW bool (decoded from base64)
- bbox: [x0,y0,x1,y1]
- image_hw: (H, W) of the full image
Returns full-image boolean mask (H,W) or None if nothing can be placed.
Handles:
* resizing mask to bbox size with NEAREST
* clipping bbox to image bounds (and cropping mask accordingly)
"""
H, W = image_hw
x0, y0, x1, y1 = map(int, bbox)
if x1 < x0:
x0, x1 = x1, x0
if y1 < y0:
y0, y1 = y1, y0
# Entirely outside?
if x1 <= 0 or y1 <= 0 or x0 >= W or y0 >= H:
return None
bw = max(0, x1 - x0)
bh = max(0, y1 - y0)
if bw == 0 or bh == 0:
return None
# Resize local mask to bbox size if needed
mh, mw = mask.shape[:2]
if (mw, mh) != (bw, bh):
mask = cv2.resize(mask.astype(np.uint8), (bw, bh), interpolation=cv2.INTER_NEAREST).astype(bool)
# Clip bbox to image
x0c = max(0, min(x0, W))
y0c = max(0, min(y0, H))
x1c = max(0, min(x1, W))
y1c = max(0, min(y1, H))
if x1c <= x0c or y1c <= y0c:
return None
# Calculate crop inside mask corresponding to the clipped bbox
dx_left = x0c - x0
dy_top = y0c - y0
dx_right = (x1 - x0) - (x1c - x0c) - dx_left
dy_bottom = (y1 - y0) - (y1c - y0c) - dy_top
y_start = int(max(0, dy_top))
x_start = int(max(0, dx_left))
y_end = int(mask.shape[0] - max(0, dy_bottom))
x_end = int(mask.shape[1] - max(0, dx_right))
if y_end <= y_start or x_end <= x_start:
return None
submask = mask[y_start:y_end, x_start:x_end]
canvas = np.zeros((H, W), dtype=bool)
canvas[y0c:y1c, x0c:x1c] = submask
return canvas
def load_person_full_masks_from_json(json_path: Path) -> Tuple[List[np.ndarray], Dict[str, Any]]:
"""
Loads image + persons from JSON and returns a list of full-image boolean masks (one per person).
JSON format:
{
"image": "filename.jpg",
"persons": [
{"face_bbox": [x0,y0,x1,y1], "face_segment": "<base64-png>"},
...
]
}
Falls back to single "person" if "persons" missing.
Returns (list_of_masks, info_dict)
"""
info = {"json": str(json_path), "image_path": None, "status": "ok"}
try:
with json_path.open("r", encoding="utf-8") as f:
data = json.load(f)
except Exception:
info["status"] = "json_load_failed"
return [], info
img_name = data.get("image")
if not img_name:
info["status"] = "image_field_missing"
return [], info
img_path = json_path.parent / img_name
info["image_path"] = str(img_path)
img = cv2.imread(str(img_path), cv2.IMREAD_UNCHANGED)
if img is None:
info["status"] = "image_load_failed"
return [], info
H, W = img.shape[:2]
persons = data.get("persons")
if persons is None:
# fallback to single "person"
p = data.get("person")
persons = [p] if isinstance(p, dict) else []
masks: List[np.ndarray] = []
for p in persons:
if not isinstance(p, dict):
continue
b64 = p.get("face_segment")
bbox = p.get("face_bbox")
if not b64 or bbox is None or not (isinstance(bbox, (list, tuple)) and len(bbox) == 4):
continue
local = decode_base64_png_to_mask(b64)
if local is None:
continue
full = place_mask_on_full_image(local, tuple(map(int, bbox)), (H, W))
if full is None:
continue
masks.append(full)
return masks, info
# ------------------------- IoU & matching -------------------------
def iou_same_shape(a: np.ndarray, b: np.ndarray) -> float:
inter = np.logical_and(a, b).sum(dtype=np.int64)
uni = np.logical_or(a, b).sum(dtype=np.int64)
if uni == 0:
return 1.0 # both empty
return float(inter) / float(uni)
def resize_masks_to_shape(masks: List[np.ndarray], shape_hw: Tuple[int, int]) -> List[np.ndarray]:
if not masks:
return []
H, W = shape_hw
out = []
for m in masks:
if m.shape != (H, W):
m2 = cv2.resize(m.astype(np.uint8), (W, H), interpolation=cv2.INTER_NEAREST).astype(bool)
out.append(m2)
else:
out.append(m)
return out
def greedy_match_by_iou(A: List[np.ndarray], B: List[np.ndarray]) -> List[Tuple[int, int, float]]:
"""
One-to-one greedy matching maximizing IoU.
Returns list of tuples (i_in_A, j_in_B, iou_value).
Matches even if IoU == 0 (so present-only mean includes zero-overlap pairs).
"""
if not A or not B:
return []
# Build IoU matrix
H, W = A[0].shape
# Ensure B masks have same shape
B = resize_masks_to_shape(B, (H, W))
nA, nB = len(A), len(B)
M = np.zeros((nA, nB), dtype=np.float32)
for i in range(nA):
for j in range(nB):
M[i, j] = iou_same_shape(A[i], B[j])
matches: List[Tuple[int, int, float]] = []
usedA = set()
usedB = set()
while True:
# find global max among unused rows/cols
best = -1.0
best_i = best_j = -1
for i in range(nA):
if i in usedA:
continue
for j in range(nB):
if j in usedB:
continue
val = float(M[i, j])
if val > best:
best = val
best_i, best_j = i, j
if best_i < 0:
break
matches.append((best_i, best_j, best))
usedA.add(best_i)
usedB.add(best_j)
if len(usedA) == nA or len(usedB) == nB:
break
return matches
# ------------------------- Main pipeline -------------------------
def main():
parser = argparse.ArgumentParser(
description="Compute mean IoU of face segments (full-image) between two folders of JSON files with multiple persons."
)
parser.add_argument("originals", type=Path, help="Folder with original JSON files and images")
parser.add_argument("modified", type=Path, help="Folder with modified JSON files and images")
parser.add_argument("--ext", default=".json", help="JSON extension (default: .json)")
args = parser.parse_args()
orig_dir: Path = args.originals
mod_dir: Path = args.modified
ext = args.ext if args.ext.startswith(".") else "." + args.ext
if not orig_dir.is_dir() or not mod_dir.is_dir():
raise SystemExit("Both inputs must be directories.")
orig_files = {p.name: p for p in orig_dir.glob(f"*{ext}") if p.is_file()}
mod_files = {p.name: p for p in mod_dir.glob(f"*{ext}") if p.is_file()}
names = sorted(set(orig_files).intersection(mod_files))
if not names:
raise SystemExit("No matching JSON filenames found between the two folders.")
# Aggregates
ious_all: List[float] = [] # includes zeros for unmatched persons
ious_present: List[float] = [] # only matched pairs (both present)
total_A = total_B = 0
total_matched = total_unmatched_A = total_unmatched_B = 0
for name in names:
A_masks, infoA = load_person_full_masks_from_json(orig_files[name])
B_masks, infoB = load_person_full_masks_from_json(mod_files[name])
if infoA["status"] != "ok" or infoB["status"] != "ok":
print(infoA)
print(infoB)
exit()
total_A += len(A_masks)
total_B += len(B_masks)
#TODO hier weiter lesen -------------------<<<<<<<<<<<<<<<<<<<<<<<<<<<
if not A_masks and not B_masks:
# nothing in either => count as 0 in 'all', skip present-only
continue
# If both sides have masks but different full-image shapes (shouldn't happen per file),
# we normalize B to A's shape inside the matcher; track if that occurred.
# (Detect by checking any B mask shape vs any A mask shape.)
if A_masks and B_masks and A_masks[0].shape != B_masks[0].shape:
print("Full images have not same shape")
exit()
matches = greedy_match_by_iou(A_masks, B_masks)
total_matched += len(matches)
# Present-only IoUs (matched pairs)
for _, _, v in matches:
ious_present.append(float(v))
ious_all.append(float(v))
# Unmatched persons contribute IoU = 0 to 'all'
unmatched_A = len(A_masks) - len(matches)
unmatched_B = len(B_masks) - len(matches)
total_unmatched_A += unmatched_A
total_unmatched_B += unmatched_B
ious_all.extend([0.0] * (unmatched_A + unmatched_B))
mean_all = float(np.mean(ious_all)) if ious_all else float("nan")
mean_present = float(np.mean(ious_present)) if ious_present else float("nan")
print(f"Files compared: {len(names)}")
print(f" persons (original): {total_A}")
print(f" persons (modified): {total_B}")
print(f" matched pairs: {total_matched}")
print(f" unmatched original: {total_unmatched_A}")
print(f" unmatched modified: {total_unmatched_B}")
print()
print(f"Mean IoU (present-only): {mean_present:.6f}")
print(f"Mean IoU (all persons; unmatched ⇒ 0): {mean_all:.6f}")
if __name__ == "__main__":
main()