|
8 | 8 | from pathlib import Path |
9 | 9 |
|
10 | 10 | import torch |
| 11 | +from torch import Tensor |
11 | 12 |
|
12 | 13 | from torchcodec._core.ops import ( |
13 | 14 | create_file_like_context, |
|
19 | 20 | ) |
20 | 21 |
|
21 | 22 |
|
22 | | -def _encode_to_dest(input, dest, param, *, to_file, to_file_like) -> None: |
23 | | - if isinstance(dest, (str, Path)): |
24 | | - to_file(input, str(dest), param) |
25 | | - else: |
26 | | - # Assume file-like, it gets validated in C++ (it's tested). |
27 | | - to_file_like(input, create_file_like_context(dest, True), param) |
28 | | - |
29 | | - |
30 | | -def _encode_to_tensor_through_bytesio(input, param, to_file_like) -> torch.Tensor: |
| 23 | +def _encode_to_tensor_through_bytesio(img, param, to_file_like) -> Tensor: |
31 | 24 | # Encode into an in-memory BytesIO and wrap its buffer as a 1-D uint8 tensor. |
32 | 25 | # getbuffer() (unlike getvalue()) exposes the buffer without copying. We |
33 | 26 | # could have native C++ implementation for that in each encoder, but it's |
34 | 27 | # not always worth it (based on benchmarks). Currently, the only encoder |
35 | 28 | # that really needs a dedicated C++ path is JPEG on CUDA. |
36 | 29 | buf = io.BytesIO() |
37 | | - to_file_like(input, create_file_like_context(buf, True), param) |
| 30 | + to_file_like(img, create_file_like_context(buf, True), param) |
38 | 31 | return torch.frombuffer(buf.getbuffer(), dtype=torch.uint8) |
39 | 32 |
|
40 | 33 |
|
41 | | -def encode_png( |
42 | | - input: torch.Tensor, |
43 | | - dest: str | Path | None = None, |
44 | | - compression_level: int = 6, |
45 | | -) -> torch.Tensor | None: |
46 | | - """Encode a CHW uint8 image tensor into a PNG. |
47 | | -
|
48 | | - Args: |
49 | | - input (``torch.Tensor``): The image to encode, a 3-dimensional uint8 |
50 | | - tensor in CHW layout with 1 (grayscale) or 3 (RGB) channels. |
51 | | - dest (str, ``pathlib.Path``, file-like object, or ``None``): The |
52 | | - destination to write the encoded PNG to. Either a path to the output |
53 | | - file, or a file-like object that supports |
54 | | - ``write(data: bytes) -> int`` and |
55 | | - ``seek(offset: int, whence: int = 0) -> int``, such as |
56 | | - ``io.BytesIO()`` or an open file in binary write mode. If ``None`` |
57 | | - (the default), the encoded bytes are returned as a 1-D uint8 tensor |
58 | | - instead of being written anywhere. |
59 | | - compression_level (int): zlib compression level between 0 (no |
60 | | - compression, fastest) and 9 (max compression, slowest). Default: 6. |
61 | | -
|
62 | | - Returns: |
63 | | - ``None`` if ``dest`` is a path or file-like object, otherwise a 1-D uint8 |
64 | | - tensor of the encoded bytes. |
65 | | - """ |
66 | | - if dest is None: |
67 | | - return _encode_to_tensor_through_bytesio( |
68 | | - input, compression_level, _encode_png_to_file_like |
69 | | - ) |
70 | | - else: |
71 | | - _encode_to_dest( |
72 | | - input, |
73 | | - dest, |
74 | | - compression_level, |
75 | | - to_file=_encode_png_to_file, |
76 | | - to_file_like=_encode_png_to_file_like, |
| 34 | +class JpegEncoder: |
| 35 | + def __init__(self, img: Tensor) -> None: |
| 36 | + self._img = img |
| 37 | + |
| 38 | + def to_file(self, dest: str | Path, *, quality: int = 75) -> None: |
| 39 | + self._validate_quality(quality) |
| 40 | + _encode_jpeg_to_file(self._img, str(dest), quality) |
| 41 | + |
| 42 | + def to_file_like( |
| 43 | + self, dest: io.RawIOBase | io.BufferedIOBase, *, quality: int = 75 |
| 44 | + ) -> None: |
| 45 | + self._validate_quality(quality) |
| 46 | + _encode_jpeg_to_file_like( |
| 47 | + self._img, create_file_like_context(dest, True), quality |
77 | 48 | ) |
78 | | - return None |
79 | | - |
80 | | - |
81 | | -def encode_jpeg( |
82 | | - input: torch.Tensor, |
83 | | - dest: str | Path | None = None, |
84 | | - quality: int = 75, |
85 | | -) -> torch.Tensor | None: |
86 | | - """Encode a CHW uint8 image tensor into a JPEG. |
87 | | -
|
88 | | - Args: |
89 | | - input (``torch.Tensor``): The image to encode, a 3-dimensional uint8 |
90 | | - tensor in CHW layout with 1 (grayscale) or 3 (RGB) channels. |
91 | | - dest (str, ``pathlib.Path``, file-like object, or ``None``): The |
92 | | - destination to write the encoded JPEG to. Either a path to the output |
93 | | - file, or a file-like object that supports |
94 | | - ``write(data: bytes) -> int`` and |
95 | | - ``seek(offset: int, whence: int = 0) -> int``, such as |
96 | | - ``io.BytesIO()`` or an open file in binary write mode. If ``None`` |
97 | | - (the default), the encoded bytes are returned as a 1-D uint8 tensor |
98 | | - instead of being written anywhere. |
99 | | - quality (int): Quality of the resulting JPEG, between 1 and 100. Higher |
100 | | - means better quality and larger file size. Default: 75. |
101 | | -
|
102 | | - Returns: |
103 | | - ``None`` if ``dest`` is a path or file-like object. If ``dest`` is |
104 | | - ``None``, a 1-D uint8 tensor of the encoded bytes, on the same device as |
105 | | - ``input`` (a CUDA input yields a CUDA tensor; call ``.cpu()`` for host |
106 | | - bytes). |
107 | | -
|
108 | | - If ``input`` is on a CUDA device, encoding is performed on the GPU with |
109 | | - nvJPEG. Only 3-channel RGB tensors are supported on CUDA (grayscale must be |
110 | | - encoded on the CPU). |
111 | | - """ |
112 | | - if quality < 1 or quality > 100: |
113 | | - raise ValueError("Image quality should be a positive number between 1 and 100") |
114 | | - |
115 | | - if dest is None: |
116 | | - if input.is_cuda: |
117 | | - return _encode_jpeg_to_tensor_cuda(input, quality) |
| 49 | + |
| 50 | + def to_tensor(self, *, quality: int = 75) -> Tensor: |
| 51 | + self._validate_quality(quality) |
| 52 | + if self._img.is_cuda: |
| 53 | + return _encode_jpeg_to_tensor_cuda(self._img, quality) |
118 | 54 | else: |
119 | 55 | return _encode_to_tensor_through_bytesio( |
120 | | - input, quality, _encode_jpeg_to_file_like |
| 56 | + self._img, quality, _encode_jpeg_to_file_like |
| 57 | + ) |
| 58 | + |
| 59 | + @staticmethod |
| 60 | + def _validate_quality(quality: int) -> None: |
| 61 | + if quality < 1 or quality > 100: |
| 62 | + raise ValueError( |
| 63 | + "Image quality should be a positive number between 1 and 100" |
121 | 64 | ) |
122 | | - else: |
123 | | - _encode_to_dest( |
124 | | - input, |
125 | | - dest, |
126 | | - quality, |
127 | | - to_file=_encode_jpeg_to_file, |
128 | | - to_file_like=_encode_jpeg_to_file_like, |
| 65 | + |
| 66 | + |
| 67 | +class PngEncoder: |
| 68 | + def __init__(self, img: Tensor) -> None: |
| 69 | + self._img = img |
| 70 | + |
| 71 | + def to_file(self, dest: str | Path, *, compression_level: int = 6) -> None: |
| 72 | + _encode_png_to_file(self._img, str(dest), compression_level) |
| 73 | + |
| 74 | + def to_file_like( |
| 75 | + self, dest: io.RawIOBase | io.BufferedIOBase, *, compression_level: int = 6 |
| 76 | + ) -> None: |
| 77 | + _encode_png_to_file_like( |
| 78 | + self._img, create_file_like_context(dest, True), compression_level |
| 79 | + ) |
| 80 | + |
| 81 | + def to_tensor(self, *, compression_level: int = 6) -> Tensor: |
| 82 | + return _encode_to_tensor_through_bytesio( |
| 83 | + self._img, compression_level, _encode_png_to_file_like |
129 | 84 | ) |
130 | | - return None |
0 commit comments