landmarkdiff 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- landmarkdiff/__init__.py +40 -0
- landmarkdiff/__main__.py +207 -0
- landmarkdiff/api_client.py +316 -0
- landmarkdiff/arcface_torch.py +583 -0
- landmarkdiff/audit.py +338 -0
- landmarkdiff/augmentation.py +293 -0
- landmarkdiff/benchmark.py +213 -0
- landmarkdiff/checkpoint_manager.py +361 -0
- landmarkdiff/cli.py +252 -0
- landmarkdiff/clinical.py +223 -0
- landmarkdiff/conditioning.py +278 -0
- landmarkdiff/config.py +358 -0
- landmarkdiff/curriculum.py +191 -0
- landmarkdiff/data.py +405 -0
- landmarkdiff/data_version.py +301 -0
- landmarkdiff/displacement_model.py +745 -0
- landmarkdiff/ensemble.py +330 -0
- landmarkdiff/evaluation.py +415 -0
- landmarkdiff/experiment_tracker.py +231 -0
- landmarkdiff/face_verifier.py +947 -0
- landmarkdiff/fid.py +244 -0
- landmarkdiff/hyperparam.py +347 -0
- landmarkdiff/inference.py +754 -0
- landmarkdiff/landmarks.py +432 -0
- landmarkdiff/log.py +90 -0
- landmarkdiff/losses.py +348 -0
- landmarkdiff/manipulation.py +651 -0
- landmarkdiff/masking.py +316 -0
- landmarkdiff/metrics_agg.py +313 -0
- landmarkdiff/metrics_viz.py +464 -0
- landmarkdiff/model_registry.py +362 -0
- landmarkdiff/morphometry.py +342 -0
- landmarkdiff/postprocess.py +600 -0
- landmarkdiff/py.typed +0 -0
- landmarkdiff/safety.py +395 -0
- landmarkdiff/synthetic/__init__.py +23 -0
- landmarkdiff/synthetic/augmentation.py +188 -0
- landmarkdiff/synthetic/pair_generator.py +208 -0
- landmarkdiff/synthetic/tps_warp.py +273 -0
- landmarkdiff/validation.py +324 -0
- landmarkdiff-0.2.3.dist-info/METADATA +1173 -0
- landmarkdiff-0.2.3.dist-info/RECORD +46 -0
- landmarkdiff-0.2.3.dist-info/WHEEL +5 -0
- landmarkdiff-0.2.3.dist-info/entry_points.txt +2 -0
- landmarkdiff-0.2.3.dist-info/licenses/LICENSE +21 -0
- landmarkdiff-0.2.3.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,600 @@
|
|
|
1
|
+
"""Post-processing pipeline for photorealistic face output.
|
|
2
|
+
|
|
3
|
+
Neural net components:
|
|
4
|
+
- CodeFormer (primary): face restoration with controllable fidelity-quality tradeoff
|
|
5
|
+
- GFPGAN (fallback): face restoration for diffusion artifact repair
|
|
6
|
+
- Real-ESRGAN: neural super-resolution for background regions
|
|
7
|
+
- ArcFace: identity verification to flag drift between input/output
|
|
8
|
+
|
|
9
|
+
Classical components:
|
|
10
|
+
- Multi-band Laplacian pyramid blending (replaces simple alpha blend)
|
|
11
|
+
- Frequency-aware sharpening (recovers fine skin texture)
|
|
12
|
+
- Color histogram matching (ensures skin tone consistency)
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import cv2
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
# Singleton model caches -- load once, reuse across calls
|
|
21
|
+
_CODEFORMER_MODEL = None
|
|
22
|
+
_GFPGAN_HELPER = None
|
|
23
|
+
_REALESRGAN_UPSAMPLER = None
|
|
24
|
+
_ARCFACE_APP = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def laplacian_pyramid_blend(
|
|
28
|
+
source: np.ndarray,
|
|
29
|
+
target: np.ndarray,
|
|
30
|
+
mask: np.ndarray,
|
|
31
|
+
levels: int = 6,
|
|
32
|
+
) -> np.ndarray:
|
|
33
|
+
"""Multi-band Laplacian pyramid blending for seamless compositing.
|
|
34
|
+
|
|
35
|
+
Unlike simple alpha blending which creates visible halos at mask edges,
|
|
36
|
+
Laplacian blending operates at multiple frequency bands. Low frequencies
|
|
37
|
+
(overall color/lighting) blend smoothly, high frequencies (skin texture,
|
|
38
|
+
pores, hair) transition sharply. This eliminates the "pasted on" look.
|
|
39
|
+
|
|
40
|
+
Args:
|
|
41
|
+
source: BGR image to blend IN (the surgical result).
|
|
42
|
+
target: BGR image to blend INTO (the original photo).
|
|
43
|
+
mask: Float32 mask [0-1] (1 = source region).
|
|
44
|
+
levels: Number of pyramid levels (6 works well for 512x512).
|
|
45
|
+
|
|
46
|
+
Returns:
|
|
47
|
+
Seamlessly composited BGR image.
|
|
48
|
+
"""
|
|
49
|
+
# Ensure same size
|
|
50
|
+
h, w = target.shape[:2]
|
|
51
|
+
source = cv2.resize(source, (w, h)) if source.shape[:2] != (h, w) else source
|
|
52
|
+
|
|
53
|
+
# Normalize mask
|
|
54
|
+
mask_f = mask.astype(np.float32)
|
|
55
|
+
if mask_f.max() > 1.0:
|
|
56
|
+
mask_f = mask_f / 255.0
|
|
57
|
+
mask_3ch = np.stack([mask_f] * 3, axis=-1) if mask_f.ndim == 2 else mask_f
|
|
58
|
+
|
|
59
|
+
# Make dimensions divisible by 2^levels
|
|
60
|
+
factor = 2**levels
|
|
61
|
+
new_h = (h + factor - 1) // factor * factor
|
|
62
|
+
new_w = (w + factor - 1) // factor * factor
|
|
63
|
+
|
|
64
|
+
if new_h != h or new_w != w:
|
|
65
|
+
source = cv2.resize(source, (new_w, new_h))
|
|
66
|
+
target = cv2.resize(target, (new_w, new_h))
|
|
67
|
+
mask_3ch = cv2.resize(mask_3ch, (new_w, new_h))
|
|
68
|
+
|
|
69
|
+
src_f = source.astype(np.float32)
|
|
70
|
+
tgt_f = target.astype(np.float32)
|
|
71
|
+
|
|
72
|
+
# Build Gaussian pyramids for the mask
|
|
73
|
+
mask_pyr = [mask_3ch]
|
|
74
|
+
for _ in range(levels):
|
|
75
|
+
mask_pyr.append(cv2.pyrDown(mask_pyr[-1]))
|
|
76
|
+
|
|
77
|
+
# Build Laplacian pyramids for source and target
|
|
78
|
+
src_lap = _build_laplacian_pyramid(src_f, levels)
|
|
79
|
+
tgt_lap = _build_laplacian_pyramid(tgt_f, levels)
|
|
80
|
+
|
|
81
|
+
# Blend each level using the mask at that resolution
|
|
82
|
+
blended_lap = []
|
|
83
|
+
for i in range(levels + 1):
|
|
84
|
+
sl = src_lap[i]
|
|
85
|
+
tl = tgt_lap[i]
|
|
86
|
+
ml = mask_pyr[i]
|
|
87
|
+
# Resize mask to match level shape if needed
|
|
88
|
+
if ml.shape[:2] != sl.shape[:2]:
|
|
89
|
+
ml = cv2.resize(ml, (sl.shape[1], sl.shape[0]))
|
|
90
|
+
blended = sl * ml + tl * (1.0 - ml)
|
|
91
|
+
blended_lap.append(blended)
|
|
92
|
+
|
|
93
|
+
# Reconstruct from blended Laplacian
|
|
94
|
+
result = _reconstruct_from_laplacian(blended_lap)
|
|
95
|
+
|
|
96
|
+
# Crop back to original size
|
|
97
|
+
result = result[:h, :w]
|
|
98
|
+
return np.clip(result, 0, 255).astype(np.uint8)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def _build_laplacian_pyramid(
|
|
102
|
+
image: np.ndarray,
|
|
103
|
+
levels: int,
|
|
104
|
+
) -> list[np.ndarray]:
|
|
105
|
+
"""Build Laplacian pyramid from an image."""
|
|
106
|
+
gaussian = [image.copy()]
|
|
107
|
+
for _ in range(levels):
|
|
108
|
+
gaussian.append(cv2.pyrDown(gaussian[-1]))
|
|
109
|
+
|
|
110
|
+
laplacian = []
|
|
111
|
+
for i in range(levels):
|
|
112
|
+
upsampled = cv2.pyrUp(gaussian[i + 1])
|
|
113
|
+
# Match sizes (pyrUp can add a pixel)
|
|
114
|
+
gh, gw = gaussian[i].shape[:2]
|
|
115
|
+
upsampled = upsampled[:gh, :gw]
|
|
116
|
+
laplacian.append(gaussian[i] - upsampled)
|
|
117
|
+
|
|
118
|
+
laplacian.append(gaussian[-1]) # coarsest level
|
|
119
|
+
return laplacian
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _reconstruct_from_laplacian(pyramid: list[np.ndarray]) -> np.ndarray:
|
|
123
|
+
"""Reconstruct image from Laplacian pyramid."""
|
|
124
|
+
image = pyramid[-1].copy()
|
|
125
|
+
for i in range(len(pyramid) - 2, -1, -1):
|
|
126
|
+
image = cv2.pyrUp(image)
|
|
127
|
+
lh, lw = pyramid[i].shape[:2]
|
|
128
|
+
image = image[:lh, :lw]
|
|
129
|
+
image = image + pyramid[i]
|
|
130
|
+
return image
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def frequency_aware_sharpen(
|
|
134
|
+
image: np.ndarray,
|
|
135
|
+
strength: float = 0.3,
|
|
136
|
+
radius: int = 3,
|
|
137
|
+
) -> np.ndarray:
|
|
138
|
+
"""Sharpen high-frequency detail (skin texture, pores) without amplifying noise.
|
|
139
|
+
|
|
140
|
+
Uses unsharp masking in LAB space (luminance only) to avoid
|
|
141
|
+
color fringing. Preserves the smooth look of diffusion output
|
|
142
|
+
while recovering fine texture detail.
|
|
143
|
+
|
|
144
|
+
Args:
|
|
145
|
+
image: BGR image.
|
|
146
|
+
strength: Sharpening strength (0.2-0.5 typical for faces).
|
|
147
|
+
radius: Gaussian blur radius for unsharp mask.
|
|
148
|
+
|
|
149
|
+
Returns:
|
|
150
|
+
Sharpened BGR image.
|
|
151
|
+
"""
|
|
152
|
+
lab = cv2.cvtColor(image, cv2.COLOR_BGR2LAB).astype(np.float32)
|
|
153
|
+
l_channel = lab[:, :, 0]
|
|
154
|
+
|
|
155
|
+
# Unsharp mask on luminance only
|
|
156
|
+
ksize = radius * 2 + 1
|
|
157
|
+
blurred = cv2.GaussianBlur(l_channel, (ksize, ksize), 0)
|
|
158
|
+
sharpened = l_channel + strength * (l_channel - blurred)
|
|
159
|
+
|
|
160
|
+
lab[:, :, 0] = np.clip(sharpened, 0, 255)
|
|
161
|
+
return cv2.cvtColor(lab.astype(np.uint8), cv2.COLOR_LAB2BGR)
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def restore_face_gfpgan(
|
|
165
|
+
image: np.ndarray,
|
|
166
|
+
upscale: int = 1,
|
|
167
|
+
) -> np.ndarray:
|
|
168
|
+
"""Restore face quality using GFPGAN.
|
|
169
|
+
|
|
170
|
+
Fixes common diffusion artifacts: blurry eyes, distorted features,
|
|
171
|
+
inconsistent skin texture. The restored face is then blended back
|
|
172
|
+
into the original for a natural look.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
image: BGR face image (any size).
|
|
176
|
+
upscale: Upscale factor (1 = same size, 2 = 2x).
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
Restored BGR image, or original if GFPGAN unavailable.
|
|
180
|
+
"""
|
|
181
|
+
try:
|
|
182
|
+
from gfpgan import GFPGANer
|
|
183
|
+
except ImportError:
|
|
184
|
+
return image
|
|
185
|
+
|
|
186
|
+
try:
|
|
187
|
+
global _GFPGAN_HELPER
|
|
188
|
+
# Singleton: avoid reloading ~300MB GFPGAN model on every call
|
|
189
|
+
if _GFPGAN_HELPER is None:
|
|
190
|
+
_GFPGAN_HELPER = GFPGANer(
|
|
191
|
+
model_path="https://github.com/TencentARC/GFPGAN/releases/download/v1.3.0/GFPGANv1.3.pth",
|
|
192
|
+
upscale=upscale,
|
|
193
|
+
arch="clean",
|
|
194
|
+
channel_multiplier=2,
|
|
195
|
+
bg_upsampler=None,
|
|
196
|
+
)
|
|
197
|
+
_, _, restored = _GFPGAN_HELPER.enhance(
|
|
198
|
+
image,
|
|
199
|
+
has_aligned=False,
|
|
200
|
+
only_center_face=True,
|
|
201
|
+
paste_back=True,
|
|
202
|
+
)
|
|
203
|
+
if restored is not None:
|
|
204
|
+
return restored
|
|
205
|
+
except Exception:
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
return image
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def restore_face_codeformer(
|
|
212
|
+
image: np.ndarray,
|
|
213
|
+
fidelity: float = 0.7,
|
|
214
|
+
upscale: int = 1,
|
|
215
|
+
) -> np.ndarray:
|
|
216
|
+
"""Restore face quality using CodeFormer (neural net).
|
|
217
|
+
|
|
218
|
+
CodeFormer uses a Transformer-based codebook lookup to restore degraded
|
|
219
|
+
faces. The fidelity parameter controls the quality-fidelity tradeoff:
|
|
220
|
+
lower values produce higher quality but may alter identity slightly,
|
|
221
|
+
higher values preserve identity but fix fewer artifacts.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
image: BGR face image.
|
|
225
|
+
fidelity: Quality-fidelity balance (0.0=quality, 1.0=fidelity). 0.7 default.
|
|
226
|
+
upscale: Upscale factor (1 = same size).
|
|
227
|
+
|
|
228
|
+
Returns:
|
|
229
|
+
Restored BGR image, or original if CodeFormer unavailable.
|
|
230
|
+
"""
|
|
231
|
+
try:
|
|
232
|
+
import torch
|
|
233
|
+
from codeformer.basicsr.utils import img2tensor, tensor2img
|
|
234
|
+
from codeformer.basicsr.utils.download_util import load_file_from_url
|
|
235
|
+
from codeformer.facelib.utils.face_restoration_helper import FaceRestoreHelper
|
|
236
|
+
from torchvision.transforms.functional import normalize as tv_normalize
|
|
237
|
+
except ImportError:
|
|
238
|
+
return image
|
|
239
|
+
|
|
240
|
+
try:
|
|
241
|
+
global _CODEFORMER_MODEL
|
|
242
|
+
from codeformer.basicsr.archs.codeformer_arch import CodeFormer as CodeFormerArch
|
|
243
|
+
from codeformer.inference_codeformer import set_realesrgan as _unused # noqa: F401
|
|
244
|
+
|
|
245
|
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
246
|
+
|
|
247
|
+
if _CODEFORMER_MODEL is None:
|
|
248
|
+
model = CodeFormerArch(
|
|
249
|
+
dim_embd=512,
|
|
250
|
+
codebook_size=1024,
|
|
251
|
+
n_head=8,
|
|
252
|
+
n_layers=9,
|
|
253
|
+
connect_list=["32", "64", "128", "256"],
|
|
254
|
+
).to(device)
|
|
255
|
+
|
|
256
|
+
ckpt_path = load_file_from_url(
|
|
257
|
+
url="https://github.com/sczhou/CodeFormer/releases/download/v0.1.0/codeformer.pth",
|
|
258
|
+
model_dir="weights/CodeFormer",
|
|
259
|
+
progress=True,
|
|
260
|
+
)
|
|
261
|
+
checkpoint = torch.load(ckpt_path, map_location=device, weights_only=True)
|
|
262
|
+
model.load_state_dict(checkpoint["params_ema"])
|
|
263
|
+
model.eval()
|
|
264
|
+
_CODEFORMER_MODEL = model
|
|
265
|
+
model = _CODEFORMER_MODEL
|
|
266
|
+
|
|
267
|
+
face_helper = FaceRestoreHelper(
|
|
268
|
+
upscale,
|
|
269
|
+
face_size=512,
|
|
270
|
+
crop_ratio=(1, 1),
|
|
271
|
+
det_model="retinaface_resnet50",
|
|
272
|
+
save_ext="png",
|
|
273
|
+
device=device,
|
|
274
|
+
)
|
|
275
|
+
face_helper.read_image(image)
|
|
276
|
+
face_helper.get_face_landmarks_5(only_center_face=True)
|
|
277
|
+
face_helper.align_warp_face()
|
|
278
|
+
|
|
279
|
+
for cropped_face in face_helper.cropped_faces:
|
|
280
|
+
face_t = img2tensor(cropped_face / 255.0, bgr2rgb=True, float32=True)
|
|
281
|
+
tv_normalize(face_t, (0.5, 0.5, 0.5), (0.5, 0.5, 0.5), inplace=True)
|
|
282
|
+
face_t = face_t.unsqueeze(0).to(device)
|
|
283
|
+
|
|
284
|
+
with torch.no_grad():
|
|
285
|
+
output = model(face_t, w=fidelity, adain=True)[0]
|
|
286
|
+
restored = tensor2img(output, rgb2bgr=True, min_max=(-1, 1))
|
|
287
|
+
restored = restored.astype(np.uint8)
|
|
288
|
+
face_helper.add_restored_face(restored)
|
|
289
|
+
|
|
290
|
+
face_helper.get_inverse_affine(None)
|
|
291
|
+
restored_img = face_helper.paste_faces_to_image()
|
|
292
|
+
if restored_img is not None:
|
|
293
|
+
return restored_img
|
|
294
|
+
except Exception:
|
|
295
|
+
pass
|
|
296
|
+
|
|
297
|
+
return image
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def enhance_background_realesrgan(
|
|
301
|
+
image: np.ndarray,
|
|
302
|
+
mask: np.ndarray,
|
|
303
|
+
outscale: int = 2,
|
|
304
|
+
) -> np.ndarray:
|
|
305
|
+
"""Enhance non-face background regions using Real-ESRGAN neural upscaler.
|
|
306
|
+
|
|
307
|
+
Only applies to regions outside the surgical mask to improve overall
|
|
308
|
+
image quality without interfering with the face restoration pipeline.
|
|
309
|
+
|
|
310
|
+
Args:
|
|
311
|
+
image: BGR image.
|
|
312
|
+
mask: Float32 mask [0-1] where 1 = face region (skip these pixels).
|
|
313
|
+
outscale: Upscale factor (2 = 2x resolution, then downsample back).
|
|
314
|
+
|
|
315
|
+
Returns:
|
|
316
|
+
Enhanced BGR image at original resolution.
|
|
317
|
+
"""
|
|
318
|
+
try:
|
|
319
|
+
import torch
|
|
320
|
+
from basicsr.archs.rrdbnet_arch import RRDBNet
|
|
321
|
+
from realesrgan import RealESRGANer
|
|
322
|
+
except ImportError:
|
|
323
|
+
return image
|
|
324
|
+
|
|
325
|
+
try:
|
|
326
|
+
global _REALESRGAN_UPSAMPLER
|
|
327
|
+
if _REALESRGAN_UPSAMPLER is None:
|
|
328
|
+
model = RRDBNet(
|
|
329
|
+
num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=4
|
|
330
|
+
)
|
|
331
|
+
_REALESRGAN_UPSAMPLER = RealESRGANer(
|
|
332
|
+
scale=4,
|
|
333
|
+
model_path="https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
|
|
334
|
+
model=model,
|
|
335
|
+
tile=400,
|
|
336
|
+
tile_pad=10,
|
|
337
|
+
pre_pad=0,
|
|
338
|
+
half=torch.cuda.is_available(),
|
|
339
|
+
)
|
|
340
|
+
enhanced, _ = _REALESRGAN_UPSAMPLER.enhance(image, outscale=outscale)
|
|
341
|
+
|
|
342
|
+
# Downscale back to original size
|
|
343
|
+
h, w = image.shape[:2]
|
|
344
|
+
enhanced = cv2.resize(enhanced, (w, h), interpolation=cv2.INTER_LANCZOS4)
|
|
345
|
+
|
|
346
|
+
# Only apply enhancement to background (outside mask)
|
|
347
|
+
mask_f = mask.astype(np.float32)
|
|
348
|
+
if mask_f.max() > 1.0:
|
|
349
|
+
mask_f /= 255.0
|
|
350
|
+
mask_3ch = np.stack([mask_f] * 3, axis=-1) if mask_f.ndim == 2 else mask_f
|
|
351
|
+
|
|
352
|
+
# Keep face region from original, use enhanced for background
|
|
353
|
+
result = np.clip(
|
|
354
|
+
image.astype(np.float32) * mask_3ch + enhanced.astype(np.float32) * (1.0 - mask_3ch),
|
|
355
|
+
0,
|
|
356
|
+
255,
|
|
357
|
+
).astype(np.uint8)
|
|
358
|
+
return result
|
|
359
|
+
except Exception:
|
|
360
|
+
pass
|
|
361
|
+
|
|
362
|
+
return image
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def verify_identity_arcface(
|
|
366
|
+
original: np.ndarray,
|
|
367
|
+
result: np.ndarray,
|
|
368
|
+
threshold: float = 0.6,
|
|
369
|
+
) -> dict:
|
|
370
|
+
"""Verify output preserves input identity using ArcFace neural net.
|
|
371
|
+
|
|
372
|
+
Computes cosine similarity between ArcFace embeddings of the original
|
|
373
|
+
and result images. If similarity drops below threshold, flags identity
|
|
374
|
+
drift — meaning the postprocessing or diffusion altered the person's
|
|
375
|
+
appearance too much.
|
|
376
|
+
|
|
377
|
+
Args:
|
|
378
|
+
original: BGR original face image.
|
|
379
|
+
result: BGR post-processed output image.
|
|
380
|
+
threshold: Minimum cosine similarity to pass (0.6 = same person).
|
|
381
|
+
|
|
382
|
+
Returns:
|
|
383
|
+
Dict with 'similarity' (float), 'passed' (bool), 'message' (str).
|
|
384
|
+
"""
|
|
385
|
+
try:
|
|
386
|
+
from insightface.app import FaceAnalysis
|
|
387
|
+
except ImportError:
|
|
388
|
+
return {
|
|
389
|
+
"similarity": -1.0,
|
|
390
|
+
"passed": True,
|
|
391
|
+
"message": "InsightFace not installed — identity check skipped",
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
try:
|
|
395
|
+
global _ARCFACE_APP
|
|
396
|
+
if _ARCFACE_APP is None:
|
|
397
|
+
_ARCFACE_APP = FaceAnalysis(
|
|
398
|
+
name="buffalo_l",
|
|
399
|
+
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
|
|
400
|
+
)
|
|
401
|
+
_ARCFACE_APP.prepare(ctx_id=0 if _has_cuda() else -1, det_size=(320, 320))
|
|
402
|
+
app = _ARCFACE_APP
|
|
403
|
+
|
|
404
|
+
orig_faces = app.get(original)
|
|
405
|
+
result_faces = app.get(result)
|
|
406
|
+
|
|
407
|
+
if not orig_faces or not result_faces:
|
|
408
|
+
return {
|
|
409
|
+
"similarity": -1.0,
|
|
410
|
+
"passed": True,
|
|
411
|
+
"message": "Could not detect face in one/both images — check skipped",
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
orig_emb = orig_faces[0].embedding
|
|
415
|
+
result_emb = result_faces[0].embedding
|
|
416
|
+
|
|
417
|
+
sim = float(
|
|
418
|
+
np.dot(orig_emb, result_emb)
|
|
419
|
+
/ (np.linalg.norm(orig_emb) * np.linalg.norm(result_emb) + 1e-8)
|
|
420
|
+
)
|
|
421
|
+
sim = float(np.clip(sim, 0, 1))
|
|
422
|
+
|
|
423
|
+
passed = sim >= threshold
|
|
424
|
+
if passed:
|
|
425
|
+
msg = f"Identity preserved (similarity={sim:.3f})"
|
|
426
|
+
else:
|
|
427
|
+
msg = f"WARNING: Identity drift detected (similarity={sim:.3f} < {threshold})"
|
|
428
|
+
|
|
429
|
+
return {"similarity": sim, "passed": passed, "message": msg}
|
|
430
|
+
except Exception as e:
|
|
431
|
+
return {
|
|
432
|
+
"similarity": -1.0,
|
|
433
|
+
"passed": True,
|
|
434
|
+
"message": f"Identity check failed: {e}",
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
|
|
438
|
+
def _has_cuda() -> bool:
|
|
439
|
+
try:
|
|
440
|
+
import torch
|
|
441
|
+
|
|
442
|
+
return torch.cuda.is_available()
|
|
443
|
+
except ImportError:
|
|
444
|
+
return False
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def histogram_match_skin(
|
|
448
|
+
source: np.ndarray,
|
|
449
|
+
reference: np.ndarray,
|
|
450
|
+
mask: np.ndarray,
|
|
451
|
+
) -> np.ndarray:
|
|
452
|
+
"""Match skin color histogram of source to reference within masked region.
|
|
453
|
+
|
|
454
|
+
More robust than simple mean/std matching — preserves the full
|
|
455
|
+
distribution of skin tones including highlights and shadows.
|
|
456
|
+
|
|
457
|
+
Args:
|
|
458
|
+
source: BGR image whose skin tone to adjust.
|
|
459
|
+
reference: BGR image with target skin tone.
|
|
460
|
+
mask: Float32 mask [0-1] of skin region.
|
|
461
|
+
|
|
462
|
+
Returns:
|
|
463
|
+
Color-matched BGR image.
|
|
464
|
+
"""
|
|
465
|
+
# Ensure 2D mask for per-channel indexing
|
|
466
|
+
m = mask
|
|
467
|
+
if m.ndim == 3:
|
|
468
|
+
m = m[:, :, 0]
|
|
469
|
+
mask_bool = m > 0.3 if m.dtype == np.float32 else m > 76
|
|
470
|
+
|
|
471
|
+
if not np.any(mask_bool):
|
|
472
|
+
return source
|
|
473
|
+
|
|
474
|
+
src_lab = cv2.cvtColor(source, cv2.COLOR_BGR2LAB).astype(np.float32)
|
|
475
|
+
ref_lab = cv2.cvtColor(reference, cv2.COLOR_BGR2LAB).astype(np.float32)
|
|
476
|
+
|
|
477
|
+
for ch in range(3):
|
|
478
|
+
src_vals = src_lab[:, :, ch][mask_bool]
|
|
479
|
+
ref_vals = ref_lab[:, :, ch][mask_bool]
|
|
480
|
+
|
|
481
|
+
if len(src_vals) == 0 or len(ref_vals) == 0:
|
|
482
|
+
continue
|
|
483
|
+
|
|
484
|
+
# CDF matching
|
|
485
|
+
src_sorted = np.sort(src_vals)
|
|
486
|
+
ref_sorted = np.sort(ref_vals)
|
|
487
|
+
|
|
488
|
+
# Interpolate reference CDF to match source length
|
|
489
|
+
src_cdf = np.linspace(0, 1, len(src_sorted))
|
|
490
|
+
ref_cdf = np.linspace(0, 1, len(ref_sorted))
|
|
491
|
+
|
|
492
|
+
# Map source values through reference distribution
|
|
493
|
+
mapping = np.interp(src_cdf, ref_cdf, ref_sorted)
|
|
494
|
+
|
|
495
|
+
# Create lookup from source intensity to matched intensity
|
|
496
|
+
src_flat = src_lab[:, :, ch].ravel()
|
|
497
|
+
matched = np.interp(src_flat, src_sorted, mapping)
|
|
498
|
+
matched_2d = matched.reshape(src_lab.shape[:2])
|
|
499
|
+
|
|
500
|
+
# Apply only in mask region
|
|
501
|
+
src_lab[:, :, ch] = np.where(mask_bool, matched_2d, src_lab[:, :, ch])
|
|
502
|
+
|
|
503
|
+
result_lab = np.clip(src_lab, 0, 255).astype(np.uint8)
|
|
504
|
+
return cv2.cvtColor(result_lab, cv2.COLOR_LAB2BGR)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def full_postprocess(
|
|
508
|
+
generated: np.ndarray,
|
|
509
|
+
original: np.ndarray,
|
|
510
|
+
mask: np.ndarray,
|
|
511
|
+
restore_mode: str = "codeformer",
|
|
512
|
+
codeformer_fidelity: float = 0.7,
|
|
513
|
+
use_realesrgan: bool = True,
|
|
514
|
+
use_laplacian_blend: bool = True,
|
|
515
|
+
sharpen_strength: float = 0.25,
|
|
516
|
+
verify_identity: bool = True,
|
|
517
|
+
identity_threshold: float = 0.6,
|
|
518
|
+
) -> dict:
|
|
519
|
+
"""Full neural net + classical post-processing pipeline for maximum photorealism.
|
|
520
|
+
|
|
521
|
+
Pipeline:
|
|
522
|
+
1. Face restoration: CodeFormer (primary) or GFPGAN (fallback) neural nets
|
|
523
|
+
2. Background enhancement: Real-ESRGAN neural upscaler (non-face regions)
|
|
524
|
+
3. Skin tone histogram matching to original (classical)
|
|
525
|
+
4. Frequency-aware sharpening for texture recovery (classical)
|
|
526
|
+
5. Laplacian pyramid blending for seamless compositing (classical)
|
|
527
|
+
6. ArcFace identity verification (neural net quality gate)
|
|
528
|
+
|
|
529
|
+
Args:
|
|
530
|
+
generated: BGR generated/warped face image.
|
|
531
|
+
original: BGR original face image.
|
|
532
|
+
mask: Float32 surgical mask [0-1].
|
|
533
|
+
restore_mode: 'codeformer', 'gfpgan', or 'none'.
|
|
534
|
+
codeformer_fidelity: CodeFormer fidelity weight (0=quality, 1=fidelity).
|
|
535
|
+
use_realesrgan: Apply Real-ESRGAN to background regions.
|
|
536
|
+
use_laplacian_blend: Use Laplacian blend vs simple alpha blend.
|
|
537
|
+
sharpen_strength: Texture sharpening amount (0 = none).
|
|
538
|
+
verify_identity: Run ArcFace identity check at the end.
|
|
539
|
+
identity_threshold: Min cosine similarity to pass identity check.
|
|
540
|
+
|
|
541
|
+
Returns:
|
|
542
|
+
Dict with 'image' (composited BGR), 'identity_check' (dict), 'restore_used' (str).
|
|
543
|
+
"""
|
|
544
|
+
result = generated.copy()
|
|
545
|
+
restore_used = "none"
|
|
546
|
+
|
|
547
|
+
# Step 1: Neural face restoration (CodeFormer > GFPGAN > skip)
|
|
548
|
+
if restore_mode == "codeformer":
|
|
549
|
+
restored = restore_face_codeformer(result, fidelity=codeformer_fidelity)
|
|
550
|
+
if restored is not result:
|
|
551
|
+
result = restored
|
|
552
|
+
restore_used = "codeformer"
|
|
553
|
+
else:
|
|
554
|
+
# CodeFormer unavailable, fall back to GFPGAN
|
|
555
|
+
pre_gfpgan = result
|
|
556
|
+
result = restore_face_gfpgan(result)
|
|
557
|
+
restore_used = "gfpgan" if result is not pre_gfpgan else "none"
|
|
558
|
+
elif restore_mode == "gfpgan":
|
|
559
|
+
restored = restore_face_gfpgan(result)
|
|
560
|
+
if restored is not result:
|
|
561
|
+
result = restored
|
|
562
|
+
restore_used = "gfpgan"
|
|
563
|
+
|
|
564
|
+
# Step 2: Neural background enhancement
|
|
565
|
+
if use_realesrgan:
|
|
566
|
+
result = enhance_background_realesrgan(result, mask)
|
|
567
|
+
|
|
568
|
+
# Step 3: Skin tone histogram matching (classical)
|
|
569
|
+
result = histogram_match_skin(result, original, mask)
|
|
570
|
+
|
|
571
|
+
# Step 4: Sharpen texture (classical)
|
|
572
|
+
if sharpen_strength > 0:
|
|
573
|
+
result = frequency_aware_sharpen(result, strength=sharpen_strength)
|
|
574
|
+
|
|
575
|
+
# Step 5: Blend into original (classical)
|
|
576
|
+
if use_laplacian_blend:
|
|
577
|
+
composited = laplacian_pyramid_blend(result, original, mask)
|
|
578
|
+
else:
|
|
579
|
+
mask_f = mask.astype(np.float32)
|
|
580
|
+
if mask_f.max() > 1.0:
|
|
581
|
+
mask_f /= 255.0
|
|
582
|
+
mask_3ch = np.stack([mask_f] * 3, axis=-1) if mask_f.ndim == 2 else mask_f
|
|
583
|
+
composited = (
|
|
584
|
+
result.astype(np.float32) * mask_3ch + original.astype(np.float32) * (1.0 - mask_3ch)
|
|
585
|
+
).astype(np.uint8)
|
|
586
|
+
|
|
587
|
+
# Step 6: Neural identity verification
|
|
588
|
+
identity_check = {"similarity": -1.0, "passed": True, "message": "skipped"}
|
|
589
|
+
if verify_identity:
|
|
590
|
+
identity_check = verify_identity_arcface(
|
|
591
|
+
original,
|
|
592
|
+
composited,
|
|
593
|
+
threshold=identity_threshold,
|
|
594
|
+
)
|
|
595
|
+
|
|
596
|
+
return {
|
|
597
|
+
"image": composited,
|
|
598
|
+
"identity_check": identity_check,
|
|
599
|
+
"restore_used": restore_used,
|
|
600
|
+
}
|
landmarkdiff/py.typed
ADDED
|
File without changes
|