vitordigitizing commited on
Commit
dcd30c0
·
verified ·
1 Parent(s): c912568

Update faceless_processing.py

Browse files
Files changed (1) hide show
  1. faceless_processing.py +191 -219
faceless_processing.py CHANGED
@@ -23,8 +23,10 @@ except Exception as e:
23
  print(f"[AI] Failed to load rembg session: {e}")
24
  _SESSION_ISNET = None
25
 
 
26
  def _download_assets_globally():
27
  try:
 
28
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
29
  os.makedirs(cascade_dir, exist_ok=True)
30
  xml_urls = {
@@ -34,32 +36,33 @@ def _download_assets_globally():
34
  for name, url in xml_urls.items():
35
  path = os.path.join(cascade_dir, name)
36
  if not os.path.exists(path) or os.path.getsize(path) < 1000:
37
- print(f"[AI] Downloading cascade {name} ...")
38
  try:
39
  urllib.request.urlretrieve(url, path)
40
- except Exception as e:
41
- print(f"[AI] Failed: {e}")
42
 
 
43
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
44
  os.makedirs(model_dir, exist_ok=True)
45
  model_path = os.path.join(model_dir, "face_landmarker.task")
46
  if not os.path.exists(model_path) or os.path.getsize(model_path) < 1000000:
47
- print("[AI] Downloading face_landmarker.task ...")
48
  try:
49
  model_url = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task"
50
  urllib.request.urlretrieve(model_url, model_path)
51
- print("[AI] Download complete!")
52
- except Exception as e:
53
- print(f"[AI] Failed: {e}")
54
  except Exception as e:
55
- print(f"[AI] Asset download error: {e}")
56
 
57
  _download_assets_globally()
58
 
59
 
60
  @dataclass
61
  class LineartConfig:
62
- # Backward compatibility fields
63
  prompt: str = ""
64
  negative_prompt: str = ""
65
  stable_diffusion_model_id: str = ""
@@ -80,34 +83,30 @@ class LineartConfig:
80
  mask_smooth_threshold: int = 128
81
  min_silhouette_area: float = 200.0
82
 
83
- silhouette_line_thickness: int = 1 # desenha fino, dilata depois
84
-
85
- # --- PARÂMETROS AJUSTADOS PARA RETER DETALHES, MAS SEM EXCESSO ---
86
- canny_low: int = 30
87
- canny_high: int = 120
88
- bilateral_d: int = 6 # um pouco menos suavização
89
- bilateral_sigma_color: int = 70 # intermediário
90
- bilateral_sigma_space: int = 70
91
- gaussian_ksize: int = 5 # menos blur
92
- min_contour_perimeter: float = 20.0 # captura linhas mais curtas
93
- interior_line_thickness: int = 1 # fino, dilata depois
94
-
95
- # Detail pass ATIVADO, mas com filtros para não gerar muito ruído
96
- enable_detail_pass: bool = True
97
- detail_canny_low: int = 8
98
- detail_canny_high: int = 35
99
- detail_gaussian_ksize: int = 3
100
- detail_min_perimeter: float = 12.0
101
- detail_bilateral_d: int = 3
102
- detail_bilateral_sigma: int = 35
103
-
104
- min_embroidery_stitch_px: int = 15
105
-
106
- # Auto-Canny sigma: 0.22 pega mais detalhes que 0.25
107
- canny_sigma: float = 0.22
108
-
109
- # Filtro de aspecto: 1.5 descarta apenas ruídos muito redondos
110
- min_aspect_ratio: float = 1.5
111
 
112
  # Face detection
113
  face_scale_factor: float = 1.05
@@ -117,23 +116,31 @@ class LineartConfig:
117
  face_nms_iou_thresh: float = 0.35
118
  face_max_count: int = 6
119
 
 
 
 
 
 
 
 
 
120
  face_cx_ratio: float = 0.50
121
- face_cy_ratio: float = 0.54
122
- face_rx_ratio: float = 0.28
123
- face_ry_ratio: float = 0.22
124
- face_erase_blur: int = 18
125
- face_erase_threshold: int = 45
126
 
 
127
  mediapipe_num_faces: int = 6
128
 
129
- detect_face_oval: bool = True
130
- face_oval_thickness: int = 2
131
-
132
- eyebrow_thickness: int = 3
133
- eyebrow_dilate: int = 2
134
 
135
 
136
  def _nms_faces(faces: list, iou_thresh: float) -> list:
 
137
  if not faces:
138
  return []
139
  boxes = np.array(faces, dtype=float)
@@ -156,8 +163,10 @@ def _nms_faces(faces: list, iou_thresh: float) -> list:
156
 
157
 
158
  def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
 
159
  h = rgb.shape[0]
160
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
 
161
  clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
162
  gray_eq = clahe.apply(gray)
163
  faces = []
@@ -181,6 +190,7 @@ def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
181
 
182
  for cascade in classifiers:
183
  if cascade and not cascade.empty():
 
184
  for img_gray in [gray, gray_eq]:
185
  detected = cascade.detectMultiScale(
186
  img_gray,
@@ -191,18 +201,27 @@ def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
191
  if len(detected) > 0:
192
  faces.extend(detected.tolist())
193
  except Exception as e:
194
- print(f"[AI] Face detection failed: {e}")
195
 
 
196
  faces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]
 
 
197
  faces = _nms_faces(faces, cfg.face_nms_iou_thresh)
 
 
198
  max_faces = getattr(cfg, 'face_max_count', 6)
199
  if len(faces) > max_faces:
 
200
  faces = sorted(faces, key=lambda f: f[2] * f[3], reverse=True)[:max_faces]
 
201
  return faces
202
 
203
 
204
  def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray:
 
205
  if alpha_channel is not None:
 
206
  mask = (alpha_channel > 30).astype(np.uint8) * 255
207
  else:
208
  white_mask = np.all(rgb > cfg.white_bg_threshold, axis=2)
@@ -214,14 +233,21 @@ def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optio
214
 
215
 
216
  def _smooth_contour_spline(cnt: np.ndarray, n_points: int = 400) -> Optional[np.ndarray]:
 
 
 
 
 
217
  if not _SCIPY_AVAILABLE:
218
  return None
219
- pts = cnt[:, 0, :]
220
  if len(pts) < 4:
221
  return None
222
  try:
 
 
223
  tck, _ = splprep([pts[:, 0].astype(float), pts[:, 1].astype(float)],
224
- s=2.0, per=True, quiet=True)
225
  u_new = np.linspace(0, 1, n_points)
226
  x_new, y_new = splev(u_new, tck)
227
  spline_pts = np.stack([x_new, y_new], axis=1).astype(np.int32)
@@ -231,44 +257,50 @@ def _smooth_contour_spline(cnt: np.ndarray, n_points: int = 400) -> Optional[np.
231
 
232
 
233
  def build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
 
 
 
 
 
234
  mask = subject_mask.copy()
 
 
235
  if cfg.mask_smooth_ksize > 1:
236
  k = max(21, cfg.mask_smooth_ksize if cfg.mask_smooth_ksize % 2 == 1 else cfg.mask_smooth_ksize + 1)
237
  mask = cv2.GaussianBlur(mask, (k, k), 0)
238
  _, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)
 
 
239
  k_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))
240
  mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k_close, iterations=2)
 
241
  contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
242
  silhouette = np.zeros_like(subject_mask)
 
243
  for cnt in contours:
244
  if cv2.contourArea(cnt) < cfg.min_silhouette_area:
245
  continue
 
 
246
  smooth = _smooth_contour_spline(cnt)
247
  if smooth is not None:
248
  cv2.polylines(silhouette, [smooth], isClosed=True,
249
  color=255, thickness=cfg.silhouette_line_thickness,
250
  lineType=cv2.LINE_AA)
251
  else:
 
252
  eps = 0.0003 * cv2.arcLength(cnt, True)
253
  approx = cv2.approxPolyDP(cnt, eps, True)
254
  cv2.drawContours(silhouette, [approx], -1, 255,
255
  cfg.silhouette_line_thickness, lineType=cv2.LINE_AA)
 
256
  return silhouette
257
 
258
 
259
- def _auto_canny(image: np.ndarray, sigma: float = 0.33,
260
- mask: Optional[np.ndarray] = None) -> np.ndarray:
261
- if mask is not None and np.any(mask > 0):
262
- subject_pixels = image[mask > 0]
263
- v = float(np.median(subject_pixels))
264
- else:
265
- v = float(np.median(image))
266
- lower = int(max(0, (1.0 - sigma) * v))
267
- upper = int(min(255, (1.0 + sigma) * v))
268
- return cv2.Canny(image, lower, upper)
269
 
270
 
271
  def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfig) -> np.ndarray:
 
272
  h, w = shape
273
  mask = np.zeros((h, w), dtype=np.uint8)
274
  for (fx, fy, fw, fh) in faces:
@@ -282,72 +314,66 @@ def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfi
282
 
283
 
284
  def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
 
 
 
 
 
 
 
285
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
286
 
287
- # Suavização moderada
288
- blurred = cv2.bilateralFilter(gray, cfg.bilateral_d,
289
- cfg.bilateral_sigma_color,
290
- cfg.bilateral_sigma_space)
291
- blurred = cv2.GaussianBlur(blurred, (cfg.gaussian_ksize, cfg.gaussian_ksize), 0)
292
-
293
- erode_size = max(3, cfg.silhouette_line_thickness + 2)
294
- if erode_size % 2 == 0:
295
- erode_size += 1
296
- kernel_erode = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (erode_size, erode_size))
297
- eroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)
298
-
299
- # Canny principal
300
- sigma = getattr(cfg, 'canny_sigma', 0.33)
301
- if sigma > 0:
302
- edges = _auto_canny(blurred, sigma, mask=eroded_mask)
303
- else:
304
- edges = cv2.Canny(blurred, cfg.canny_low, cfg.canny_high)
305
-
306
- # Detail pass (ativado)
307
- if getattr(cfg, 'enable_detail_pass', False):
308
- detail_d = getattr(cfg, 'detail_bilateral_d', 3)
309
- detail_sigma = getattr(cfg, 'detail_bilateral_sigma', 35)
310
- detail_ksize = getattr(cfg, 'detail_gaussian_ksize', 3)
311
  blurred_detail = cv2.bilateralFilter(gray, detail_d, detail_sigma, detail_sigma)
312
  blurred_detail = cv2.GaussianBlur(blurred_detail, (detail_ksize, detail_ksize), 0)
313
  edges_detail = cv2.Canny(
314
  blurred_detail,
315
- getattr(cfg, 'detail_canny_low', 8),
316
- getattr(cfg, 'detail_canny_high', 35)
317
  )
318
- edges = cv2.bitwise_or(edges, edges_detail)
319
 
 
 
 
 
 
 
 
 
 
320
  edges = cv2.bitwise_and(edges, eroded_mask)
321
 
322
- # Filtrar contornos
323
  min_perimeter = cfg.min_contour_perimeter
324
  min_stitch = getattr(cfg, 'min_embroidery_stitch_px', 15)
325
- min_aspect = getattr(cfg, 'min_aspect_ratio', 1.5)
326
-
327
  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
328
  filtered = np.zeros_like(edges)
329
-
330
  for cnt in contours:
331
  perimeter = cv2.arcLength(cnt, False)
 
332
  if perimeter < min_perimeter:
333
  continue
 
334
  if min_stitch > 0 and perimeter < min_stitch:
335
  continue
336
- if min_aspect > 0:
337
- x, y, bw, bh = cv2.boundingRect(cnt)
338
- long_side = max(bw, bh)
339
- short_side = min(bw, bh) + 1
340
- if long_side / short_side < min_aspect:
341
- continue
342
-
343
- eps = 0.005 * perimeter
344
  smooth = cv2.approxPolyDP(cnt, eps, False)
345
  cv2.drawContours(filtered, [smooth], -1, 255, cfg.interior_line_thickness)
346
 
347
- # Dilatação final: apenas 1 iteração para não perder detalhes
348
  kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
349
  filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)
350
-
351
  return filtered
352
 
353
 
@@ -357,6 +383,7 @@ _LANDMARKER_NUM_FACES = None
357
 
358
  def get_landmarker(model_path, num_faces: int = 6):
359
  global _LANDMARKER_CACHE, _LANDMARKER_NUM_FACES
 
360
  if _LANDMARKER_CACHE is None or _LANDMARKER_NUM_FACES != num_faces:
361
  import mediapipe as mp
362
  from mediapipe.tasks import python
@@ -375,6 +402,14 @@ def get_landmarker(model_path, num_faces: int = 6):
375
 
376
 
377
  def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = None) -> np.ndarray:
 
 
 
 
 
 
 
 
378
  h, w, _ = rgb.shape
379
  eyebrows_layer = np.zeros((h, w), dtype=np.uint8)
380
 
@@ -383,6 +418,7 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
383
  from mediapipe.tasks import python
384
  from mediapipe.tasks.python import vision
385
 
 
386
  model_path = cfg.mediapipe_model_path
387
  if not model_path or not os.path.exists(model_path):
388
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
@@ -394,16 +430,18 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
394
  urllib.request.urlretrieve(model_url, model_path)
395
  print("[AI] Download complete!")
396
 
 
397
  LEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]
398
  RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276]
399
 
400
- eyebrow_thickness = getattr(cfg, 'eyebrow_thickness', 3)
401
- eyebrow_dilate = getattr(cfg, 'eyebrow_dilate', 2)
402
 
403
- drawn_centers_px: list = []
 
404
 
405
  def is_duplicate_px(cx_px: float, cy_px: float) -> bool:
406
- min_dist = min(w, h) * 0.06
407
  for (pcx, pcy) in drawn_centers_px:
408
  if np.hypot(cx_px - pcx, cy_px - pcy) < min_dist:
409
  return True
@@ -411,6 +449,7 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
411
 
412
  def draw_eyebrow_landmarks(face_lms, origin_x: int, origin_y: int,
413
  scale_x: float, scale_y: float):
 
414
  for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:
415
  pts = []
416
  for idx in indices:
@@ -431,17 +470,23 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
431
  num_faces = getattr(cfg, 'mediapipe_num_faces', 6)
432
  landmarker = get_landmarker(model_path, num_faces=num_faces)
433
 
 
434
  mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
435
  global_result = landmarker.detect(mp_image)
436
  if global_result.face_landmarks:
437
  for face_lms in global_result.face_landmarks:
 
438
  cx_px = np.mean([lm.x for lm in face_lms]) * w
439
  cy_px = np.mean([lm.y for lm in face_lms]) * h
440
  if not is_duplicate_px(cx_px, cy_px):
441
  drawn_centers_px.append((cx_px, cy_px))
442
- draw_eyebrow_landmarks(face_lms, 0, 0, w, h)
 
 
443
 
 
444
  for (fx, fy, fw, fh) in faces:
 
445
  mx = int(fw * 0.50)
446
  my = int(fh * 0.50)
447
  x1 = max(0, fx - mx); y1 = max(0, fy - my)
@@ -449,25 +494,33 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
449
  crop_w, crop_h = x2 - x1, y2 - y1
450
  if crop_w < 20 or crop_h < 20:
451
  continue
 
 
452
  face_cx_px = (x1 + x2) / 2
453
  face_cy_px = (y1 + y2) / 2
454
  if is_duplicate_px(face_cx_px, face_cy_px):
455
- continue
 
456
  crop = rgb[y1:y2, x1:x2]
 
457
  target = max(512, crop_w, crop_h)
458
  scale = target / max(crop_w, crop_h)
459
  cw_scaled = int(crop_w * scale)
460
  ch_scaled = int(crop_h * scale)
461
  crop_resized = cv2.resize(crop, (cw_scaled, ch_scaled), interpolation=cv2.INTER_CUBIC)
 
462
  crop_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=crop_resized)
463
  crop_result = landmarker.detect(crop_image)
 
464
  if crop_result.face_landmarks:
465
  face_lms = crop_result.face_landmarks[0]
 
466
  cx_px2 = x1 + np.mean([lm.x for lm in face_lms]) * crop_w
467
  cy_px2 = y1 + np.mean([lm.y for lm in face_lms]) * crop_h
468
  if is_duplicate_px(cx_px2, cy_px2):
469
  continue
470
  drawn_centers_px.append((cx_px2, cy_px2))
 
471
  draw_eyebrow_landmarks(face_lms,
472
  origin_x=x1, origin_y=y1,
473
  scale_x=crop_w / cw_scaled * cw_scaled,
@@ -476,10 +529,11 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
476
  print(f"[eyebrows] Drew eyebrows for {len(drawn_centers_px)} face(s)")
477
 
478
  except Exception as e:
479
- print(f"[AI] Eyebrow extraction error: {e}")
480
 
 
481
  if eyebrows_layer.any():
482
- dil = getattr(cfg, 'eyebrow_dilate', 2)
483
  if dil > 0:
484
  kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
485
  eyebrows_layer = cv2.dilate(eyebrows_layer, kernel, iterations=dil)
@@ -487,117 +541,22 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
487
  return eyebrows_layer
488
 
489
 
490
- def draw_face_oval(rgb: np.ndarray, cfg: 'LineartConfig', faces: Optional[list] = None) -> np.ndarray:
491
- h, w, _ = rgb.shape
492
- oval_layer = np.zeros((h, w), dtype=np.uint8)
493
-
494
- FACE_LOWER_CONTOUR = [
495
- 454, 323, 361, 288, 397, 365, 379, 378, 400, 377,
496
- 152,
497
- 148, 176, 149, 150, 136, 172, 58, 132, 93, 234
498
- ]
499
-
500
- thickness = getattr(cfg, 'face_oval_thickness', 2)
501
-
502
- try:
503
- import mediapipe as mp
504
-
505
- model_path = cfg.mediapipe_model_path
506
- if not model_path or not os.path.exists(model_path):
507
- model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
508
- model_path = os.path.join(model_dir, "face_landmarker.task")
509
-
510
- if not os.path.exists(model_path) or os.path.getsize(model_path) < 1000000:
511
- print("[face_oval] face_landmarker.task not found, skipping oval drawing")
512
- return oval_layer
513
-
514
- drawn_centers_px: list = []
515
-
516
- def is_duplicate_px(cx_px: float, cy_px: float) -> bool:
517
- min_dist = min(w, h) * 0.06
518
- return any(np.hypot(cx_px - pcx, cy_px - pcy) < min_dist
519
- for (pcx, pcy) in drawn_centers_px)
520
-
521
- def draw_oval_from_landmarks(face_lms, origin_x: int, origin_y: int,
522
- scale_x: float, scale_y: float):
523
- pts = []
524
- for idx in FACE_LOWER_CONTOUR:
525
- if idx >= len(face_lms):
526
- continue
527
- lm = face_lms[idx]
528
- px = int(origin_x + lm.x * scale_x)
529
- py = int(origin_y + lm.y * scale_y)
530
- pts.append([px, py])
531
- if len(pts) < 4:
532
- return
533
- pts_np = np.array(pts, np.int32).reshape((-1, 1, 2))
534
- cv2.polylines(oval_layer, [pts_np], isClosed=False,
535
- color=255, thickness=thickness, lineType=cv2.LINE_AA)
536
-
537
- if faces is None:
538
- faces = detect_faces(rgb, cfg)
539
-
540
- with _LANDMARKER_LOCK:
541
- num_faces = getattr(cfg, 'mediapipe_num_faces', 6)
542
- landmarker = get_landmarker(model_path, num_faces=num_faces)
543
-
544
- mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
545
- result = landmarker.detect(mp_image)
546
- if result.face_landmarks:
547
- for face_lms in result.face_landmarks:
548
- cx_px = np.mean([lm.x for lm in face_lms]) * w
549
- cy_px = np.mean([lm.y for lm in face_lms]) * h
550
- if not is_duplicate_px(cx_px, cy_px):
551
- drawn_centers_px.append((cx_px, cy_px))
552
- draw_oval_from_landmarks(face_lms, 0, 0, w, h)
553
-
554
- for (fx, fy, fw, fh) in faces:
555
- mx = int(fw * 0.50)
556
- my = int(fh * 0.50)
557
- x1 = max(0, fx - mx); y1 = max(0, fy - my)
558
- x2 = min(w, fx + fw + mx); y2 = min(h, fy + fh + my)
559
- crop_w, crop_h = x2 - x1, y2 - y1
560
- if crop_w < 20 or crop_h < 20:
561
- continue
562
- face_cx_px = (x1 + x2) / 2
563
- face_cy_px = (y1 + y2) / 2
564
- if is_duplicate_px(face_cx_px, face_cy_px):
565
- continue
566
- crop = rgb[y1:y2, x1:x2]
567
- target = max(512, crop_w, crop_h)
568
- scale = target / max(crop_w, crop_h)
569
- cw_s = int(crop_w * scale); ch_s = int(crop_h * scale)
570
- crop_r = cv2.resize(crop, (cw_s, ch_s), interpolation=cv2.INTER_CUBIC)
571
- crop_img = mp.Image(image_format=mp.ImageFormat.SRGB, data=crop_r)
572
- crop_res = landmarker.detect(crop_img)
573
- if crop_res.face_landmarks:
574
- face_lms = crop_res.face_landmarks[0]
575
- cx2 = x1 + np.mean([lm.x for lm in face_lms]) * crop_w
576
- cy2 = y1 + np.mean([lm.y for lm in face_lms]) * crop_h
577
- if is_duplicate_px(cx2, cy2):
578
- continue
579
- drawn_centers_px.append((cx2, cy2))
580
- draw_oval_from_landmarks(face_lms, x1, y1, crop_w, crop_h)
581
-
582
- print(f"[face_oval] Drew face oval for {len(drawn_centers_px)} face(s)")
583
-
584
- except Exception as e:
585
- print(f"[face_oval] Error: {e}")
586
-
587
- if oval_layer.any():
588
- kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
589
- oval_layer = cv2.dilate(oval_layer, kernel, iterations=2)
590
 
591
- return oval_layer
592
-
593
-
594
- def make_faceless_lineart(img: Image.Image, cfg: LineartConfig = None) -> Image.Image:
 
 
 
595
  cfg = cfg or LineartConfig()
596
 
 
597
  alpha_channel: Optional[np.ndarray] = None
598
  if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
599
  rgba_img = img.convert("RGBA")
600
  alpha_np = np.array(rgba_img)[:, :, 3]
 
601
  if np.any(alpha_np < 200):
602
  alpha_channel = alpha_np
603
  background = Image.new("RGBA", img.size, (255, 255, 255, 255))
@@ -610,27 +569,32 @@ def make_faceless_lineart(img: Image.Image, cfg: LineartConfig = None) -> Image.
610
  rgb = img_np[:, :, :3]
611
  h, w = rgb.shape[:2]
612
 
 
613
  subject_mask = build_subject_mask(rgb, cfg, alpha_channel)
 
 
614
  faces = detect_faces(rgb, cfg)
615
  print(f"[lineart] Detected {len(faces)} face(s)")
616
 
 
617
  silhouette = build_silhouette(subject_mask, cfg)
 
 
618
  interior = build_interior_edges(rgb, subject_mask, cfg)
619
 
 
620
  face_erase = build_face_erase_mask(faces, (h, w), cfg)
621
  interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))
622
 
 
623
  final_lines = cv2.add(silhouette, interior_clean)
624
 
 
625
  if cfg.detect_eyebrows:
626
  eyebrows = draw_eyebrows(rgb, cfg, faces=faces)
627
  final_lines = cv2.add(final_lines, eyebrows)
628
 
629
- if getattr(cfg, 'detect_face_oval', True):
630
- face_oval = draw_face_oval(rgb, cfg, faces=faces)
631
- final_lines = cv2.add(final_lines, face_oval)
632
-
633
- # Remove bordas
634
  border_erase_width = max(cfg.silhouette_line_thickness, cfg.interior_line_thickness) + 2
635
  if border_erase_width > 0:
636
  final_lines[0:border_erase_width, :] = 0
@@ -638,9 +602,14 @@ def make_faceless_lineart(img: Image.Image, cfg: LineartConfig = None) -> Image.
638
  final_lines[:, 0:border_erase_width] = 0
639
  final_lines[:, -border_erase_width:] = 0
640
 
 
 
641
  alpha = Image.fromarray(final_lines)
642
- transparent = Image.new("RGBA", img.size, (0, 0, 0, 0))
 
 
643
  transparent.putalpha(alpha)
 
644
  return transparent
645
 
646
 
@@ -673,13 +642,16 @@ def remove_background_subject(img: Image.Image) -> Image.Image:
673
  rgba = img.convert("RGBA")
674
  if _has_real_transparency(rgba):
675
  return rgba
 
676
  if _SESSION_ISNET is None:
677
  return rgba
 
678
  mask = remove(rgba, session=_SESSION_ISNET, only_mask=True)
679
  alpha = mask.convert("L") if isinstance(mask, Image.Image) else Image.open(io.BytesIO(mask)).convert("L")
680
  if alpha.size != rgba.size:
681
  alpha = alpha.resize(rgba.size, Image.LANCZOS)
682
  alpha = alpha.filter(ImageFilter.GaussianBlur(radius=0.8))
 
683
  r, g, b, _a = rgba.split()
684
  return Image.merge("RGBA", (r, g, b, alpha))
685
  except Exception as exc:
 
23
  print(f"[AI] Failed to load rembg session: {e}")
24
  _SESSION_ISNET = None
25
 
26
+ # Globally download cascades and models at startup if missing (runs on main container with internet access)
27
  def _download_assets_globally():
28
  try:
29
+ # 1. Cascades
30
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
31
  os.makedirs(cascade_dir, exist_ok=True)
32
  xml_urls = {
 
36
  for name, url in xml_urls.items():
37
  path = os.path.join(cascade_dir, name)
38
  if not os.path.exists(path) or os.path.getsize(path) < 1000:
39
+ print(f"[AI] Downloading cascade {name} globally from OpenCV GitHub...")
40
  try:
41
  urllib.request.urlretrieve(url, path)
42
+ except Exception as dl_err:
43
+ print(f"[AI] Failed to download {name} globally: {dl_err}")
44
 
45
+ # 2. MediaPipe Model
46
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
47
  os.makedirs(model_dir, exist_ok=True)
48
  model_path = os.path.join(model_dir, "face_landmarker.task")
49
  if not os.path.exists(model_path) or os.path.getsize(model_path) < 1000000:
50
+ print("[AI] Downloading face_landmarker.task globally...")
51
  try:
52
  model_url = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task"
53
  urllib.request.urlretrieve(model_url, model_path)
54
+ print("[AI] face_landmarker.task download complete!")
55
+ except Exception as dl_err:
56
+ print(f"[AI] Failed to download face_landmarker.task globally: {dl_err}")
57
  except Exception as e:
58
+ print(f"[AI] Global asset download manager failed: {e}")
59
 
60
  _download_assets_globally()
61
 
62
 
63
  @dataclass
64
  class LineartConfig:
65
+ # Backward compatibility fields (unused by OpenCV pipeline but required by callers)
66
  prompt: str = ""
67
  negative_prompt: str = ""
68
  stable_diffusion_model_id: str = ""
 
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
 
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:
143
+ """Non-maximum suppression to remove duplicate face detections."""
144
  if not faces:
145
  return []
146
  boxes = np.array(faces, dtype=float)
 
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 = []
 
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,
 
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
 
206
+ # Remove detections in lower body (false positives)
207
  faces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]
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
 
221
  def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray:
222
+ """Build subject mask. Uses alpha channel if available, otherwise thresholds white background."""
223
  if alpha_channel is not None:
224
+ # Use rembg/RGBA alpha directly — much more accurate than color threshold
225
  mask = (alpha_channel > 30).astype(np.uint8) * 255
226
  else:
227
  white_mask = np.all(rgb > cfg.white_bg_threshold, axis=2)
 
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)
 
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
305
  mask = np.zeros((h, w), dtype=np.uint8)
306
  for (fx, fy, fw, fh) in faces:
 
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
352
+ kernel_erode = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (erode_size, erode_size))
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))
376
  filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)
 
377
  return filtered
378
 
379
 
 
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
 
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
  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
  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
 
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:
 
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)
 
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,
 
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)
 
541
  return eyebrows_layer
542
 
543
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
544
 
545
+ def make_faceless_lineart(
546
+ img: Image.Image,
547
+ cfg: LineartConfig = None
548
+ ) -> Image.Image:
549
+ """
550
+ Generate faceless lineart transparent image from a photo.
551
+ """
552
  cfg = cfg or LineartConfig()
553
 
554
+ # Preserve alpha channel if image already has a transparent background (e.g. from rembg)
555
  alpha_channel: Optional[np.ndarray] = None
556
  if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
557
  rgba_img = img.convert("RGBA")
558
  alpha_np = np.array(rgba_img)[:, :, 3]
559
+ # Only use alpha mask if it contains meaningful transparency
560
  if np.any(alpha_np < 200):
561
  alpha_channel = alpha_np
562
  background = Image.new("RGBA", img.size, (255, 255, 255, 255))
 
569
  rgb = img_np[:, :, :3]
570
  h, w = rgb.shape[:2]
571
 
572
+ # 1. Subject mask — use alpha if available, else color threshold
573
  subject_mask = build_subject_mask(rgb, cfg, alpha_channel)
574
+
575
+ # 2. Detect faces
576
  faces = detect_faces(rgb, cfg)
577
  print(f"[lineart] Detected {len(faces)} face(s)")
578
 
579
+ # 3. Silhouette outline
580
  silhouette = build_silhouette(subject_mask, cfg)
581
+
582
+ # 4. Interior structural edges
583
  interior = build_interior_edges(rgb, subject_mask, cfg)
584
 
585
+ # 5. Erase face details (keep silhouette outline of head shape)
586
  face_erase = build_face_erase_mask(faces, (h, w), cfg)
587
  interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))
588
 
589
+ # 6. Combine
590
  final_lines = cv2.add(silhouette, interior_clean)
591
 
592
+ # 6.5. Optional eyebrow detection overlay
593
  if cfg.detect_eyebrows:
594
  eyebrows = draw_eyebrows(rgb, cfg, faces=faces)
595
  final_lines = cv2.add(final_lines, eyebrows)
596
 
597
+ # Avoid drawing rectangular boxes/borders at the image edges
 
 
 
 
598
  border_erase_width = max(cfg.silhouette_line_thickness, cfg.interior_line_thickness) + 2
599
  if border_erase_width > 0:
600
  final_lines[0:border_erase_width, :] = 0
 
602
  final_lines[:, 0:border_erase_width] = 0
603
  final_lines[:, -border_erase_width:] = 0
604
 
605
+
606
+ # 7. Build output image
607
  alpha = Image.fromarray(final_lines)
608
+ size = img.size
609
+
610
+ transparent = Image.new("RGBA", size, (0, 0, 0, 0))
611
  transparent.putalpha(alpha)
612
+
613
  return transparent
614
 
615
 
 
642
  rgba = img.convert("RGBA")
643
  if _has_real_transparency(rgba):
644
  return rgba
645
+
646
  if _SESSION_ISNET is None:
647
  return rgba
648
+
649
  mask = remove(rgba, session=_SESSION_ISNET, only_mask=True)
650
  alpha = mask.convert("L") if isinstance(mask, Image.Image) else Image.open(io.BytesIO(mask)).convert("L")
651
  if alpha.size != rgba.size:
652
  alpha = alpha.resize(rgba.size, Image.LANCZOS)
653
  alpha = alpha.filter(ImageFilter.GaussianBlur(radius=0.8))
654
+
655
  r, g, b, _a = rgba.split()
656
  return Image.merge("RGBA", (r, g, b, alpha))
657
  except Exception as exc: