File size: 2,842 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
57
58
59
60
61
62
63
64
65
66
67
from __future__ import annotations

import numpy as np

from .camera import PinholeCamera
from .compose import to_uint8
from .protocol import GRID_518x294

DIRECT = 'direct_anisotropic_full_frame'


def resize_float(values: np.ndarray, width: int, height: int, *, batched: bool = False) -> np.ndarray:
    import torch
    import torch.nn.functional as F
    x = np.asarray(values)
    if x.dtype != np.float32:
        raise ValueError(f'resize expects float32 input, got {x.dtype}')
    if x.ndim != (3 if batched else 2) and x.ndim != (4 if batched else 3):
        raise ValueError(f'Unsupported layout {x.shape} (batched={batched})')
    t = torch.from_numpy(np.ascontiguousarray(x))
    if not batched:
        t = t[None]
    channels = t.ndim == 4
    t = t.permute(0, 3, 1, 2) if channels else t[:, None]
    with torch.inference_mode():
        y = F.interpolate(t, size=(int(height), int(width)), mode='bilinear', antialias=True, align_corners=False)
    y = y.permute(0, 2, 3, 1) if channels else y[:, 0]
    if not batched:
        y = y[0]
    return np.ascontiguousarray(y.numpy())


class ScoringGrid:
    def __init__(self, spec: dict | None = None):
        self.spec = dict(spec or GRID_518x294)
        self.width, self.height = int(self.spec['width']), int(self.spec['height'])
        self.geometry = self.spec['geometry']
        if self.geometry != DIRECT:
            raise ValueError('Unknown grid geometry: ' + self.geometry)
        self.threshold = float(self.spec['mask_threshold'])

    @property
    def label(self) -> str:
        return f'g{self.height}'

    def camera(self, native: PinholeCamera) -> PinholeCamera:
        sx, sy = self.width / native.width, self.height / native.height
        return PinholeCamera(self.width, self.height, native.fx * sx, native.fy * sy,
                             (native.cx + .5) * sx - .5, (native.cy + .5) * sy - .5)

    def continuous(self, layer: np.ndarray, *, batched: bool = False) -> np.ndarray:
        layer = np.asarray(layer, dtype=np.float32)
        return resize_float(layer, self.width, self.height, batched=batched)

    def rgb(self, frames_u8: np.ndarray) -> np.ndarray:
        frames = np.asarray(frames_u8)
        if frames.dtype != np.uint8 or frames.shape[-1] != 3 or frames.ndim not in (3, 4):
            raise ValueError('Expected uint8 RGB (N,)HxWx3')
        return to_uint8(self.continuous(frames.astype(np.float32) / 255, batched=frames.ndim == 4))

    def mask(self, mask: np.ndarray) -> np.ndarray:
        mask = np.asarray(mask)
        if mask.ndim not in (2, 3) or not np.isin(mask, (0, 1)).all():
            raise ValueError('Expected a binary (N,)HxW mask')
        resized = resize_float(mask.astype(np.float32), self.width, self.height, batched=mask.ndim == 3)
        return (resized >= self.threshold).astype(np.uint8)