File size: 1,094 Bytes
f877698
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
fb3460f
 
 
 
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
import numpy as np
import torch


class PilResize:
    def __init__(self, width: int = 518, multiple: int = 14):
        self.width, self.multiple = int(width), int(multiple)

    def size(self, w: int, h: int) -> tuple:
        return self.width, round(h * (self.width / w) / self.multiple) * self.multiple

    def __call__(self, frames_u8):
        from PIL import Image
        from torchvision import transforms as TF
        frames = np.asarray(frames_u8)
        if frames.dtype != np.uint8 or frames.ndim != 4 or frames.shape[-1] != 3:
            raise ValueError('Expected (N, H, W, 3) uint8 frames')
        to_tensor, out = TF.ToTensor(), []
        for frame in frames:
            image = Image.fromarray(frame).convert('RGB')
            image = image.resize(self.size(*image.size), Image.Resampling.BICUBIC)
            tensor = to_tensor(image)
            if tensor.shape[1] > self.width:
                start = (tensor.shape[1] - self.width) // 2
                tensor = tensor[:, start:start + self.width, :]
            out.append(tensor)
        return torch.stack(out)