georgefen/Face-Landmark-ControlNet
116
1import cv22import numpy as np3import torch4 5from einops import rearrange6from .api import MiDaSInference7 8 9class MidasDetector:10 def __init__(self):11 self.model = MiDaSInference(model_type="dpt_hybrid").cuda()12 13 def __call__(self, input_image, a=np.pi * 2.0, bg_th=0.1):14 assert input_image.ndim == 315 image_depth = input_image16 with torch.no_grad():17 image_depth = torch.from_numpy(image_depth).float().cuda()18 image_depth = image_depth / 127.5 - 1.019 image_depth = rearrange(image_depth, 'h w c -> 1 c h w')20 depth = self.model(image_depth)[0]21 22 depth_pt = depth.clone()23 depth_pt -= torch.min(depth_pt)24 depth_pt /= torch.max(depth_pt)25 depth_pt = depth_pt.cpu().numpy()26 depth_image = (depth_pt * 255.0).clip(0, 255).astype(np.uint8)27 28 depth_np = depth.cpu().numpy()29 x = cv2.Sobel(depth_np, cv2.CV_32F, 1, 0, ksize=3)30 y = cv2.Sobel(depth_np, cv2.CV_32F, 0, 1, ksize=3)31 z = np.ones_like(x) * a32 x[depth_pt < bg_th] = 033 y[depth_pt < bg_th] = 034 normal = np.stack([x, y, z], axis=2)35 normal /= np.sum(normal ** 2.0, axis=2, keepdims=True) ** 0.536 normal_image = (normal * 127.5 + 127.5).clip(0, 255).astype(np.uint8)37 38 return depth_image, normal_image39 