MCPcopy Create free account
hub / github.com/ModelTC/LightX2V / FunctionalTensorMock

Class FunctionalTensorMock

tools/postprocess/torchvision_fix.py:17–64  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

15 import torchvision.transforms.functional as F
16
17 class FunctionalTensorMock:
18 @staticmethod
19 def rgb_to_grayscale(img, num_output_channels=1):
20 if hasattr(F, "rgb_to_grayscale"):
21 return F.rgb_to_grayscale(img, num_output_channels)
22 if len(img.shape) == 4:
23 weights = torch.tensor([0.299, 0.587, 0.114], device=img.device, dtype=img.dtype).view(1, 3, 1, 1)
24 else:
25 weights = torch.tensor([0.299, 0.587, 0.114], device=img.device, dtype=img.dtype).view(3, 1, 1)
26 grayscale = torch.sum(img * weights, dim=-3, keepdim=True)
27 if num_output_channels == 3:
28 if len(img.shape) == 4:
29 grayscale = grayscale.repeat(1, 3, 1, 1)
30 else:
31 grayscale = grayscale.repeat(3, 1, 1)
32 return grayscale
33
34 @staticmethod
35 def resize(img, size, interpolation=2, antialias=None):
36 try:
37 from torchvision.transforms.v2.functional import resize as v2_resize
38
39 return v2_resize(img, size, interpolation=interpolation, antialias=antialias)
40 except ImportError:
41 if hasattr(F, "resize"):
42 return F.resize(img, size, interpolation=interpolation)
43 import torch.nn.functional as torch_F
44
45 if isinstance(size, int):
46 size = (size, size)
47 return torch_F.interpolate(
48 img.unsqueeze(0) if len(img.shape) == 3 else img,
49 size=size,
50 mode="bilinear",
51 align_corners=False,
52 )
53
54 def __getattr__(self, name):
55 if hasattr(F, name):
56 return getattr(F, name)
57 try:
58 import torchvision.transforms.v2.functional as v2_F
59
60 if hasattr(v2_F, name):
61 return getattr(v2_F, name)
62 except ImportError:
63 pass
64 raise AttributeError(f"'{name}' not found in functional_tensor mock")
65
66 sys.modules["torchvision.transforms.functional_tensor"] = FunctionalTensorMock()
67 return True

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected