Reproduzierbar machen, was den 'meldet OK, aber nichts erkennbar'-Befund gestuetzt hat. Alle Skripte nutzen ausschliesslich die Beispielfotos aus dem insightface-Paket, keine Nutzerfotos. - probe_identity.py Identitaetsgewinn je Filterkonfiguration - probe_mask_width.py Maskenbreite gegen Swap-Pixel ausserhalb - probe_blend_undo.py Wie viele Swap-Pixel der Blend zuruecknimmt - probe_blend_necessity.py Blend: schaedlich UND nahterzeugend - probe_tradeoff.py Identitaet <-> Hintergrund, mit altem Blend - probe_batch_identity.py Gegenprobe ueber den vollen Batch-Pfad Bilder und Messergebnisse landen in tests/out/ (bereits in .gitignore).
110 lines
4.3 KiB
Python
110 lines
4.3 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
PRUEFT DEN MECHANISMUS hinter dem Identitaetsverlust durch soft_blend.
|
|
|
|
Hypothese: `build_face_mask` zeichnet eine Ellipse mit
|
|
half_w = eye_dx * 0.80
|
|
Der Augenabstand betraegt typischerweise ~0.45 der Gesichtsbreite, die
|
|
Halbbreite der Maske also nur 0.80*0.45 = 0.36 der Gesichtsbreite - die Ellipse
|
|
ist damit SCHMALER als das Gesicht. Wangen, Schlaefen und Kiefer liegen
|
|
ausserhalb der Maske. `apply_soft_face_blend` mischt dort das ORIGINAL zurueck
|
|
und stellt genau die Gesichtspartien wieder her, die die Identitaet tragen.
|
|
|
|
Gemessen wird:
|
|
1) wie viel Prozent der BBox die Gesichtsmaske wirklich abdeckt
|
|
2) wie viele der von inswapper geaenderten Pixel AUSSERHALB der Maske liegen
|
|
(das sind genau die vom Blend zurueckgenommenen Identitaets-Pixel)
|
|
3) derselbe Lauf mit korrigierter Maskenbreite
|
|
|
|
Aufruf: .venv/bin/python tests/probe_mask_width.py
|
|
"""
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import cv2
|
|
import numpy as np
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from core.config import cv2_imread_unicode # noqa: E402
|
|
from core.face_engine import ( # noqa: E402
|
|
FaceSwapper, normalize_bbox, build_face_mask, apply_soft_face_blend,
|
|
)
|
|
from probe_identity import IMGS, face_crop, primary_embedding # noqa: E402
|
|
|
|
|
|
def mask_width_factor(kps, img_shape, bbox, factor):
|
|
"""build_face_mask mit veraenderbarem Breitenfaktor, sonst identisch."""
|
|
h, w = int(img_shape[0]), int(img_shape[1])
|
|
k = np.asarray(kps, dtype=np.float32)
|
|
eye_l, eye_r, nose, mouth_l, mouth_r = k[0], k[1], k[2], k[3], k[4]
|
|
eye_dx = float(np.linalg.norm(eye_r - eye_l))
|
|
eye_mid = (eye_l + eye_r) / 2.0
|
|
chin = (mouth_l + mouth_r) / 2.0
|
|
cx = float((eye_mid[0] + chin[0] + nose[0]) / 3.0)
|
|
half_w = eye_dx * factor
|
|
top = float(min(eye_l[1], eye_r[1])) - eye_dx * 0.92
|
|
bottom = float(chin[1]) + eye_dx * 0.30
|
|
if bottom - top < eye_dx * 0.8:
|
|
bottom = top + eye_dx * 1.3
|
|
mask = np.zeros((h, w), np.uint8)
|
|
cv2.ellipse(mask, (int(cx), int((top + bottom) / 2.0)),
|
|
(int(max(3, half_w)), int(max(3, (bottom - top) / 2.0))),
|
|
0, 0, 360, 255, -1)
|
|
sigma = max(1.0, eye_dx * 0.28)
|
|
return cv2.GaussianBlur(mask, (0, 0), sigma).astype(np.float32) / 255.0
|
|
|
|
|
|
def main():
|
|
sw = FaceSwapper(log_fn=lambda m: None)
|
|
sw.init_models()
|
|
app = sw.app
|
|
|
|
group = cv2_imread_unicode(IMGS / "t1.jpg")
|
|
faces = app.get(group)
|
|
src_img = face_crop(group, faces[0])
|
|
tgt_img = face_crop(group, faces[1])
|
|
src_face = sw.get_first_face(src_img)
|
|
|
|
e_src = primary_embedding(app, src_img)
|
|
e_orig = primary_embedding(app, tgt_img)
|
|
|
|
# WICHTIG: soft_blend muss aus, sonst ist die "pure"-Basis bereits geblendet
|
|
# und die Messung zaehlt den Blend doppelt.
|
|
sw.color = sw.enhance = sw.soft_blend = False
|
|
pure, _ = sw.swap_single_frame(tgt_img, src_face)
|
|
pure_diff = (np.abs(pure.astype(np.float32) - tgt_img.astype(np.float32)).max(axis=2) > 8)
|
|
|
|
f = app.get(tgt_img)[0]
|
|
nb = normalize_bbox(f.bbox, tgt_img.shape)
|
|
x1, y1, x2, y2 = nb
|
|
bbox_px = (x2 - x1) * (y2 - y1)
|
|
eye_dx = float(np.linalg.norm(f.kps[1] - f.kps[0]))
|
|
print(f"BBox {bbox_px} px, Augenabstand {eye_dx:.1f} px")
|
|
print(f"Masken-Halbbreite bei Faktor 0.80: {eye_dx*0.80:.1f} px "
|
|
f"= {200*eye_dx*0.80/bbox_px:.0f} % der BBox-Breite\n")
|
|
|
|
for factor in (0.80, 0.95, 1.10, 1.25):
|
|
m = mask_width_factor(f.kps, tgt_img.shape, nb, factor)
|
|
mm = m > 0.5
|
|
cov = 100.0 * mm[y1:y2, x1:x2].sum() / bbox_px
|
|
outside = int((pure_diff & ~mm).sum())
|
|
total = int(pure_diff.sum())
|
|
|
|
blended = apply_soft_face_blend(pure.copy(), tgt_img, nb, face_mask=m)
|
|
e_out = primary_embedding(app, blended)
|
|
s_orig = float(np.dot(e_out, e_orig))
|
|
s_src = float(np.dot(e_out, e_src))
|
|
print(f"Faktor {factor:4.2f}: Maske deckt {cov:5.1f} % der BBox | "
|
|
f"Swap-Pixel ausserhalb der Maske: {outside:5d}/{total} ({100*outside/max(total,1):4.1f} %) | "
|
|
f"Identitaet: zum-Orig {s_orig:.3f} zur-Quelle {s_src:.3f} (Gewinn {s_src-s_orig:+.3f})")
|
|
|
|
print("\n-> Je breiter die Maske, desto mehr Swap-Pixel bleiben erhalten "
|
|
"und desto staerker wandert die Identitaet zur Quelle.")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|