Download project/scripts/cave_badcase_refinement.py from xiaojie06/CaveWorld3D: direct link, hf CLI and curl.
- Browser
- Download file 7.65 kB
-
https://huggingface.co/xiaojie06/CaveWorld3D/resolve/main/project/scripts/cave_badcase_refinement.py
- Command line
-
hf download hf://xiaojie06/CaveWorld3D/project/scripts/cave_badcase_refinement.py
-
curl -L -o cave_badcase_refinement.py https://huggingface.co/xiaojie06/CaveWorld3D/resolve/main/project/scripts/cave_badcase_refinement.py
7.65 kB
| """Input-only proposals and a bounded, identity-initialized alignment and appearance adapter.""" | |
| import cv2 | |
| import numpy as np | |
| import torch | |
| from scipy.spatial import cKDTree | |
| from torch import nn | |
| from torch.nn import functional as F | |
| def bytes_(a): | |
| return np.rint(np.clip(a, 0, 255)).astype("uint8") | |
| def donor_texture(base, guide, known): | |
| """Match patches inside the visible photograph by local colour, structure tensor and position.""" | |
| h, w = known.shape | |
| reference = np.where(known[..., None], guide, base) | |
| if min(h, w) < 31 or known.sum() < 900: | |
| return base.copy(), np.zeros((h, w), "uint8") | |
| radius = 12 | |
| def descriptor(im, pts): | |
| y, x = pts.T | |
| rgb = im.astype("f4") / 255 | |
| low = cv2.blur(rgb, (13, 13)) | |
| gray = cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY) | |
| dx = cv2.Sobel(gray, -1, 1, 0, ksize=3) * 0.125 | |
| dy = cv2.Sobel(gray, -1, 0, 1, ksize=3) * 0.125 | |
| tensor = cv2.blur(np.stack([dx * dx, dy * dy, dx * dy], -1), (19, 19)) | |
| e = tensor[y, x] | |
| power = e[:, :2].sum(1) + 0.0002 | |
| return np.column_stack( | |
| [ | |
| low[y, x] * 2, | |
| *[ | |
| (low[y + oy, x + ox] - low[y, x]).mean(1) * 1.5 | |
| for oy, ox in ((-7, 0), (7, 0), (0, -7), (0, 7)) | |
| ], | |
| 0.26 * (e[:, 0] - e[:, 1]) / power, | |
| 0.38 * e[:, 2] / power, | |
| 1.6 * np.sqrt(power), | |
| 0.16 * y / h, | |
| 0.16 * x / w, | |
| ] | |
| ) | |
| def grid(step): | |
| gy = np.unique(np.r_[np.arange(radius, h - radius, step), h - radius - 1]) | |
| gx = np.unique(np.r_[np.arange(radius, w - radius, step), w - radius - 1]) | |
| return np.stack(np.meshgrid(gy, gx, indexing="ij"), -1).reshape(-1, 2) | |
| full = cv2.erode( | |
| known.astype("u1"), | |
| np.ones((25, 25), "u1"), | |
| borderType=cv2.BORDER_CONSTANT, | |
| borderValue=0, | |
| ) | |
| src = grid(8) | |
| src = src[full[tuple(src.T)] > 0] | |
| target = grid(15) | |
| target = target[~(full[tuple(target.T)] > 0)] | |
| if len(src) < 3 or not len(target): | |
| return base.copy(), np.zeros((h, w), "u1") | |
| dist, ix = cKDTree(descriptor(reference, src)).query(descriptor(base, target)) | |
| weight = np.maximum(0.015, np.outer(np.hanning(25), np.hanning(25))).astype("f4") | |
| accum = np.zeros_like(base, dtype="f4") | |
| quality = np.zeros((h, w), "f4") | |
| norm = quality.copy() | |
| for (y, x), (sy, sx), dis in zip(target, src[ix], dist): | |
| dest = np.s_[y - 12 : y + 13, x - 12 : x + 13] | |
| accum[dest] += ( | |
| reference[sy - 12 : sy + 13, sx - 12 : sx + 13] * weight[..., None] | |
| ) | |
| norm[dest] += weight | |
| quality[dest] += weight * np.exp(-2.7 * dis) | |
| donor = bytes_(accum / np.maximum(norm[..., None], 1.0e-7)) | |
| donor[norm == 0] = base[norm == 0] | |
| return donor, bytes_(255 * quality / np.maximum(norm, 1.0e-7)) | |
| def flow_donor(anchor, donor, limit): | |
| """Warp using the two predicted views. Forward/backward consistency suppresses new occlusions.""" | |
| h, w = anchor.shape[:2] | |
| size = (max(16, w // 2), max(16, h // 2)) | |
| a, b = [ | |
| cv2.resize( | |
| cv2.cvtColor(v, cv2.COLOR_RGB2GRAY), size, interpolation=cv2.INTER_AREA | |
| ) | |
| for v in (anchor, donor) | |
| ] | |
| dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_FAST) | |
| dis.setFinestScale(0) | |
| forward = dis.calc(a, b, None) | |
| back = dis.calc(b, a, None) | |
| yy, xx = np.indices(a.shape, dtype="f4") | |
| rx = xx + forward[..., 0] | |
| ry = yy + forward[..., 1] | |
| residual = np.linalg.norm( | |
| forward | |
| + cv2.remap(back, rx, ry, cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE), | |
| axis=-1, | |
| ) | |
| valid = (rx >= 0) & (ry >= 0) & (rx <= size[0] - 1) & (ry <= size[1] - 1) | |
| scale = np.array([w / size[0], h / size[1]], "f4") | |
| flow = cv2.resize(forward, (w, h)) * scale | |
| length = np.linalg.norm(flow, axis=-1) | |
| yy, xx = np.indices((h, w), dtype="f4") | |
| warped = cv2.remap( | |
| donor, | |
| xx + flow[..., 0], | |
| yy + flow[..., 1], | |
| cv2.INTER_LINEAR, | |
| borderMode=cv2.BORDER_REPLICATE, | |
| ) | |
| gap = cv2.blur(np.abs(anchor.astype("f4") - warped).mean(2), (9, 9)) | |
| q = ( | |
| cv2.resize(np.exp(-(residual**2) / 2.5) * valid, (w, h)) | |
| * np.exp(-gap / 42) | |
| * (length < limit) | |
| ) | |
| return warped, bytes_(255 * q) | |
| def pack(base, alternate, donor, confidence, keep): | |
| if keep is not None and keep.any(): | |
| distance = cv2.distanceTransform((~keep).astype("u1"), cv2.DIST_L2, 5) | |
| distance = bytes_(255 * distance / max(1, 0.5 * min(keep.shape))) | |
| else: | |
| distance = np.full(base.shape[:2], 255, "u1") | |
| return np.ascontiguousarray( | |
| np.dstack([base, alternate, donor, confidence, distance]) | |
| ) | |
| def tensor(im): | |
| return ( | |
| torch.as_tensor(np.ascontiguousarray(im), device="cuda") | |
| .permute(2, 0, 1) | |
| .float() | |
| / 255 | |
| ) | |
| def blur(x, k): | |
| return F.avg_pool2d(F.pad(x, (k // 2,) * 4, mode="replicate"), k, 1) | |
| class PatchRefinement(nn.Module): | |
| def __init__(self): | |
| super().__init__() | |
| self.encode = nn.Sequential( | |
| nn.Conv2d(20, 24, 3, padding=1), | |
| nn.SiLU(), | |
| nn.Conv2d(24, 24, 3, padding=2, dilation=2), | |
| nn.SiLU(), | |
| nn.Conv2d(24, 24, 3, padding=4, dilation=4), | |
| nn.SiLU(), | |
| nn.Conv2d(24, 12, 1), | |
| ) | |
| nn.init.zeros_(self.encode[-1].weight) | |
| nn.init.zeros_(self.encode[-1].bias) | |
| def forward(self, x): | |
| base, alt, donor = x[:, :3], x[:, 3:6], x[:, 6:9] | |
| q = x[:, 9:10] | |
| mid = blur(x[:, :9], 5) | |
| hi = x[:, :9] - mid | |
| feat = torch.cat([x, hi.abs() * 3], 1) | |
| coarse = F.avg_pool2d(feat, 4, 4, ceil_mode=True) | |
| ctrl = F.interpolate( | |
| self.encode(coarse), size=x.shape[-2:], mode="bilinear", align_corners=False | |
| ).tanh() | |
| # Predicted displacement applies only to the candidate donor, never to the real input pixels. | |
| b, _, h, w = x.shape | |
| yy, xx = torch.meshgrid( | |
| torch.arange(h, device=x.device, dtype=x.dtype), | |
| torch.arange(w, device=x.device, dtype=x.dtype), | |
| indexing="ij", | |
| ) | |
| grid = torch.stack( | |
| [ | |
| 2 * (xx[None] + 3 * ctrl[:, 0] + 0.5) / w - 1, | |
| 2 * (yy[None] + 3 * ctrl[:, 1] + 0.5) / h - 1, | |
| ], | |
| -1, | |
| ) | |
| donor = F.grid_sample( | |
| donor, grid, mode="bilinear", padding_mode="border", align_corners=False | |
| ) | |
| dl = blur(donor, 15) | |
| dm = blur(donor, 5) | |
| bl = blur(base, 15) | |
| al = blur(alt, 15) | |
| low = base + (al - bl) * ctrl[:, 2:3] + 0.45 * q * (dl - bl) * ctrl[:, 3:4] | |
| band_a = mid[:, 3:6] - al - (mid[:, :3] - bl) | |
| band_d = dm - dl - (mid[:, :3] - bl) | |
| high_d = donor - dm | |
| out = low + band_a * ctrl[:, 4:5] + q * band_d * ctrl[:, 5:6] | |
| out = ( | |
| out | |
| + ctrl[:, 6:7] * (hi[:, 3:6] - hi[:, :3]) | |
| + q * ctrl[:, 7:8] * (high_d - hi[:, :3]) | |
| ) | |
| out = out + 0.50 * ctrl[:, 8:9] * hi[:, :3] + 0.095 * ctrl[:, 9:12] | |
| return out.clamp(0, 1) | |
| def predict(net, x, amount, keep): | |
| if not amount: | |
| return x[:, :, :3].copy() | |
| a = tensor(x)[None] | |
| y = torch.lerp(a[:, :3], net(a), float(amount)) | |
| data = (y[0].permute(1, 2, 0) * 255).round().clamp(0, 255).byte().cpu().numpy() | |
| if keep is not None: | |
| data[keep] = x[:, :, :3][keep] | |
| return data | |