vitordigitizing commited on
Commit
b9ec882
·
verified ·
1 Parent(s): ef60c6c

Update faceless_processing.py

Browse files
Files changed (1) hide show
  1. faceless_processing.py +123 -281
faceless_processing.py CHANGED
@@ -10,13 +10,6 @@ import urllib.request
10
  from rembg import remove, new_session
11
  import threading
12
 
13
- try:
14
- from scipy.interpolate import splprep, splev
15
- _SCIPY_AVAILABLE = True
16
- except ImportError:
17
- _SCIPY_AVAILABLE = False
18
- print("[AI] scipy not available — falling back to approxPolyDP for silhouette smoothing")
19
-
20
  try:
21
  _SESSION_ISNET = new_session("isnet-general-use")
22
  except Exception as e:
@@ -75,68 +68,42 @@ class LineartConfig:
75
  transparency_threshold: float = 0.03
76
  detect_eyebrows: bool = True
77
 
 
78
  # Subject mask
79
- white_bg_threshold: int = 245
80
  mask_close_iterations: int = 4
81
  mask_open_iterations: int = 1
82
- mask_smooth_ksize: int = 5
83
- mask_smooth_threshold: int = 128
84
- min_silhouette_area: float = 200.0
85
 
86
- # Silhouette outline — thicker for embroidery visibility
87
- silhouette_line_thickness: int = 4 # bold outer contour
88
 
89
- # Edge detection — single pass, balanced for body/clothing details
90
- canny_low: int = 40 # slight lower to recover chin/jaw line
91
- canny_high: int = 130
92
  bilateral_d: int = 11
93
- bilateral_sigma_color: int = 110
94
- bilateral_sigma_space: int = 110
95
- gaussian_ksize: int = 11
96
- min_contour_perimeter: float = 65.0
97
- interior_line_thickness: int = 3
98
-
99
- # Secondary detail pass — keep OFF
100
- enable_detail_pass: bool = False
101
- detail_canny_low: int = 15
102
- detail_canny_high: int = 55
103
- detail_gaussian_ksize: int = 5
104
- detail_min_perimeter: float = 30.0
105
- detail_bilateral_d: int = 7
106
- detail_bilateral_sigma: int = 60
107
-
108
- # Embroidery stitch feasibility
109
- min_embroidery_stitch_px: int = 25
110
 
111
  # Face detection
112
  face_scale_factor: float = 1.05
113
  face_min_neighbors: int = 3
114
- face_min_size: Tuple[int, int] = (20, 20)
115
- face_max_y_ratio: float = 0.65
116
- face_nms_iou_thresh: float = 0.35
117
- face_max_count: int = 6
118
-
119
- # Face erase ellipse — covers ONLY eyes/nose/mouth zone.
120
- # Face bbox from OpenCV Haar cascade (forehead=0% → chin=100%):
121
- # Eyebrows: ~20–30% ← must NOT be erased
122
- # Eyes: ~30–40%
123
- # Nose: ~45–60%
124
- # Mouth: ~60–70%
125
- # Chin: ~80–100% ← must NOT be erased
126
- # cy=0.46, ry=0.19 → erases from 27% to 65% → eyebrows above, chin below.
127
- face_cx_ratio: float = 0.50
128
- face_cy_ratio: float = 0.46 # center = eye-to-mouth midpoint
129
- face_rx_ratio: float = 0.27 # moderate width
130
- face_ry_ratio: float = 0.19 # short: 46-19=27% top, 46+19=65% bottom
131
- face_erase_blur: int = 5 # tight blur → won't spill onto eyebrows/chin
132
- face_erase_threshold: int = 90 # lower → harder edge
133
-
134
- # MediaPipe face landmarker: max faces
135
- mediapipe_num_faces: int = 6
136
-
137
- # Eyebrow drawing — thick and bold for embroidery visibility
138
- eyebrow_thickness: int = 5 # thick stroke
139
- eyebrow_dilate: int = 2 # extra dilation for bolder lines
140
 
141
 
142
  def _nms_faces(faces: list, iou_thresh: float) -> list:
@@ -163,15 +130,13 @@ def _nms_faces(faces: list, iou_thresh: float) -> list:
163
 
164
 
165
  def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
166
- """Detect up to cfg.face_max_count faces using dual Haar cascade + CLAHE preprocessing."""
167
  h = rgb.shape[0]
168
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
169
- # CLAHE equalisation improves detection on uneven lighting / dark photos
170
- clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
171
- gray_eq = clahe.apply(gray)
172
  faces = []
173
 
174
  try:
 
175
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
176
  path_default = os.path.join(cascade_dir, 'haarcascade_frontalface_default.xml')
177
  path_alt = os.path.join(cascade_dir, 'haarcascade_frontalface_alt2.xml')
@@ -182,6 +147,7 @@ def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
182
  if os.path.exists(path_alt):
183
  classifiers.append(cv2.CascadeClassifier(path_alt))
184
 
 
185
  if not classifiers or all(c.empty() for c in classifiers):
186
  classifiers = [
187
  cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'),
@@ -190,16 +156,14 @@ def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
190
 
191
  for cascade in classifiers:
192
  if cascade and not cascade.empty():
193
- # Run on both raw and CLAHE-equalised gray for better recall
194
- for img_gray in [gray, gray_eq]:
195
- detected = cascade.detectMultiScale(
196
- img_gray,
197
- scaleFactor=cfg.face_scale_factor,
198
- minNeighbors=cfg.face_min_neighbors,
199
- minSize=cfg.face_min_size
200
- )
201
- if len(detected) > 0:
202
- faces.extend(detected.tolist())
203
  except Exception as e:
204
  print(f"[AI] Face detection failed or cascades unavailable: {e}")
205
 
@@ -208,13 +172,6 @@ def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
208
 
209
  # Remove duplicates
210
  faces = _nms_faces(faces, cfg.face_nms_iou_thresh)
211
-
212
- # Enforce maximum face count
213
- max_faces = getattr(cfg, 'face_max_count', 6)
214
- if len(faces) > max_faces:
215
- # Keep the largest faces (most prominent)
216
- faces = sorted(faces, key=lambda f: f[2] * f[3], reverse=True)[:max_faces]
217
-
218
  return faces
219
 
220
 
@@ -232,73 +189,28 @@ def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optio
232
  return mask
233
 
234
 
235
- def _smooth_contour_spline(cnt: np.ndarray, n_points: int = 400) -> Optional[np.ndarray]:
236
- """
237
- Fit a periodic B-spline through contour points and resample at n_points.
238
- Returns a smooth (N,1,2) array ready for cv2.drawContours/polylines,
239
- or None if spline fitting fails (e.g. too few points).
240
- """
241
- if not _SCIPY_AVAILABLE:
242
- return None
243
- pts = cnt[:, 0, :] # (N, 2) array of (x, y)
244
- if len(pts) < 4:
245
- return None
246
- try:
247
- # smoothing factor s=0 = interpolating spline (passes through all points)
248
- # per=True = closed/periodic curve
249
- tck, _ = splprep([pts[:, 0].astype(float), pts[:, 1].astype(float)],
250
- s=len(pts) * 0.5, per=True, quiet=True)
251
- u_new = np.linspace(0, 1, n_points)
252
- x_new, y_new = splev(u_new, tck)
253
- spline_pts = np.stack([x_new, y_new], axis=1).astype(np.int32)
254
- return spline_pts.reshape((-1, 1, 2))
255
- except Exception:
256
- return None
257
-
258
-
259
  def build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
260
- """
261
- Draw the subject silhouette as a smooth, anti-aliased contour.
262
- Uses scipy B-spline smoothing when available (far smoother than approxPolyDP).
263
- Falls back to tiny-epsilon approxPolyDP + LINE_AA if scipy is missing.
264
- """
265
  mask = subject_mask.copy()
266
 
267
- # 1. Large Gaussian blur + re-threshold to eliminate staircase jaggies on mask edge
268
  if cfg.mask_smooth_ksize > 1:
269
- k = max(21, cfg.mask_smooth_ksize if cfg.mask_smooth_ksize % 2 == 1 else cfg.mask_smooth_ksize + 1)
 
270
  mask = cv2.GaussianBlur(mask, (k, k), 0)
271
  _, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)
272
 
273
- # 2. Extra morphological close to fill small notches on the boundary
274
- k_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))
275
- mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k_close, iterations=2)
276
-
277
- contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
278
  silhouette = np.zeros_like(subject_mask)
279
-
280
  for cnt in contours:
281
- if cv2.contourArea(cnt) < cfg.min_silhouette_area:
282
- continue
283
-
284
- # Try scipy B-spline first for organically smooth curves
285
- smooth = _smooth_contour_spline(cnt)
286
- if smooth is not None:
287
- cv2.polylines(silhouette, [smooth], isClosed=True,
288
- color=255, thickness=cfg.silhouette_line_thickness,
289
- lineType=cv2.LINE_AA)
290
- else:
291
- # Fallback: very small epsilon so approxPolyDP barely simplifies
292
- eps = 0.0003 * cv2.arcLength(cnt, True)
293
- approx = cv2.approxPolyDP(cnt, eps, True)
294
- cv2.drawContours(silhouette, [approx], -1, 255,
295
- cfg.silhouette_line_thickness, lineType=cv2.LINE_AA)
296
-
297
  return silhouette
298
 
299
 
300
-
301
-
302
  def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfig) -> np.ndarray:
303
  """Build a soft binary mask covering face interior regions."""
304
  h, w = shape
@@ -314,38 +226,13 @@ def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfi
314
 
315
 
316
  def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
317
- """
318
- Detect structural body lines using a two-pass Canny strategy:
319
- - Primary pass: standard parameters for prominent structural lines
320
- - Detail pass (optional): more sensitive params to capture fine features
321
- (hair texture, fabric folds, accessories) that would still be stitchable
322
- Lines too short to translate to embroidery stitches are discarded.
323
- """
324
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
325
-
326
- # --- Primary pass ---
327
- blurred_primary = cv2.bilateralFilter(gray, cfg.bilateral_d, cfg.bilateral_sigma_color, cfg.bilateral_sigma_space)
328
- blurred_primary = cv2.GaussianBlur(blurred_primary, (cfg.gaussian_ksize, cfg.gaussian_ksize), 0)
329
- edges_primary = cv2.Canny(blurred_primary, cfg.canny_low, cfg.canny_high)
330
-
331
- # --- Detail pass (fine features) ---
332
- edges_detail = np.zeros_like(edges_primary)
333
- if getattr(cfg, 'enable_detail_pass', True):
334
- detail_d = getattr(cfg, 'detail_bilateral_d', 7)
335
- detail_sigma = getattr(cfg, 'detail_bilateral_sigma', 60)
336
- detail_ksize = getattr(cfg, 'detail_gaussian_ksize', 5)
337
- blurred_detail = cv2.bilateralFilter(gray, detail_d, detail_sigma, detail_sigma)
338
- blurred_detail = cv2.GaussianBlur(blurred_detail, (detail_ksize, detail_ksize), 0)
339
- edges_detail = cv2.Canny(
340
- blurred_detail,
341
- getattr(cfg, 'detail_canny_low', 15),
342
- getattr(cfg, 'detail_canny_high', 55)
343
- )
344
-
345
- # Combine both passes
346
- edges = cv2.bitwise_or(edges_primary, edges_detail)
347
-
348
- # Erode subject mask to avoid catching the outer boundary twice
349
  erode_size = max(5, cfg.silhouette_line_thickness * 2 + 3)
350
  if erode_size % 2 == 0:
351
  erode_size += 1
@@ -353,23 +240,16 @@ def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: Lineart
353
  eroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)
354
  edges = cv2.bitwise_and(edges, eroded_mask)
355
 
356
- # Filter contours: remove noise and lines too short to be embroidered
357
- min_perimeter = cfg.min_contour_perimeter
358
- min_stitch = getattr(cfg, 'min_embroidery_stitch_px', 15)
359
  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
360
  filtered = np.zeros_like(edges)
361
  for cnt in contours:
362
  perimeter = cv2.arcLength(cnt, False)
363
- # Skip contours that are too short for embroidery
364
- if perimeter < min_perimeter:
365
- continue
366
- # Additional embroidery feasibility check (absolute pixel length)
367
- if min_stitch > 0 and perimeter < min_stitch:
368
- continue
369
- # Smooth contour to reduce Canny wobbles while preserving natural flow
370
- eps = 0.0012 * perimeter
371
- smooth = cv2.approxPolyDP(cnt, eps, False)
372
- cv2.drawContours(filtered, [smooth], -1, 255, cfg.interior_line_thickness)
373
 
374
  # Mild dilation for uniform, solid strokes
375
  kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
@@ -379,12 +259,10 @@ def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: Lineart
379
 
380
  _LANDMARKER_LOCK = threading.Lock()
381
  _LANDMARKER_CACHE = None
382
- _LANDMARKER_NUM_FACES = None
383
 
384
- def get_landmarker(model_path, num_faces: int = 6):
385
- global _LANDMARKER_CACHE, _LANDMARKER_NUM_FACES
386
- # Re-create if num_faces changed
387
- if _LANDMARKER_CACHE is None or _LANDMARKER_NUM_FACES != num_faces:
388
  import mediapipe as mp
389
  from mediapipe.tasks import python
390
  from mediapipe.tasks.python import vision
@@ -394,22 +272,14 @@ def get_landmarker(model_path, num_faces: int = 6):
394
  base_options=base_options,
395
  output_face_blendshapes=False,
396
  output_facial_transformation_matrixes=False,
397
- num_faces=num_faces
398
  )
399
  _LANDMARKER_CACHE = vision.FaceLandmarker.create_from_options(options)
400
- _LANDMARKER_NUM_FACES = num_faces
401
  return _LANDMARKER_CACHE
402
 
403
 
404
  def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = None) -> np.ndarray:
405
- """
406
- Detect and draw eyebrows using MediaPipe FaceLandmarker.
407
- Strategy:
408
- Phase 1 — global detection on the full image (catches upright faces).
409
- Phase 2 — per-face crops (catches tilted / partially occluded faces that
410
- the global pass misses).
411
- Deduplication uses pixel-space distance to avoid double-drawing same face.
412
- """
413
  h, w, _ = rgb.shape
414
  eyebrows_layer = np.zeros((h, w), dtype=np.uint8)
415
 
@@ -418,7 +288,7 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
418
  from mediapipe.tasks import python
419
  from mediapipe.tasks.python import vision
420
 
421
- # Resolve model path
422
  model_path = cfg.mediapipe_model_path
423
  if not model_path or not os.path.exists(model_path):
424
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
@@ -430,114 +300,86 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
430
  urllib.request.urlretrieve(model_url, model_path)
431
  print("[AI] Download complete!")
432
 
433
- # Landmark indices for full eyebrow arcs (upper + lower boundary)
434
- LEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]
435
  RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276]
 
 
 
436
 
437
- eyebrow_thickness = getattr(cfg, 'eyebrow_thickness', cfg.interior_line_thickness)
438
- eyebrow_dilate = getattr(cfg, 'eyebrow_dilate', 1)
439
-
440
- # Deduplication in pixel space (avoids normalised-coord mismatches)
441
- drawn_centers_px: list = [] # list of (cx_px, cy_px)
442
-
443
- def is_duplicate_px(cx_px: float, cy_px: float) -> bool:
444
- min_dist = min(w, h) * 0.06 # 6% of shortest side
445
- for (pcx, pcy) in drawn_centers_px:
446
- if np.hypot(cx_px - pcx, cy_px - pcy) < min_dist:
447
  return True
448
  return False
449
 
450
- def draw_eyebrow_landmarks(face_lms, origin_x: int, origin_y: int,
451
- scale_x: float, scale_y: float):
452
- """Map landmark coords back to full-image pixels and draw."""
453
- for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:
454
- pts = []
455
- for idx in indices:
456
- lm = face_lms[idx]
457
- px = int(origin_x + lm.x * scale_x)
458
- py = int(origin_y + lm.y * scale_y)
459
- pts.append([px, py])
460
- pts_np = np.array(pts, np.int32).reshape((-1, 1, 2))
461
- cv2.polylines(eyebrows_layer, [pts_np],
462
- isClosed=False, color=255,
463
- thickness=eyebrow_thickness,
464
- lineType=cv2.LINE_AA)
465
-
466
  if faces is None:
467
  faces = detect_faces(rgb, cfg)
468
 
469
  with _LANDMARKER_LOCK:
470
- num_faces = getattr(cfg, 'mediapipe_num_faces', 6)
471
- landmarker = get_landmarker(model_path, num_faces=num_faces)
472
-
473
- # ── Phase 1: full-image detection ──────────────────────────────
474
  mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
475
  global_result = landmarker.detect(mp_image)
476
  if global_result.face_landmarks:
477
- for face_lms in global_result.face_landmarks:
478
- # Face centre in pixel coords
479
- cx_px = np.mean([lm.x for lm in face_lms]) * w
480
- cy_px = np.mean([lm.y for lm in face_lms]) * h
481
- if not is_duplicate_px(cx_px, cy_px):
482
- drawn_centers_px.append((cx_px, cy_px))
483
- draw_eyebrow_landmarks(face_lms,
484
- origin_x=0, origin_y=0,
485
- scale_x=w, scale_y=h)
486
-
487
- # ── Phase 2: per-face crop (tilted / small / occluded faces) ───
488
- for (fx, fy, fw, fh) in faces:
489
- # Generous 50% margin so MediaPipe sees face context
490
- mx = int(fw * 0.50)
491
- my = int(fh * 0.50)
492
- x1 = max(0, fx - mx); y1 = max(0, fy - my)
493
- x2 = min(w, fx + fw + mx); y2 = min(h, fy + fh + my)
494
- crop_w, crop_h = x2 - x1, y2 - y1
495
- if crop_w < 20 or crop_h < 20:
 
 
 
 
 
 
 
496
  continue
497
 
498
- # Face centre in full-image pixels
499
- face_cx_px = (x1 + x2) / 2
500
- face_cy_px = (y1 + y2) / 2
501
- if is_duplicate_px(face_cx_px, face_cy_px):
502
- continue # already drawn from Phase 1
503
 
504
  crop = rgb[y1:y2, x1:x2]
505
- # Upscale to at least 256px wide for better landmarker accuracy
506
- target = max(512, crop_w, crop_h)
507
- scale = target / max(crop_w, crop_h)
508
- cw_scaled = int(crop_w * scale)
509
- ch_scaled = int(crop_h * scale)
510
- crop_resized = cv2.resize(crop, (cw_scaled, ch_scaled), interpolation=cv2.INTER_CUBIC)
511
-
512
  crop_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=crop_resized)
513
  crop_result = landmarker.detect(crop_image)
514
 
515
  if crop_result.face_landmarks:
516
- face_lms = crop_result.face_landmarks[0]
517
- # Re-compute centre in full-image coords
518
- cx_px2 = x1 + np.mean([lm.x for lm in face_lms]) * crop_w
519
- cy_px2 = y1 + np.mean([lm.y for lm in face_lms]) * crop_h
520
- if is_duplicate_px(cx_px2, cy_px2):
521
- continue
522
- drawn_centers_px.append((cx_px2, cy_px2))
523
- # Scale back: landmark coords are relative to the scaled crop
524
- draw_eyebrow_landmarks(face_lms,
525
- origin_x=x1, origin_y=y1,
526
- scale_x=crop_w / cw_scaled * cw_scaled,
527
- scale_y=crop_h / ch_scaled * ch_scaled)
528
-
529
- print(f"[eyebrows] Drew eyebrows for {len(drawn_centers_px)} face(s)")
530
-
531
  except Exception as e:
532
  print(f"[AI] Eyebrow extraction error or library missing: {e}")
533
 
534
- # Dilate eyebrow strokes for bolder/more visible lines
535
- if eyebrows_layer.any():
536
- dil = getattr(cfg, 'eyebrow_dilate', 1)
537
- if dil > 0:
538
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
539
- eyebrows_layer = cv2.dilate(eyebrows_layer, kernel, iterations=dil)
540
-
541
  return eyebrows_layer
542
 
543
 
@@ -677,4 +519,4 @@ def build_faceless_embroidery_assets(
677
 
678
  lineart = make_faceless_lineart(img, cfg)
679
  cutout = make_faceless_cutout(img)
680
- return lineart, cutout
 
10
  from rembg import remove, new_session
11
  import threading
12
 
 
 
 
 
 
 
 
13
  try:
14
  _SESSION_ISNET = new_session("isnet-general-use")
15
  except Exception as e:
 
68
  transparency_threshold: float = 0.03
69
  detect_eyebrows: bool = True
70
 
71
+
72
  # Subject mask
73
+ white_bg_threshold: int = 245 # pixels above this = background (raised to avoid erasing light subjects)
74
  mask_close_iterations: int = 4
75
  mask_open_iterations: int = 1
76
+ mask_smooth_ksize: int = 5 # GaussianBlur kernel before silhouette (must be odd; 0 = disabled)
77
+ mask_smooth_threshold: int = 128 # re-binarize after blur
78
+ min_silhouette_area: float = 200.0 # drop tiny isolated blobs from the silhouette (px²)
79
 
80
+ # Silhouette outline
81
+ silhouette_line_thickness: int = 3 # outer contour stroke width (px); match interior for uniform look
82
 
83
+ # Edge detection
84
+ canny_low: int = 40
85
+ canny_high: int = 110
86
  bilateral_d: int = 11
87
+ bilateral_sigma_color: int = 80
88
+ bilateral_sigma_space: int = 80
89
+ gaussian_ksize: int = 9
90
+ min_contour_perimeter: float = 50.0 # filters out short noisy lines
91
+ interior_line_thickness: int = 3 # thickness of interior detail lines (>=1)
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
  # Face detection
94
  face_scale_factor: float = 1.05
95
  face_min_neighbors: int = 3
96
+ face_min_size: Tuple[int, int] = (25, 25)
97
+ face_max_y_ratio: float = 0.6 # ignore faces below 60% image height
98
+ face_nms_iou_thresh: float = 0.4
99
+
100
+ # Face erase ellipse (ratios relative to face bbox) — smaller = more conservative
101
+ face_cx_ratio: float = 0.5
102
+ face_cy_ratio: float = 0.45
103
+ face_rx_ratio: float = 0.35 # reduced from 0.40 to avoid erasing neck/ears
104
+ face_ry_ratio: float = 0.38 # reduced from 0.42 to avoid erasing chin/neck
105
+ face_erase_blur: int = 8
106
+ face_erase_threshold: int = 130 # higher = sharper face mask edge, less spill
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
 
109
  def _nms_faces(faces: list, iou_thresh: float) -> list:
 
130
 
131
 
132
  def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
133
+ """Detect faces and filter out false positives in lower body."""
134
  h = rgb.shape[0]
135
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
 
 
 
136
  faces = []
137
 
138
  try:
139
+ # Load local classifiers from downloaded folder
140
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
141
  path_default = os.path.join(cascade_dir, 'haarcascade_frontalface_default.xml')
142
  path_alt = os.path.join(cascade_dir, 'haarcascade_frontalface_alt2.xml')
 
147
  if os.path.exists(path_alt):
148
  classifiers.append(cv2.CascadeClassifier(path_alt))
149
 
150
+ # Fallback to cv2 data directory if local files are missing
151
  if not classifiers or all(c.empty() for c in classifiers):
152
  classifiers = [
153
  cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'),
 
156
 
157
  for cascade in classifiers:
158
  if cascade and not cascade.empty():
159
+ detected = cascade.detectMultiScale(
160
+ gray,
161
+ scaleFactor=cfg.face_scale_factor,
162
+ minNeighbors=cfg.face_min_neighbors,
163
+ minSize=cfg.face_min_size
164
+ )
165
+ if len(detected) > 0:
166
+ faces.extend(detected.tolist())
 
 
167
  except Exception as e:
168
  print(f"[AI] Face detection failed or cascades unavailable: {e}")
169
 
 
172
 
173
  # Remove duplicates
174
  faces = _nms_faces(faces, cfg.face_nms_iou_thresh)
 
 
 
 
 
 
 
175
  return faces
176
 
177
 
 
189
  return mask
190
 
191
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
192
  def build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
193
+ """Draw the subject silhouette as a smooth, solid-stroke contour."""
 
 
 
 
194
  mask = subject_mask.copy()
195
 
196
+ # Smooth the mask boundary to eliminate staircase jaggies before tracing
197
  if cfg.mask_smooth_ksize > 1:
198
+ # Use a larger kernel (at least 15) for beautiful organic curves
199
+ k = max(15, cfg.mask_smooth_ksize if cfg.mask_smooth_ksize % 2 == 1 else cfg.mask_smooth_ksize + 1)
200
  mask = cv2.GaussianBlur(mask, (k, k), 0)
201
  _, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)
202
 
203
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)
 
 
 
 
204
  silhouette = np.zeros_like(subject_mask)
 
205
  for cnt in contours:
206
+ if cv2.contourArea(cnt) >= cfg.min_silhouette_area:
207
+ # Smooth contour slightly without polygonal blockiness
208
+ eps = 0.0012 * cv2.arcLength(cnt, True)
209
+ smooth = cv2.approxPolyDP(cnt, eps, True)
210
+ cv2.drawContours(silhouette, [smooth], -1, 255, cfg.silhouette_line_thickness)
 
 
 
 
 
 
 
 
 
 
 
211
  return silhouette
212
 
213
 
 
 
214
  def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfig) -> np.ndarray:
215
  """Build a soft binary mask covering face interior regions."""
216
  h, w = shape
 
226
 
227
 
228
  def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
229
+ """Detect structural body lines using Canny, filtering noise."""
 
 
 
 
 
 
230
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
231
+ blurred = cv2.GaussianBlur(gray, (cfg.gaussian_ksize, cfg.gaussian_ksize), 0)
232
+ blurred = cv2.bilateralFilter(blurred, cfg.bilateral_d, cfg.bilateral_sigma_color, cfg.bilateral_sigma_space)
233
+ edges = cv2.Canny(blurred, cfg.canny_low, cfg.canny_high)
234
+
235
+ # Erode the subject mask so Canny doesn't catch the outer boundary twice
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
236
  erode_size = max(5, cfg.silhouette_line_thickness * 2 + 3)
237
  if erode_size % 2 == 0:
238
  erode_size += 1
 
240
  eroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)
241
  edges = cv2.bitwise_and(edges, eroded_mask)
242
 
243
+ # Filter out short/noisy contours
 
 
244
  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
245
  filtered = np.zeros_like(edges)
246
  for cnt in contours:
247
  perimeter = cv2.arcLength(cnt, False)
248
+ if perimeter > cfg.min_contour_perimeter:
249
+ # Simplify interior edges slightly to remove Canny wobbles while keeping natural flow
250
+ eps = 0.0012 * perimeter
251
+ smooth = cv2.approxPolyDP(cnt, eps, False)
252
+ cv2.drawContours(filtered, [smooth], -1, 255, cfg.interior_line_thickness)
 
 
 
 
 
253
 
254
  # Mild dilation for uniform, solid strokes
255
  kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
 
259
 
260
  _LANDMARKER_LOCK = threading.Lock()
261
  _LANDMARKER_CACHE = None
 
262
 
263
+ def get_landmarker(model_path):
264
+ global _LANDMARKER_CACHE
265
+ if _LANDMARKER_CACHE is None:
 
266
  import mediapipe as mp
267
  from mediapipe.tasks import python
268
  from mediapipe.tasks.python import vision
 
272
  base_options=base_options,
273
  output_face_blendshapes=False,
274
  output_facial_transformation_matrixes=False,
275
+ num_faces=1
276
  )
277
  _LANDMARKER_CACHE = vision.FaceLandmarker.create_from_options(options)
 
278
  return _LANDMARKER_CACHE
279
 
280
 
281
  def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = None) -> np.ndarray:
282
+ """Detect and draw eyebrows landmarks using MediaPipe Task API with hybrid global + crop detection."""
 
 
 
 
 
 
 
283
  h, w, _ = rgb.shape
284
  eyebrows_layer = np.zeros((h, w), dtype=np.uint8)
285
 
 
288
  from mediapipe.tasks import python
289
  from mediapipe.tasks.python import vision
290
 
291
+ # Determine model path
292
  model_path = cfg.mediapipe_model_path
293
  if not model_path or not os.path.exists(model_path):
294
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
 
300
  urllib.request.urlretrieve(model_url, model_path)
301
  print("[AI] Download complete!")
302
 
303
+ LEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]
 
304
  RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276]
305
+
306
+ eyebrow_thickness = max(1, cfg.interior_line_thickness - 1)
307
+ processed_centers = []
308
 
309
+ def is_duplicate(cx, cy):
310
+ for (pcx, pcy) in processed_centers:
311
+ dist = np.sqrt((cx - pcx)**2 + (cy - pcy)**2)
312
+ if dist < 0.08:
 
 
 
 
 
 
313
  return True
314
  return False
315
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  if faces is None:
317
  faces = detect_faces(rgb, cfg)
318
 
319
  with _LANDMARKER_LOCK:
320
+ landmarker = get_landmarker(model_path)
321
+
322
+ # Phase 1: Global detection (upright / clear faces)
 
323
  mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
324
  global_result = landmarker.detect(mp_image)
325
  if global_result.face_landmarks:
326
+ for face_landmarks in global_result.face_landmarks:
327
+ xs = [lm.x for lm in face_landmarks]
328
+ ys = [lm.y for lm in face_landmarks]
329
+ cx, cy = np.mean(xs), np.mean(ys)
330
+ if not is_duplicate(cx, cy):
331
+ processed_centers.append((cx, cy))
332
+ for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:
333
+ points = []
334
+ for idx in indices:
335
+ lm = face_landmarks[idx]
336
+ points.append([int(lm.x * w), int(lm.y * h)])
337
+ pts = np.array(points, np.int32).reshape((-1, 1, 2))
338
+ cv2.polylines(eyebrows_layer, [pts], isClosed=False, color=255, thickness=eyebrow_thickness)
339
+
340
+ # Phase 2: OpenCV crops with 45% margin (for tilted / overlapping faces)
341
+ for i, (fx, fy, fw, fh) in enumerate(faces):
342
+ margin_x = int(fw * 0.45)
343
+ margin_y = int(fh * 0.45)
344
+ x1 = max(0, fx - margin_x)
345
+ y1 = max(0, fy - margin_y)
346
+ x2 = min(w, fx + fw + margin_x)
347
+ y2 = min(h, fy + fh + margin_y)
348
+
349
+ crop_w = x2 - x1
350
+ crop_h = y2 - y1
351
+ if crop_w <= 0 or crop_h <= 0:
352
  continue
353
 
354
+ crop_cx = (x1 + crop_w / 2) / w
355
+ crop_cy = (y1 + crop_h / 2) / h
356
+ if is_duplicate(crop_cx, crop_cy):
357
+ continue
 
358
 
359
  crop = rgb[y1:y2, x1:x2]
360
+ crop_resized = cv2.resize(crop, (512, 512), interpolation=cv2.INTER_CUBIC)
 
 
 
 
 
 
361
  crop_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=crop_resized)
362
  crop_result = landmarker.detect(crop_image)
363
 
364
  if crop_result.face_landmarks:
365
+ face_landmarks = crop_result.face_landmarks[0]
366
+ xs_global = [(x1 + lm.x * crop_w) / w for lm in face_landmarks]
367
+ ys_global = [(y1 + lm.y * crop_h) / h for lm in face_landmarks]
368
+ cx, cy = np.mean(xs_global), np.mean(ys_global)
369
+ if not is_duplicate(cx, cy):
370
+ processed_centers.append((cx, cy))
371
+ for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:
372
+ points = []
373
+ for idx in indices:
374
+ lm = face_landmarks[idx]
375
+ gx = int(x1 + lm.x * crop_w)
376
+ gy = int(y1 + lm.y * crop_h)
377
+ points.append([gx, gy])
378
+ pts = np.array(points, np.int32).reshape((-1, 1, 2))
379
+ cv2.polylines(eyebrows_layer, [pts], isClosed=False, color=255, thickness=eyebrow_thickness)
380
  except Exception as e:
381
  print(f"[AI] Eyebrow extraction error or library missing: {e}")
382
 
 
 
 
 
 
 
 
383
  return eyebrows_layer
384
 
385
 
 
519
 
520
  lineart = make_faceless_lineart(img, cfg)
521
  cutout = make_faceless_cutout(img)
522
+ return lineart, cutout