Download code/agt/eval/hole.py from MRBSTUDIO/AGT: direct link, hf CLI and curl.
- Browser
- Download file 2.36 kB
-
https://huggingface.co/MRBSTUDIO/AGT/resolve/main/code/agt/eval/hole.py
- Command line
-
hf download hf://MRBSTUDIO/AGT/code/agt/eval/hole.py
-
curl -L -o hole.py https://huggingface.co/MRBSTUDIO/AGT/resolve/main/code/agt/eval/hole.py
2.36 kB
| from __future__ import annotations | |
| import math | |
| import numpy as np | |
| from scipy.ndimage import find_objects, label | |
| from .rgb import gt_float | |
| def component_boxes(mask, expansion=.1): | |
| mask = np.asarray(mask, bool) | |
| if mask.ndim != 2: | |
| raise ValueError('component boxes require a single HW mask') | |
| components, _ = label(mask, structure=np.ones((3, 3), bool)) | |
| boxes = [] | |
| for region in find_objects(components): | |
| y, x = region | |
| dy, dx = math.ceil((y.stop-y.start)*expansion), math.ceil((x.stop-x.start)*expansion) | |
| boxes.append((max(0, y.start-dy), min(mask.shape[0], y.stop+dy), | |
| max(0, x.start-dx), min(mask.shape[1], x.stop+dx))) | |
| return boxes | |
| class HoleScorer: | |
| def __init__(self, region_scorer): | |
| self.region = region_scorer | |
| self.device = region_scorer.device | |
| self._dists = None | |
| def dists(self, pred, gt): | |
| import torch | |
| import torch.nn.functional as F | |
| if self._dists is None: | |
| from DISTS_pytorch import DISTS | |
| self._dists = DISTS().eval().to(self.device) | |
| inputs = [] | |
| for array in (pred, gt): | |
| x = torch.from_numpy(np.ascontiguousarray(array.transpose(2, 0, 1))).to(self.device)[None] | |
| if min(x.shape[-2:]) < 32: | |
| scale = 32 / min(x.shape[-2:]) | |
| x = F.interpolate(x, size=[math.ceil(d*scale) for d in x.shape[-2:]], | |
| mode='bilinear', align_corners=False, antialias=True) | |
| inputs.append(x) | |
| with torch.inference_mode(): | |
| return float(self._dists(*inputs).item()) | |
| def score(self, pred, gt_u8, unobserved): | |
| pred, gt = np.clip(np.asarray(pred, np.float32), 0, 1), gt_float(gt_u8) | |
| pixels, lpips_sum, dists_sum, n_dists = 0, 0., 0., 0 | |
| for i, U in enumerate(unobserved): | |
| n = int(U.sum()) | |
| if not n: | |
| continue | |
| pixels += n | |
| lpips_sum += self.region.lpips_map(pred[i], gt[i], U, blackout=False) * n | |
| values = [self.dists(pred[i, y0:y1, x0:x1], gt[i, y0:y1, x0:x1]) for y0, y1, x0, x1 in component_boxes(U)] | |
| dists_sum += sum(values) | |
| n_dists += len(values) | |
| return dict(lpips=lpips_sum / pixels if pixels else None, dists=dists_sum / n_dists if n_dists else None) | |