Spaces:
Paused
Paused
File size: 1,894 Bytes
c97431f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | from __future__ import annotations
import cv2
import numpy as np
def normalize_vectors(vectors: np.ndarray) -> np.ndarray:
out = np.zeros_like(vectors, dtype=np.float32)
lengths = np.linalg.norm(vectors, axis=-1)
good = np.isfinite(vectors).all(axis=-1) & (lengths > 1e-6)
out[good] = vectors[good] / lengths[good, None]
return out
def smooth_normal_map(normals: np.ndarray, kernel_size: int) -> np.ndarray:
kernel_size = max(1, int(kernel_size)) | 1
smoothed = normals.astype(np.float32)
if kernel_size > 1:
smoothed = cv2.GaussianBlur(smoothed, (kernel_size, kernel_size), 0)
return normalize_vectors(smoothed)
def compute_normals_from_points(
points_map: np.ndarray,
valid_mask: np.ndarray,
smoothing_kernel: int,
) -> np.ndarray:
points = points_map.astype(np.float32).copy()
valid = valid_mask.astype(bool) & np.isfinite(points).all(axis=2)
if not valid.any():
return np.zeros_like(points, dtype=np.float32)
filled = points.copy()
for channel_idx in range(3):
channel = filled[:, :, channel_idx]
fill_value = float(np.median(channel[valid]))
channel[~valid] = fill_value
filled[:, :, channel_idx] = channel
kernel_size = max(1, int(smoothing_kernel)) | 1
if kernel_size > 1:
filled = cv2.GaussianBlur(filled, (kernel_size, kernel_size), 0)
dx = np.zeros_like(filled, dtype=np.float32)
dy = np.zeros_like(filled, dtype=np.float32)
dx[:, 1:-1] = filled[:, 2:] - filled[:, :-2]
dx[:, 0] = filled[:, 1] - filled[:, 0]
dx[:, -1] = filled[:, -1] - filled[:, -2]
dy[1:-1, :] = filled[2:, :] - filled[:-2, :]
dy[0, :] = filled[1, :] - filled[0, :]
dy[-1, :] = filled[-1, :] - filled[-2, :]
normals = normalize_vectors(np.cross(dx, dy))
normals[~valid] = 0.0
return smooth_normal_map(normals, smoothing_kernel)
|