vitordigitizing commited on
Commit
a254b78
·
verified ·
1 Parent(s): 1c07d7d

Update faceless_processing.py

Browse files
Files changed (1) hide show
  1. faceless_processing.py +400 -182
faceless_processing.py CHANGED
@@ -10,16 +10,69 @@ import urllib.request
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:
16
  print(f"[AI] Failed to load rembg session: {e}")
17
  _SESSION_ISNET = None
18
 
19
- # Globally download cascades and models at startup if missing (runs on main container with internet access)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  def _download_assets_globally():
21
  try:
22
- # 1. Cascades
23
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
24
  os.makedirs(cascade_dir, exist_ok=True)
25
  xml_urls = {
@@ -35,7 +88,6 @@ def _download_assets_globally():
35
  except Exception as dl_err:
36
  print(f"[AI] Failed to download {name} globally: {dl_err}")
37
 
38
- # 2. MediaPipe Model
39
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
40
  os.makedirs(model_dir, exist_ok=True)
41
  model_path = os.path.join(model_dir, "face_landmarker.task")
@@ -51,11 +103,14 @@ def _download_assets_globally():
51
  print(f"[AI] Global asset download manager failed: {e}")
52
 
53
  _download_assets_globally()
 
 
 
54
 
55
 
56
  @dataclass
57
  class LineartConfig:
58
- # Backward compatibility fields (unused by OpenCV pipeline but required by callers)
59
  prompt: str = ""
60
  negative_prompt: str = ""
61
  stable_diffusion_model_id: str = ""
@@ -68,46 +123,94 @@ class LineartConfig:
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:
110
- """Non-maximum suppression to remove duplicate face detections."""
111
  if not faces:
112
  return []
113
  boxes = np.array(faces, dtype=float)
@@ -130,55 +233,50 @@ 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')
143
-
144
  classifiers = []
145
  if os.path.exists(path_default):
146
  classifiers.append(cv2.CascadeClassifier(path_default))
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'),
154
  cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')
155
  ]
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
 
170
- # Remove detections in lower body (false positives)
171
  faces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]
172
-
173
- # Remove duplicates
174
  faces = _nms_faces(faces, cfg.face_nms_iou_thresh)
 
 
 
175
  return faces
176
 
 
177
 
178
  def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray:
179
- """Build subject mask. Uses alpha channel if available, otherwise thresholds white background."""
180
  if alpha_channel is not None:
181
- # Use rembg/RGBA alpha directly — much more accurate than color threshold
182
  mask = (alpha_channel > 30).astype(np.uint8) * 255
183
  else:
184
  white_mask = np.all(rgb > cfg.white_bg_threshold, axis=2)
@@ -189,30 +287,53 @@ def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optio
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, lineType=cv2.LINE_AA)
 
 
 
 
 
 
 
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
217
  mask = np.zeros((h, w), dtype=np.uint8)
218
  for (fx, fy, fw, fh) in faces:
@@ -225,14 +346,89 @@ def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfi
225
  return (soft > cfg.face_erase_threshold).astype(np.uint8) * 255
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,55 +436,54 @@ def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: Lineart
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, lineType=cv2.LINE_AA)
253
-
254
- # Mild dilation for uniform, solid strokes
255
  kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
256
  filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)
257
  return filtered
258
 
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
269
-
270
  base_options = python.BaseOptions(model_asset_path=model_path)
271
  options = vision.FaceLandmarkerOptions(
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
-
286
  try:
287
  import mediapipe as mp
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")
@@ -298,107 +493,136 @@ def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = N
298
  print("[AI] Downloading face_landmarker.task for eyebrows...")
299
  model_url = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task"
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, lineType=cv2.LINE_AA)
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, lineType=cv2.LINE_AA)
380
  except Exception as e:
381
  print(f"[AI] Eyebrow extraction error or library missing: {e}")
382
 
 
 
 
 
 
383
  return eyebrows_layer
384
 
385
 
386
-
387
- def make_faceless_lineart(
388
- img: Image.Image,
389
- cfg: LineartConfig = None
390
- ) -> Image.Image:
391
- """
392
- Generate faceless lineart transparent image from a photo.
393
- """
394
  cfg = cfg or LineartConfig()
395
-
396
- # Preserve alpha channel if image already has a transparent background (e.g. from rembg)
397
  alpha_channel: Optional[np.ndarray] = None
398
  if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
399
  rgba_img = img.convert("RGBA")
400
  alpha_np = np.array(rgba_img)[:, :, 3]
401
- # Only use alpha mask if it contains meaningful transparency
402
  if np.any(alpha_np < 200):
403
  alpha_channel = alpha_np
404
  background = Image.new("RGBA", img.size, (255, 255, 255, 255))
@@ -411,32 +635,34 @@ def make_faceless_lineart(
411
  rgb = img_np[:, :, :3]
412
  h, w = rgb.shape[:2]
413
 
414
- # 1. Subject mask — use alpha if available, else color threshold
415
- subject_mask = build_subject_mask(rgb, cfg, alpha_channel)
 
 
 
 
 
 
 
 
 
416
 
417
- # 2. Detect faces
418
  faces = detect_faces(rgb, cfg)
419
  print(f"[lineart] Detected {len(faces)} face(s)")
420
 
421
- # 3. Silhouette outline
422
  silhouette = build_silhouette(subject_mask, cfg)
423
-
424
- # 4. Interior structural edges
425
  interior = build_interior_edges(rgb, subject_mask, cfg)
426
 
427
- # 5. Erase face details (keep silhouette outline of head shape)
428
  face_erase = build_face_erase_mask(faces, (h, w), cfg)
429
  interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))
430
 
431
- # 6. Combine
432
  final_lines = cv2.add(silhouette, interior_clean)
433
 
434
- # 6.5. Optional eyebrow detection overlay
435
  if cfg.detect_eyebrows:
436
  eyebrows = draw_eyebrows(rgb, cfg, faces=faces)
437
  final_lines = cv2.add(final_lines, eyebrows)
438
 
439
- # Avoid drawing rectangular boxes/borders at the image edges
440
  border_erase_width = max(cfg.silhouette_line_thickness, cfg.interior_line_thickness) + 2
441
  if border_erase_width > 0:
442
  final_lines[0:border_erase_width, :] = 0
@@ -444,14 +670,9 @@ def make_faceless_lineart(
444
  final_lines[:, 0:border_erase_width] = 0
445
  final_lines[:, -border_erase_width:] = 0
446
 
447
-
448
- # 7. Build output image
449
  alpha = Image.fromarray(final_lines)
450
- size = img.size
451
-
452
- transparent = Image.new("RGBA", size, (0, 0, 0, 0))
453
  transparent.putalpha(alpha)
454
-
455
  return transparent
456
 
457
 
@@ -479,21 +700,23 @@ def _has_real_transparency(img: Image.Image) -> bool:
479
  return total > 0 and (visible / total) >= 0.03
480
 
481
 
 
 
 
 
 
482
  def remove_background_subject(img: Image.Image) -> Image.Image:
483
  try:
484
  rgba = img.convert("RGBA")
485
  if _has_real_transparency(rgba):
486
  return rgba
487
-
488
  if _SESSION_ISNET is None:
489
  return rgba
490
-
491
  mask = remove(rgba, session=_SESSION_ISNET, only_mask=True)
492
  alpha = mask.convert("L") if isinstance(mask, Image.Image) else Image.open(io.BytesIO(mask)).convert("L")
493
  if alpha.size != rgba.size:
494
  alpha = alpha.resize(rgba.size, Image.LANCZOS)
495
  alpha = alpha.filter(ImageFilter.GaussianBlur(radius=0.8))
496
-
497
  r, g, b, _a = rgba.split()
498
  return Image.merge("RGBA", (r, g, b, alpha))
499
  except Exception as exc:
@@ -505,18 +728,13 @@ def make_faceless_cutout(img: Image.Image) -> Image.Image:
505
  return remove_background_subject(img)
506
 
507
 
508
- def build_faceless_embroidery_assets(
509
- img: Image.Image,
510
- cfg: Optional[LineartConfig] = None,
511
- **kwargs
512
- ) -> Tuple[Image.Image, Image.Image]:
513
  if cfg is None:
514
  cfg = LineartConfig()
515
  if "prompt" in kwargs and kwargs["prompt"] is not None:
516
  cfg.prompt = kwargs["prompt"]
517
  if "negative_prompt" in kwargs and kwargs["negative_prompt"] is not None:
518
  cfg.negative_prompt = kwargs["negative_prompt"]
519
-
520
  lineart = make_faceless_lineart(img, cfg)
521
  cutout = make_faceless_cutout(img)
522
- return lineart, cutout
 
10
  from rembg import remove, new_session
11
  import threading
12
 
13
+
14
+ try:
15
+ from scipy.interpolate import splprep, splev
16
+
17
+ _SCIPY_AVAILABLE = True
18
+ except ImportError:
19
+ _SCIPY_AVAILABLE = False
20
+ print("[AI] scipy not available — falling back to approxPolyDP for silhouette smoothing")
21
+
22
  try:
23
  _SESSION_ISNET = new_session("isnet-general-use")
24
  except Exception as e:
25
  print(f"[AI] Failed to load rembg session: {e}")
26
  _SESSION_ISNET = None
27
 
28
+
29
+ # ---------------------------------------------------------------------------
30
+ # Neural line-art detector (controlnet_aux / informative-drawings)
31
+ # This is what produces the clean, continuous "illustrator" strokes that a
32
+ # Canny edge detector can never achieve.
33
+ # ---------------------------------------------------------------------------
34
+ _LINEART_LOCK = threading.Lock()
35
+ _LINEART_DETECTOR = None
36
+ _LINEART_AVAILABLE = True
37
+
38
+
39
+
40
+
41
+ def get_lineart_detector():
42
+ """
43
+ Lazy-load the controlnet_aux LineartDetector (informative-drawings model
44
+ from lllyasviel/Annotators). Loaded once and cached. Moves to GPU if torch
45
+ + CUDA are available, otherwise runs on CPU.
46
+ """
47
+ global _LINEART_DETECTOR, _LINEART_AVAILABLE
48
+ if _LINEART_DETECTOR is not None or not _LINEART_AVAILABLE:
49
+ return _LINEART_DETECTOR
50
+ with _LINEART_LOCK:
51
+ if _LINEART_DETECTOR is not None:
52
+ return _LINEART_DETECTOR
53
+ try:
54
+ from controlnet_aux import LineartDetector
55
+ detector = LineartDetector.from_pretrained("lllyasviel/Annotators")
56
+ try:
57
+ import torch
58
+ if torch.cuda.is_available():
59
+ detector = detector.to("cuda")
60
+ print("[AI] LineartDetector loaded on CUDA")
61
+ else:
62
+ print("[AI] LineartDetector loaded on CPU")
63
+ except Exception:
64
+ print("[AI] LineartDetector loaded (torch device check skipped)")
65
+ _LINEART_DETECTOR = detector
66
+ except Exception as e:
67
+ print(f"[AI] controlnet_aux LineartDetector unavailable, falling back to Canny: {e}")
68
+ _LINEART_AVAILABLE = False
69
+ _LINEART_DETECTOR = None
70
+ return _LINEART_DETECTOR
71
+
72
+
73
+ # Globally download cascades and models at startup if missing
74
  def _download_assets_globally():
75
  try:
 
76
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
77
  os.makedirs(cascade_dir, exist_ok=True)
78
  xml_urls = {
 
88
  except Exception as dl_err:
89
  print(f"[AI] Failed to download {name} globally: {dl_err}")
90
 
 
91
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
92
  os.makedirs(model_dir, exist_ok=True)
93
  model_path = os.path.join(model_dir, "face_landmarker.task")
 
103
  print(f"[AI] Global asset download manager failed: {e}")
104
 
105
  _download_assets_globally()
106
+ # Warm up the neural detector at import time (download weights once)
107
+ get_lineart_detector()
108
+
109
 
110
 
111
  @dataclass
112
  class LineartConfig:
113
+ # Backward compatibility fields
114
  prompt: str = ""
115
  negative_prompt: str = ""
116
  stable_diffusion_model_id: str = ""
 
123
  transparency_threshold: float = 0.03
124
  detect_eyebrows: bool = True
125
 
 
126
  # Subject mask
127
+ white_bg_threshold: int = 245
128
  mask_close_iterations: int = 4
129
  mask_open_iterations: int = 1
130
+ mask_smooth_ksize: int = 5
131
+ mask_smooth_threshold: int = 128
132
+ min_silhouette_area: float = 200.0
133
 
134
  # Silhouette outline
 
135
 
136
+ silhouette_smooth_ksize: int = 5
137
+
138
+ silhouette_line_thickness: int = 3
139
+
140
+ # --- Neural line-art parameters ---
141
+ lineart_detect_resolution: int = 2048
142
+ lineart_image_resolution: int = 2048
143
+ lineart_coarse: bool = True
144
+
145
+
146
+
147
+ # AUMENTADO: Força a ignorar dobras de roupa e focar só na estrutura
148
+ lineart_threshold: int = 105
149
+
150
+ # AJUSTE DE CABELO E CORPO: Diminuído para capturar fios e dobras de roupa.
151
+ lineart_min_perimeter: float = 70.0
152
+
153
+ # Diminuído para manter os traços mais próximos da borda.
154
+ interior_erode_size: int = 1
155
+
156
+ # AJUSTE GERAL: Afinado para traços internos mais delicados.
157
+ interior_line_thickness: int = 2
158
+
159
+
160
+
161
+ # ---- Canny fallback parametros ----
162
+ canny_low: int = 35
163
+ canny_high: int = 75
164
  bilateral_d: int = 11
165
+ bilateral_sigma_color: int = 110
166
+ bilateral_sigma_space: int = 110
167
+ gaussian_ksize: int = 11
168
+ min_contour_perimeter: float = 15.0
169
+ min_embroidery_stitch_px: int = 25
170
+ enable_detail_pass: bool = False
171
+ detail_canny_low: int = 15
172
+ detail_canny_high: int = 55
173
+ detail_gaussian_ksize: int = 5
174
+ detail_min_perimeter: float = 30.0
175
+ detail_bilateral_d: int = 7
176
+ detail_bilateral_sigma: int = 60
177
 
178
  # Face detection
179
  face_scale_factor: float = 1.05
180
  face_min_neighbors: int = 3
181
+ face_min_size: Tuple[int, int] = (20, 20)
182
+ face_max_y_ratio: float = 0.65
183
+ face_nms_iou_thresh: float = 0.35
184
+ face_max_count: int = 6
185
+
186
+ # Face erase ellipse
187
+ face_cx_ratio: float = 0.50
188
+ face_cy_ratio: float = 0.55
189
+ face_rx_ratio: float = 0.48
190
+ face_ry_ratio: float = 0.50
191
+ face_erase_blur: int = 5
192
+ face_erase_threshold: int = 90
193
+
194
+ # MediaPipe
195
+ mediapipe_num_faces: int = 6
196
+
197
+ # --- AJUSTE DE SOBRANCELHA ---
198
+ # Reduzido drasticamente para um traço fino e sutil.
199
+ eyebrow_thickness: int = 2
200
+ # Zerado (era 1). Isso remove o "borrão" que deixava a sobrancelha grossa demais.
201
+ eyebrow_dilate: int = 0
202
+
203
+ # Face shape
204
+ draw_face_oval: bool = True
205
+ face_oval_thickness: int = 3
206
+ face_oval_skip_top_ratio: float = 0.50
207
+
208
+
209
+
210
 
 
 
 
 
 
 
 
211
 
212
 
213
  def _nms_faces(faces: list, iou_thresh: float) -> list:
 
214
  if not faces:
215
  return []
216
  boxes = np.array(faces, dtype=float)
 
233
 
234
 
235
  def detect_faces(rgb: np.ndarray, cfg: LineartConfig) -> list:
 
236
  h = rgb.shape[0]
237
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
238
+ clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
239
+ gray_eq = clahe.apply(gray)
240
  faces = []
 
241
  try:
 
242
  cascade_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "cascades")
243
  path_default = os.path.join(cascade_dir, 'haarcascade_frontalface_default.xml')
244
  path_alt = os.path.join(cascade_dir, 'haarcascade_frontalface_alt2.xml')
 
245
  classifiers = []
246
  if os.path.exists(path_default):
247
  classifiers.append(cv2.CascadeClassifier(path_default))
248
  if os.path.exists(path_alt):
249
  classifiers.append(cv2.CascadeClassifier(path_alt))
 
 
250
  if not classifiers or all(c.empty() for c in classifiers):
251
  classifiers = [
252
  cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'),
253
  cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')
254
  ]
 
255
  for cascade in classifiers:
256
  if cascade and not cascade.empty():
257
+ for img_gray in [gray, gray_eq]:
258
+ detected = cascade.detectMultiScale(
259
+ img_gray,
260
+ scaleFactor=cfg.face_scale_factor,
261
+ minNeighbors=cfg.face_min_neighbors,
262
+ minSize=cfg.face_min_size
263
+ )
264
+ if len(detected) > 0:
265
+ faces.extend(detected.tolist())
266
  except Exception as e:
267
  print(f"[AI] Face detection failed or cascades unavailable: {e}")
268
 
 
269
  faces = [f for f in faces if f[1] < h * cfg.face_max_y_ratio]
 
 
270
  faces = _nms_faces(faces, cfg.face_nms_iou_thresh)
271
+ max_faces = getattr(cfg, 'face_max_count', 6)
272
+ if len(faces) > max_faces:
273
+ faces = sorted(faces, key=lambda f: f[2] * f[3], reverse=True)[:max_faces]
274
  return faces
275
 
276
+
277
 
278
  def build_subject_mask(rgb: np.ndarray, cfg: LineartConfig, alpha_channel: Optional[np.ndarray] = None) -> np.ndarray:
 
279
  if alpha_channel is not None:
 
280
  mask = (alpha_channel > 30).astype(np.uint8) * 255
281
  else:
282
  white_mask = np.all(rgb > cfg.white_bg_threshold, axis=2)
 
287
  return mask
288
 
289
 
290
+ def _smooth_contour_spline(cnt: np.ndarray, n_points: int = 400) -> Optional[np.ndarray]:
291
+ if not _SCIPY_AVAILABLE:
292
+ return None
293
+ pts = cnt[:, 0, :]
294
+ if len(pts) < 4:
295
+ return None
296
+ try:
297
+ tck, _ = splprep([pts[:, 0].astype(float), pts[:, 1].astype(float)],
298
+ s=len(pts) * 0.5, per=True, quiet=True)
299
+ u_new = np.linspace(0, 1, n_points)
300
+ x_new, y_new = splev(u_new, tck)
301
+ spline_pts = np.stack([x_new, y_new], axis=1).astype(np.int32)
302
+ return spline_pts.reshape((-1, 1, 2))
303
+ except Exception:
304
+
305
+
306
+ return None
307
+
308
+
309
  def build_silhouette(subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
 
310
  mask = subject_mask.copy()
 
 
311
  if cfg.mask_smooth_ksize > 1:
312
+ k = max(21, cfg.mask_smooth_ksize if cfg.mask_smooth_ksize % 2 == 1 else cfg.mask_smooth_ksize + 1)
 
313
  mask = cv2.GaussianBlur(mask, (k, k), 0)
314
  _, mask = cv2.threshold(mask, cfg.mask_smooth_threshold, 255, cv2.THRESH_BINARY)
315
+ k_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (9, 9))
316
+ mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, k_close, iterations=2)
317
 
318
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
319
  silhouette = np.zeros_like(subject_mask)
320
  for cnt in contours:
321
+ if cv2.contourArea(cnt) < cfg.min_silhouette_area:
322
+ continue
323
+ smooth = _smooth_contour_spline(cnt)
324
+ if smooth is not None:
325
+ cv2.polylines(silhouette, [smooth], isClosed=True,
326
+ color=255, thickness=cfg.silhouette_line_thickness,
327
+ lineType=cv2.LINE_AA)
328
+ else:
329
+ eps = 0.0003 * cv2.arcLength(cnt, True)
330
+ approx = cv2.approxPolyDP(cnt, eps, True)
331
+ cv2.drawContours(silhouette, [approx], -1, 255,
332
+ cfg.silhouette_line_thickness, lineType=cv2.LINE_AA)
333
  return silhouette
334
 
335
 
336
  def build_face_erase_mask(faces: list, shape: Tuple[int, int], cfg: LineartConfig) -> np.ndarray:
 
337
  h, w = shape
338
  mask = np.zeros((h, w), dtype=np.uint8)
339
  for (fx, fy, fw, fh) in faces:
 
346
  return (soft > cfg.face_erase_threshold).astype(np.uint8) * 255
347
 
348
 
349
+ def _line_strength_from_detector(pil_lineart: Image.Image, target_hw: Tuple[int, int]) -> np.ndarray:
350
+ """
351
+ Convert the detector output into a polarity-normalised "line strength" map
352
+ where lines = bright (255) on a black (0) background, resized to target.
353
+ Handles either polarity (black-on-white or white-on-black).
354
+ """
355
+ h, w = target_hw
356
+ gray = np.array(pil_lineart.convert("L"))
357
+ # Determine background from the image corners
358
+ corners = [gray[0, 0], gray[0, -1], gray[-1, 0], gray[-1, -1]]
359
+ bg = float(np.median(corners))
360
+ if bg > 127:
361
+ strength = 255 - gray # dark lines on light bg -> invert
362
+ else:
363
+ strength = gray # already light lines on dark bg
364
+ if strength.shape[:2] != (h, w):
365
+ strength = cv2.resize(strength, (w, h), interpolation=cv2.INTER_LINEAR)
366
+ return strength.astype(np.uint8)
367
+
368
+
369
+
370
  def build_interior_edges(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
371
+ """
372
+ Detect structural lines (clothing folds, lapels, collars, cuffs, hair) using
373
+ the neural LineartDetector. Produces continuous, illustrator-style strokes.
374
+ Falls back to the legacy Canny pipeline if controlnet_aux is unavailable.
375
+ """
376
+ h, w = rgb.shape[:2]
377
+ detector = get_lineart_detector()
378
+
379
+ if detector is not None:
380
+ try:
381
+ pil_in = Image.fromarray(rgb)
382
+ with _LINEART_LOCK:
383
+ pil_out = detector(
384
+ pil_in,
385
+ detect_resolution=cfg.lineart_detect_resolution,
386
+ image_resolution=cfg.lineart_image_resolution,
387
+ coarse=cfg.lineart_coarse,
388
+ )
389
+ strength = _line_strength_from_detector(pil_out, (h, w))
390
+
391
+ # Threshold to a binary line map
392
+ _, edges = cv2.threshold(strength, cfg.lineart_threshold, 255, cv2.THRESH_BINARY)
393
+
394
+ # Keep lines only inside the subject. Use a SMALL erosion so that
395
+ # face-shape, hairline and jaw lines (which sit close to the
396
+ # silhouette) are preserved instead of being eaten away.
397
+ erode_size = getattr(cfg, 'interior_erode_size', 3)
398
+ erode_size = max(1, erode_size)
399
+ if erode_size % 2 == 0:
400
+ erode_size += 1
401
+ kernel_erode = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (erode_size, erode_size))
402
+ eroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)
403
+ edges = cv2.bitwise_and(edges, eroded_mask)
404
+
405
+ # Remove speckle: drop tiny contours
406
+ contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
407
+ filtered = np.zeros_like(edges)
408
+ for cnt in contours:
409
+ if cv2.arcLength(cnt, False) < cfg.lineart_min_perimeter:
410
+ continue
411
+ cv2.drawContours(filtered, [cnt], -1, 255, cfg.interior_line_thickness)
412
+
413
+ # Gentle dilation for solid, embroiderable strokes
414
+ kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
415
+ filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)
416
+ filtered = cv2.GaussianBlur(filtered, (3, 3), 0)
417
+ filtered = cv2.threshold(filtered, 127, 255, cv2.THRESH_BINARY)
418
+ return filtered
419
+ except Exception as e:
420
+ print(f"[AI] Neural lineart failed, fallink back to Canny: {e}")
421
+
422
+ # ---------------- Legacy Canny fallback ----------------
423
+ return _build_interior_edges_canny(rgb, subject_mask, cfg)
424
+
425
+
426
+ def _build_interior_edges_canny(rgb: np.ndarray, subject_mask: np.ndarray, cfg: LineartConfig) -> np.ndarray:
427
  gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY)
428
+ blurred = cv2.bilateralFilter(gray, cfg.bilateral_d, cfg.bilateral_sigma_color, cfg.bilateral_sigma_space)
429
+ blurred = cv2.GaussianBlur(blurred, (cfg.gaussian_ksize, cfg.gaussian_ksize), 0)
430
  edges = cv2.Canny(blurred, cfg.canny_low, cfg.canny_high)
431
+
 
432
  erode_size = max(5, cfg.silhouette_line_thickness * 2 + 3)
433
  if erode_size % 2 == 0:
434
  erode_size += 1
 
436
  eroded_mask = cv2.erode(subject_mask, kernel_erode, iterations=1)
437
  edges = cv2.bitwise_and(edges, eroded_mask)
438
 
 
439
  contours, _ = cv2.findContours(edges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
440
  filtered = np.zeros_like(edges)
441
  for cnt in contours:
442
  perimeter = cv2.arcLength(cnt, False)
443
+ if perimeter < cfg.min_contour_perimeter:
444
+ continue
445
+ eps = 0.0012 * perimeter
446
+ smooth = cv2.approxPolyDP(cnt, eps, False)
447
+ cv2.drawContours(filtered, [smooth], -1, 255, cfg.interior_line_thickness)
 
 
448
  kernel_dilate = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
449
  filtered = cv2.dilate(filtered, kernel_dilate, iterations=1)
450
  return filtered
451
 
452
 
453
+
454
  _LANDMARKER_LOCK = threading.Lock()
455
  _LANDMARKER_CACHE = None
456
+ _LANDMARKER_NUM_FACES = None
457
 
458
+ def get_landmarker(model_path, num_faces: int = 6):
459
+ global _LANDMARKER_CACHE, _LANDMARKER_NUM_FACES
460
+ if _LANDMARKER_CACHE is None or _LANDMARKER_NUM_FACES != num_faces:
461
  import mediapipe as mp
462
  from mediapipe.tasks import python
463
  from mediapipe.tasks.python import vision
 
464
  base_options = python.BaseOptions(model_asset_path=model_path)
465
  options = vision.FaceLandmarkerOptions(
466
  base_options=base_options,
467
  output_face_blendshapes=False,
468
  output_facial_transformation_matrixes=False,
469
+ num_faces=num_faces,
470
+ # Lower confidence thresholds so smiling / tilted / smaller faces
471
+ # are still detected and their eyebrows get drawn.
472
+ min_face_detection_confidence=0.2,
473
+ min_face_presence_confidence=0.2,
474
+ min_tracking_confidence=0.2,
475
  )
476
  _LANDMARKER_CACHE = vision.FaceLandmarker.create_from_options(options)
477
+ _LANDMARKER_NUM_FACES = num_faces
478
  return _LANDMARKER_CACHE
479
 
480
 
481
  def draw_eyebrows(rgb: np.ndarray, cfg: LineartConfig, faces: Optional[list] = None) -> np.ndarray:
 
482
  h, w, _ = rgb.shape
483
  eyebrows_layer = np.zeros((h, w), dtype=np.uint8)
 
484
  try:
485
  import mediapipe as mp
 
 
486
 
 
487
  model_path = cfg.mediapipe_model_path
488
  if not model_path or not os.path.exists(model_path):
489
  model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "models")
 
493
  print("[AI] Downloading face_landmarker.task for eyebrows...")
494
  model_url = "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task"
495
  urllib.request.urlretrieve(model_url, model_path)
 
496
 
497
+ LEFT_EYEBROW = [70, 63, 105, 66, 107, 55, 65, 52, 53, 46]
498
  RIGHT_EYEBROW = [336, 296, 334, 293, 300, 285, 295, 282, 283, 276]
499
+ # MediaPipe face oval (head/jaw outline), ordered around the perimeter.
500
+ FACE_OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288,
501
+ 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136,
502
+ 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109]
503
+
504
+ eyebrow_thickness = getattr(cfg, 'eyebrow_thickness', cfg.interior_line_thickness)
505
+ draw_oval = True
506
+ oval_thickness = getattr(cfg, 'face_oval_thickness', 2)
507
+ oval_skip_top = getattr(cfg, 'face_oval_skip_top_ratio', 0.18)
508
+ drawn_centers_px: list = []
509
+
510
+ def is_duplicate_px(cx_px: float, cy_px: float) -> bool:
511
+ min_dist = min(w, h) * 0.06
512
+ for (pcx, pcy) in drawn_centers_px:
513
+ if np.hypot(cx_px - pcx, cy_px - pcy) < min_dist:
514
  return True
515
  return False
516
 
517
+ def draw_eyebrow_landmarks(face_lms, origin_x, origin_y, scale_x, scale_y):
518
+ # Eyebrows
519
+ for indices in [LEFT_EYEBROW, RIGHT_EYEBROW]:
520
+ pts = []
521
+ for idx in indices:
522
+ lm = face_lms[idx]
523
+ px = int(origin_x + lm.x * scale_x)
524
+ py = int(origin_y + lm.y * scale_y)
525
+ pts.append([px, py])
526
+ pts_np = np.array(pts, np.int32).reshape((-1, 1, 2))
527
+ cv2.polylines(eyebrows_layer, [pts_np], isClosed=False, color=255,
528
+ thickness=eyebrow_thickness, lineType=cv2.LINE_AA)
529
+
530
+ # Face oval (head / jaw outline) — gives the "formato do rosto"
531
+ if draw_oval:
532
+ oval_pts = []
533
+ for idx in FACE_OVAL:
534
+ lm = face_lms[idx]
535
+ px = int(origin_x + lm.x * scale_x)
536
+ py = int(origin_y + lm.y * scale_y)
537
+ oval_pts.append([px, py])
538
+ oval_np = np.array(oval_pts, np.int32)
539
+
540
+ if len(oval_np) >= 4:
541
+ # LÓGICA REVISADA: Focar apenas no terço inferior (queixo/maxilar)
542
+ y_min = oval_np[:, 1].min()
543
+ y_max = oval_np[:, 1].max()
544
+
545
+ # Corta os 60% superiores do rosto (mantém apenas o "U" inferior)
546
+ cutoff = y_min + (y_max - y_min) * 0.60
547
+
548
+ kept = oval_np[oval_np[:, 1] >= cutoff]
549
+
550
+ if len(kept) >= 4:
551
+ # Ordena os pontos da esquerda para a direita para evitar o polígono maluco
552
+ kept = kept[np.argsort(kept[:, 0])]
553
+ arc = kept.reshape((-1, 1, 2))
554
+
555
+ # Desenha o maxilar sem fechar a forma
556
+ cv2.polylines(eyebrows_layer, [arc], isClosed=False,
557
+ color=255, thickness=oval_thickness,
558
+ lineType=cv2.LINE_AA)
559
+ else:
560
+ cv2.polylines(eyebrows_layer, [oval_np.reshape((-1, 1, 2))],
561
+ isClosed=True, color=255,
562
+ thickness=oval_thickness, lineType=cv2.LINE_AA)
563
+
564
  if faces is None:
565
  faces = detect_faces(rgb, cfg)
566
 
567
  with _LANDMARKER_LOCK:
568
+ num_faces = getattr(cfg, 'mediapipe_num_faces', 6)
569
+ landmarker = get_landmarker(model_path, num_faces=num_faces)
570
+
571
  mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
572
  global_result = landmarker.detect(mp_image)
573
  if global_result.face_landmarks:
574
+ for face_lms in global_result.face_landmarks:
575
+ cx_px = np.mean([lm.x for lm in face_lms]) * w
576
+ cy_px = np.mean([lm.y for lm in face_lms]) * h
577
+ if not is_duplicate_px(cx_px, cy_px):
578
+ drawn_centers_px.append((cx_px, cy_px))
579
+ draw_eyebrow_landmarks(face_lms, 0, 0, w, h)
580
+
581
+ for (fx, fy, fw, fh) in faces:
582
+ mx = int(fw * 0.50); my = int(fh * 0.50)
583
+ x1 = max(0, fx - mx); y1 = max(0, fy - my)
584
+ x2 = min(w, fx + fw + mx); y2 = min(h, fy + fh + my)
585
+ crop_w, crop_h = x2 - x1, y2 - y1
586
+ if crop_w < 20 or crop_h < 20:
 
 
 
 
 
 
 
 
 
 
 
 
 
587
  continue
588
+ face_cx_px = (x1 + x2) / 2; face_cy_px = (y1 + y2) / 2
589
+ if is_duplicate_px(face_cx_px, face_cy_px):
 
 
590
  continue
 
591
  crop = rgb[y1:y2, x1:x2]
592
+ target = max(512, crop_w, crop_h)
593
+ scale = target / max(crop_w, crop_h)
594
+ cw_scaled = int(crop_w * scale); ch_scaled = int(crop_h * scale)
595
+ crop_resized = cv2.resize(crop, (cw_scaled, ch_scaled), interpolation=cv2.INTER_CUBIC)
596
  crop_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=crop_resized)
597
  crop_result = landmarker.detect(crop_image)
 
598
  if crop_result.face_landmarks:
599
+ face_lms = crop_result.face_landmarks[0]
600
+ cx_px2 = x1 + np.mean([lm.x for lm in face_lms]) * crop_w
601
+ cy_px2 = y1 + np.mean([lm.y for lm in face_lms]) * crop_h
602
+ if is_duplicate_px(cx_px2, cy_px2):
603
+ continue
604
+ drawn_centers_px.append((cx_px2, cy_px2))
605
+ draw_eyebrow_landmarks(face_lms, x1, y1, crop_w, crop_h)
606
+
607
+ print(f"[eyebrows] Drew eyebrows for {len(drawn_centers_px)} face(s)")
 
 
 
 
 
 
608
  except Exception as e:
609
  print(f"[AI] Eyebrow extraction error or library missing: {e}")
610
 
611
+ if eyebrows_layer.any():
612
+ dil = getattr(cfg, 'eyebrow_dilate', 1)
613
+ if dil > 0:
614
+ kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
615
+ eyebrows_layer = cv2.dilate(eyebrows_layer, kernel, iterations=dil)
616
  return eyebrows_layer
617
 
618
 
619
+ def make_faceless_lineart(img: Image.Image, cfg: LineartConfig = None) -> Image.Image:
 
 
 
 
 
 
 
620
  cfg = cfg or LineartConfig()
621
+
 
622
  alpha_channel: Optional[np.ndarray] = None
623
  if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
624
  rgba_img = img.convert("RGBA")
625
  alpha_np = np.array(rgba_img)[:, :, 3]
 
626
  if np.any(alpha_np < 200):
627
  alpha_channel = alpha_np
628
  background = Image.new("RGBA", img.size, (255, 255, 255, 255))
 
635
  rgb = img_np[:, :, :3]
636
  h, w = rgb.shape[:2]
637
 
638
+ # If no alpha was provided, derive a subject mask with rembg for a clean
639
+ # silhouette and to confine interior lines to the subject.
640
+ if alpha_channel is None and _SESSION_ISNET is not None:
641
+ try:
642
+ cut = remove(Image.fromarray(rgb).convert("RGBA"), session=_SESSION_ISNET, only_mask=True)
643
+ cut_l = cut.convert("L") if isinstance(cut, Image.Image) else Image.open(io.BytesIO(cut)).convert("L")
644
+ if cut_l.size != (w, h):
645
+ cut_l = cut_l.resize((w, h), Image.LANCZOS)
646
+ alpha_channel = np.array(cut_l)
647
+ except Exception as e:
648
+ print(f"[AI] rembg mask for lineart failed: {e}")
649
 
650
+ subject_mask = build_subject_mask(rgb, cfg, alpha_channel)
651
  faces = detect_faces(rgb, cfg)
652
  print(f"[lineart] Detected {len(faces)} face(s)")
653
 
 
654
  silhouette = build_silhouette(subject_mask, cfg)
 
 
655
  interior = build_interior_edges(rgb, subject_mask, cfg)
656
 
 
657
  face_erase = build_face_erase_mask(faces, (h, w), cfg)
658
  interior_clean = cv2.bitwise_and(interior, cv2.bitwise_not(face_erase))
659
 
 
660
  final_lines = cv2.add(silhouette, interior_clean)
661
 
 
662
  if cfg.detect_eyebrows:
663
  eyebrows = draw_eyebrows(rgb, cfg, faces=faces)
664
  final_lines = cv2.add(final_lines, eyebrows)
665
 
 
666
  border_erase_width = max(cfg.silhouette_line_thickness, cfg.interior_line_thickness) + 2
667
  if border_erase_width > 0:
668
  final_lines[0:border_erase_width, :] = 0
 
670
  final_lines[:, 0:border_erase_width] = 0
671
  final_lines[:, -border_erase_width:] = 0
672
 
 
 
673
  alpha = Image.fromarray(final_lines)
674
+ transparent = Image.new("RGBA", img.size, (0, 0, 0, 0))
 
 
675
  transparent.putalpha(alpha)
 
676
  return transparent
677
 
678
 
 
700
  return total > 0 and (visible / total) >= 0.03
701
 
702
 
703
+
704
+
705
+
706
+
707
+
708
  def remove_background_subject(img: Image.Image) -> Image.Image:
709
  try:
710
  rgba = img.convert("RGBA")
711
  if _has_real_transparency(rgba):
712
  return rgba
 
713
  if _SESSION_ISNET is None:
714
  return rgba
 
715
  mask = remove(rgba, session=_SESSION_ISNET, only_mask=True)
716
  alpha = mask.convert("L") if isinstance(mask, Image.Image) else Image.open(io.BytesIO(mask)).convert("L")
717
  if alpha.size != rgba.size:
718
  alpha = alpha.resize(rgba.size, Image.LANCZOS)
719
  alpha = alpha.filter(ImageFilter.GaussianBlur(radius=0.8))
 
720
  r, g, b, _a = rgba.split()
721
  return Image.merge("RGBA", (r, g, b, alpha))
722
  except Exception as exc:
 
728
  return remove_background_subject(img)
729
 
730
 
731
+ def build_faceless_embroidery_assets(img: Image.Image, cfg: Optional[LineartConfig] = None, **kwargs) -> Tuple[Image.Image, Image.Image]:
 
 
 
 
732
  if cfg is None:
733
  cfg = LineartConfig()
734
  if "prompt" in kwargs and kwargs["prompt"] is not None:
735
  cfg.prompt = kwargs["prompt"]
736
  if "negative_prompt" in kwargs and kwargs["negative_prompt"] is not None:
737
  cfg.negative_prompt = kwargs["negative_prompt"]
 
738
  lineart = make_faceless_lineart(img, cfg)
739
  cutout = make_faceless_cutout(img)
740
+ return lineart, cutout