File size: 1,590 Bytes
d3b61f8 | 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 | from dataclasses import dataclass
import math
import torch
@dataclass(frozen=True)
class Layout:
width: int
height: int
stride: int = 32
subdivisions: int = 32
def __post_init__(self):
if min(self.width, self.height) < 1 or self.stride != 32:
raise ValueError('Positive image dimensions and the native 32-pixel stride required')
if self.subdivisions < 1 or self.stride % self.subdivisions:
raise ValueError('Subdivisions must divide the native stride')
@property
def cols(self):
return math.ceil(self.width / self.stride)
@property
def rows(self):
return math.ceil(self.height / self.stride)
@property
def count(self):
return self.rows * self.cols
@property
def canvas_size(self):
return self.cols * self.stride, self.rows * self.stride
@property
def fine_count(self):
return self.subdivisions**2
def positions(self, device=None):
parent = torch.arange(self.count, device=device)
fine = torch.arange(self.fine_count, device=device)
unit = self.stride / self.subdivisions
horizontal = (parent[:, None] % self.cols) * self.stride + (fine[None] % self.subdivisions + .5) * unit
vertical = (parent[:, None] // self.cols) * self.stride + (fine[None] // self.subdivisions + .5) * unit
return torch.stack((horizontal, vertical), -1)
def valid(self, device=None):
positions = self.positions(device)
return (positions[..., 0] < self.width) & (positions[..., 1] < self.height)
|