75 lines
3.0 KiB
Python
75 lines
3.0 KiB
Python
import cv2
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn.functional as F
|
|
from torchvision import transforms
|
|
from face_parsing.model import BiSeNet
|
|
|
|
class FaceSegmenter:
|
|
# 19-Klassen Mapping (CelebAMask-HQ)
|
|
FACE_LABELS_NO_HAIR = {1,2,3,4,5,6,7,8,9,10,11,12,13}
|
|
FACE_LABELS_WITH_HAIR = {1,2,3,4,5,6,7,8,9,10,11,12,13,17}
|
|
MIN_COVERAGE = 0.01
|
|
|
|
def __init__(self, weight_path: str, device=None, input_size=512, include_hair=False):
|
|
"""
|
|
weight_path: Pfad zu 79999_iter.pth (CelebAMask-HQ, 19 Klassen)
|
|
"""
|
|
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
|
self.input_size = int(input_size)
|
|
self.include_hair = bool(include_hair)
|
|
|
|
|
|
self.net = BiSeNet(n_classes=19).to(self.device).eval()
|
|
|
|
state = torch.load(weight_path, map_location="cpu")
|
|
if isinstance(state, dict) and "state_dict" in state:
|
|
state = {k.replace("module.", ""): v for k, v in state["state_dict"].items()}
|
|
else:
|
|
state = {k.replace("module.", ""): v for k, v in state.items()}
|
|
self.net.load_state_dict(state, strict=False)
|
|
|
|
self.tf = transforms.Compose([
|
|
transforms.ToTensor(), # erwartet RGB (wir konvertieren vorher)
|
|
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
|
std=[0.229, 0.224, 0.225]),
|
|
])
|
|
|
|
def extract_face(self, face_roi_bgr: np.ndarray):
|
|
if face_roi_bgr is None or face_roi_bgr.size == 0:
|
|
raise ValueError("Eingabebild ist leer.")
|
|
if face_roi_bgr.ndim == 2:
|
|
face_roi_bgr = cv2.cvtColor(face_roi_bgr, cv2.COLOR_GRAY2BGR)
|
|
|
|
h, w = face_roi_bgr.shape[:2]
|
|
rgb = cv2.cvtColor(face_roi_bgr, cv2.COLOR_BGR2RGB)
|
|
rgb_resized = cv2.resize(rgb, (self.input_size, self.input_size), interpolation=cv2.INTER_LINEAR)
|
|
x = self.tf(rgb_resized).unsqueeze(0).to(self.device)
|
|
|
|
with torch.no_grad():
|
|
logits = self.net(x)
|
|
if isinstance(logits, (list, tuple)):
|
|
logits = logits[0]
|
|
logits = F.interpolate(logits, size=(self.input_size, self.input_size),
|
|
mode="bilinear", align_corners=False)
|
|
parsing = logits.argmax(1).squeeze(0).cpu().numpy().astype(np.uint8)
|
|
|
|
parsing = cv2.resize(parsing, (w, h), interpolation=cv2.INTER_NEAREST)
|
|
keep = self.FACE_LABELS_WITH_HAIR if self.include_hair else self.FACE_LABELS_NO_HAIR
|
|
mask = np.isin(parsing, list(keep)).astype(np.uint8)
|
|
mask_3 = np.repeat(mask[:, :, None], 3, axis=2)
|
|
|
|
out = np.zeros_like(face_roi_bgr, dtype=np.uint8)
|
|
out[mask_3 == 1] = face_roi_bgr[mask_3 == 1]
|
|
|
|
coverage = (cv2.cvtColor(out, cv2.COLOR_BGR2GRAY) > 0).mean()
|
|
if coverage < self.MIN_COVERAGE: # 1%
|
|
return None
|
|
return out
|
|
|
|
|
|
if __name__ == '__main__':
|
|
seg = FaceSegmenter(weight_path="/models/79999_iter.pth", include_hair=False)
|
|
face_only = seg.extract_face(cv2.imread("/test/face.jpg"))
|
|
cv2.imwrite("/test/face_only.png", face_only)
|