Spaces:
Sleeping
Sleeping
Create overlay.py
Browse files- overlay.py +37 -0
overlay.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
def _read_png_rgba(path):
|
5 |
+
png = cv2.imread(path, cv2.IMREAD_UNCHANGED)
|
6 |
+
if png is None or png.shape[2] != 4:
|
7 |
+
raise ValueError("Hairstyle PNG must be RGBA with transparency.")
|
8 |
+
return png
|
9 |
+
|
10 |
+
def auto_align(png_rgba, mask, landmarks=None):
|
11 |
+
mh, mw = mask.shape[:2]
|
12 |
+
ys, xs = np.where(mask > 0)
|
13 |
+
if len(xs) == 0 or len(ys) == 0:
|
14 |
+
return cv2.resize(png_rgba, (mw, mh))
|
15 |
+
x0, x1 = xs.min(), xs.max()
|
16 |
+
y0, y1 = ys.min(), ys.max()
|
17 |
+
tw, th = int((x1 - x0) * 1.1), int((y1 - y0) * 0.7)
|
18 |
+
tw = max(1, min(tw, mw))
|
19 |
+
th = max(1, min(th, mh))
|
20 |
+
aligned = cv2.resize(png_rgba, (tw, th))
|
21 |
+
canvas = np.zeros((mh, mw, 4), dtype=np.uint8)
|
22 |
+
y = max(0, y0 - int(0.25 * th))
|
23 |
+
x = max(0, x0 - int(0.05 * tw))
|
24 |
+
y2, x2 = min(mh, y + th), min(mw, x + tw)
|
25 |
+
canvas[y:y2, x:x2] = aligned[:(y2 - y), :(x2 - x)]
|
26 |
+
return canvas
|
27 |
+
|
28 |
+
def _alpha_blend(base_bgr, overlay_rgba):
|
29 |
+
bgr = base_bgr.copy()
|
30 |
+
alpha = overlay_rgba[:, :, 3:4] / 255.0
|
31 |
+
rgb = overlay_rgba[:, :, :3]
|
32 |
+
return (alpha * rgb + (1 - alpha) * bgr).astype(np.uint8)
|
33 |
+
|
34 |
+
def apply_hairstyle(img_bgr, style_path, mask, landmarks=None):
|
35 |
+
png = _read_png_rgba(style_path)
|
36 |
+
aligned = auto_align(png, mask, landmarks)
|
37 |
+
return _alpha_blend(img_bgr, aligned)
|