ZTWHHH commited on
Commit
b1fe075
·
verified ·
1 Parent(s): f63d72a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/betweenness_subset.cpython-310.pyc +0 -0
  3. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/current_flow_closeness.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/degree_alg.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/flow_matrix.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/group.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/percolation.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_betweenness_centrality.cpython-310.pyc +0 -0
  9. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_reaching.cpython-310.pyc +0 -0
  10. llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_voterank.cpython-310.pyc +0 -0
  11. vlmpy310/lib/python3.10/site-packages/notebook/static/e4299464e7b012968eed.eot +3 -0
  12. vlmpy310/lib/python3.10/site-packages/tokenizers/normalizers/__init__.py +29 -0
  13. vlmpy310/lib/python3.10/site-packages/tokenizers/normalizers/__init__.pyi +636 -0
  14. vlmpy310/lib/python3.10/site-packages/tokenizers/trainers/__init__.pyi +156 -0
  15. vlmpy310/lib/python3.10/site-packages/tokenizers/trainers/__pycache__/__init__.cpython-310.pyc +0 -0
  16. vlmpy310/lib/python3.10/site-packages/torchvision/__init__.py +103 -0
  17. vlmpy310/lib/python3.10/site-packages/torchvision/_internally_replaced_utils.py +50 -0
  18. vlmpy310/lib/python3.10/site-packages/torchvision/_meta_registrations.py +225 -0
  19. vlmpy310/lib/python3.10/site-packages/torchvision/_utils.py +32 -0
  20. vlmpy310/lib/python3.10/site-packages/torchvision/extension.py +92 -0
  21. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__init__.py +2 -0
  22. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/__init__.cpython-310.pyc +0 -0
  23. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_functional_pil.cpython-310.pyc +0 -0
  24. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_functional_tensor.cpython-310.pyc +0 -0
  25. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_functional_video.cpython-310.pyc +0 -0
  26. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_presets.cpython-310.pyc +0 -0
  27. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_transforms_video.cpython-310.pyc +0 -0
  28. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/autoaugment.cpython-310.pyc +0 -0
  29. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/functional.cpython-310.pyc +0 -0
  30. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/transforms.cpython-310.pyc +0 -0
  31. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_functional_pil.py +393 -0
  32. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_functional_tensor.py +960 -0
  33. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_functional_video.py +114 -0
  34. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_presets.py +216 -0
  35. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_transforms_video.py +174 -0
  36. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/autoaugment.py +615 -0
  37. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/functional.py +1569 -0
  38. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/transforms.py +2153 -0
  39. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__init__.py +57 -0
  40. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_auto_augment.cpython-310.pyc +0 -0
  41. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_color.cpython-310.pyc +0 -0
  42. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_deprecated.cpython-310.pyc +0 -0
  43. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_misc.cpython-310.pyc +0 -0
  44. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_augment.py +319 -0
  45. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_auto_augment.py +627 -0
  46. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_color.py +362 -0
  47. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_container.py +174 -0
  48. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_deprecated.py +48 -0
  49. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_geometry.py +1401 -0
  50. vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_meta.py +38 -0
.gitattributes CHANGED
@@ -1156,3 +1156,4 @@ llava_next/lib/python3.10/site-packages/google/_upb/_message.abi3.so filter=lfs
1156
  vlmpy310/lib/python3.10/site-packages/notebook/static/af6397503fcefbd61397.ttf filter=lfs diff=lfs merge=lfs -text
1157
  vlmpy310/lib/python3.10/site-packages/notebook/static/cda59d6efffa685830fd.ttf filter=lfs diff=lfs merge=lfs -text
1158
  vlmpy310/lib/python3.10/site-packages/notebook/static/3f6d3488cf65374f6f67.woff filter=lfs diff=lfs merge=lfs -text
 
 
1156
  vlmpy310/lib/python3.10/site-packages/notebook/static/af6397503fcefbd61397.ttf filter=lfs diff=lfs merge=lfs -text
1157
  vlmpy310/lib/python3.10/site-packages/notebook/static/cda59d6efffa685830fd.ttf filter=lfs diff=lfs merge=lfs -text
1158
  vlmpy310/lib/python3.10/site-packages/notebook/static/3f6d3488cf65374f6f67.woff filter=lfs diff=lfs merge=lfs -text
1159
+ vlmpy310/lib/python3.10/site-packages/notebook/static/e4299464e7b012968eed.eot filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/betweenness_subset.cpython-310.pyc ADDED
Binary file (8.21 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/current_flow_closeness.cpython-310.pyc ADDED
Binary file (3.37 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/degree_alg.cpython-310.pyc ADDED
Binary file (4.55 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/flow_matrix.cpython-310.pyc ADDED
Binary file (5.08 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/group.cpython-310.pyc ADDED
Binary file (21.5 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/__pycache__/percolation.cpython-310.pyc ADDED
Binary file (4.16 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_betweenness_centrality.cpython-310.pyc ADDED
Binary file (21.1 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_reaching.cpython-310.pyc ADDED
Binary file (6.92 kB). View file
 
llava_next/lib/python3.10/site-packages/networkx/algorithms/centrality/tests/__pycache__/test_voterank.cpython-310.pyc ADDED
Binary file (2.23 kB). View file
 
vlmpy310/lib/python3.10/site-packages/notebook/static/e4299464e7b012968eed.eot ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e4299464e7b012968eed63ac2db1c9509f56bca409ef9f71f2926a8c3c80b2a9
3
+ size 134294
vlmpy310/lib/python3.10/site-packages/tokenizers/normalizers/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .. import normalizers
2
+
3
+
4
+ Normalizer = normalizers.Normalizer
5
+ BertNormalizer = normalizers.BertNormalizer
6
+ NFD = normalizers.NFD
7
+ NFKD = normalizers.NFKD
8
+ NFC = normalizers.NFC
9
+ NFKC = normalizers.NFKC
10
+ Sequence = normalizers.Sequence
11
+ Lowercase = normalizers.Lowercase
12
+ Prepend = normalizers.Prepend
13
+ Strip = normalizers.Strip
14
+ StripAccents = normalizers.StripAccents
15
+ Nmt = normalizers.Nmt
16
+ Precompiled = normalizers.Precompiled
17
+ Replace = normalizers.Replace
18
+ ByteLevel = normalizers.ByteLevel
19
+
20
+ NORMALIZERS = {"nfc": NFC, "nfd": NFD, "nfkc": NFKC, "nfkd": NFKD}
21
+
22
+
23
+ def unicode_normalizer_from_str(normalizer: str) -> Normalizer:
24
+ if normalizer not in NORMALIZERS:
25
+ raise ValueError(
26
+ "{} is not a known unicode normalizer. Available are {}".format(normalizer, NORMALIZERS.keys())
27
+ )
28
+
29
+ return NORMALIZERS[normalizer]()
vlmpy310/lib/python3.10/site-packages/tokenizers/normalizers/__init__.pyi ADDED
@@ -0,0 +1,636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated content DO NOT EDIT
2
+ class Normalizer:
3
+ """
4
+ Base class for all normalizers
5
+
6
+ This class is not supposed to be instantiated directly. Instead, any implementation of a
7
+ Normalizer will return an instance of this class when instantiated.
8
+ """
9
+ def normalize(self, normalized):
10
+ """
11
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
12
+
13
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
14
+ keep track of the alignment information. If you just want to see the result
15
+ of the normalization on a raw string, you can use
16
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
17
+
18
+ Args:
19
+ normalized (:class:`~tokenizers.NormalizedString`):
20
+ The normalized string on which to apply this
21
+ :class:`~tokenizers.normalizers.Normalizer`
22
+ """
23
+ pass
24
+
25
+ def normalize_str(self, sequence):
26
+ """
27
+ Normalize the given string
28
+
29
+ This method provides a way to visualize the effect of a
30
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
31
+ information. If you need to get/convert offsets, you can use
32
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
33
+
34
+ Args:
35
+ sequence (:obj:`str`):
36
+ A string to normalize
37
+
38
+ Returns:
39
+ :obj:`str`: A string after normalization
40
+ """
41
+ pass
42
+
43
+ class BertNormalizer(Normalizer):
44
+ """
45
+ BertNormalizer
46
+
47
+ Takes care of normalizing raw text before giving it to a Bert model.
48
+ This includes cleaning the text, handling accents, chinese chars and lowercasing
49
+
50
+ Args:
51
+ clean_text (:obj:`bool`, `optional`, defaults to :obj:`True`):
52
+ Whether to clean the text, by removing any control characters
53
+ and replacing all whitespaces by the classic one.
54
+
55
+ handle_chinese_chars (:obj:`bool`, `optional`, defaults to :obj:`True`):
56
+ Whether to handle chinese chars by putting spaces around them.
57
+
58
+ strip_accents (:obj:`bool`, `optional`):
59
+ Whether to strip all accents. If this option is not specified (ie == None),
60
+ then it will be determined by the value for `lowercase` (as in the original Bert).
61
+
62
+ lowercase (:obj:`bool`, `optional`, defaults to :obj:`True`):
63
+ Whether to lowercase.
64
+ """
65
+ def __init__(self, clean_text=True, handle_chinese_chars=True, strip_accents=None, lowercase=True):
66
+ pass
67
+
68
+ def normalize(self, normalized):
69
+ """
70
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
71
+
72
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
73
+ keep track of the alignment information. If you just want to see the result
74
+ of the normalization on a raw string, you can use
75
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
76
+
77
+ Args:
78
+ normalized (:class:`~tokenizers.NormalizedString`):
79
+ The normalized string on which to apply this
80
+ :class:`~tokenizers.normalizers.Normalizer`
81
+ """
82
+ pass
83
+
84
+ def normalize_str(self, sequence):
85
+ """
86
+ Normalize the given string
87
+
88
+ This method provides a way to visualize the effect of a
89
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
90
+ information. If you need to get/convert offsets, you can use
91
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
92
+
93
+ Args:
94
+ sequence (:obj:`str`):
95
+ A string to normalize
96
+
97
+ Returns:
98
+ :obj:`str`: A string after normalization
99
+ """
100
+ pass
101
+
102
+ class ByteLevel(Normalizer):
103
+ """
104
+ Bytelevel Normalizer
105
+ """
106
+ def __init__(self):
107
+ pass
108
+
109
+ def normalize(self, normalized):
110
+ """
111
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
112
+
113
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
114
+ keep track of the alignment information. If you just want to see the result
115
+ of the normalization on a raw string, you can use
116
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
117
+
118
+ Args:
119
+ normalized (:class:`~tokenizers.NormalizedString`):
120
+ The normalized string on which to apply this
121
+ :class:`~tokenizers.normalizers.Normalizer`
122
+ """
123
+ pass
124
+
125
+ def normalize_str(self, sequence):
126
+ """
127
+ Normalize the given string
128
+
129
+ This method provides a way to visualize the effect of a
130
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
131
+ information. If you need to get/convert offsets, you can use
132
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
133
+
134
+ Args:
135
+ sequence (:obj:`str`):
136
+ A string to normalize
137
+
138
+ Returns:
139
+ :obj:`str`: A string after normalization
140
+ """
141
+ pass
142
+
143
+ class Lowercase(Normalizer):
144
+ """
145
+ Lowercase Normalizer
146
+ """
147
+ def __init__(self):
148
+ pass
149
+
150
+ def normalize(self, normalized):
151
+ """
152
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
153
+
154
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
155
+ keep track of the alignment information. If you just want to see the result
156
+ of the normalization on a raw string, you can use
157
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
158
+
159
+ Args:
160
+ normalized (:class:`~tokenizers.NormalizedString`):
161
+ The normalized string on which to apply this
162
+ :class:`~tokenizers.normalizers.Normalizer`
163
+ """
164
+ pass
165
+
166
+ def normalize_str(self, sequence):
167
+ """
168
+ Normalize the given string
169
+
170
+ This method provides a way to visualize the effect of a
171
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
172
+ information. If you need to get/convert offsets, you can use
173
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
174
+
175
+ Args:
176
+ sequence (:obj:`str`):
177
+ A string to normalize
178
+
179
+ Returns:
180
+ :obj:`str`: A string after normalization
181
+ """
182
+ pass
183
+
184
+ class NFC(Normalizer):
185
+ """
186
+ NFC Unicode Normalizer
187
+ """
188
+ def __init__(self):
189
+ pass
190
+
191
+ def normalize(self, normalized):
192
+ """
193
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
194
+
195
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
196
+ keep track of the alignment information. If you just want to see the result
197
+ of the normalization on a raw string, you can use
198
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
199
+
200
+ Args:
201
+ normalized (:class:`~tokenizers.NormalizedString`):
202
+ The normalized string on which to apply this
203
+ :class:`~tokenizers.normalizers.Normalizer`
204
+ """
205
+ pass
206
+
207
+ def normalize_str(self, sequence):
208
+ """
209
+ Normalize the given string
210
+
211
+ This method provides a way to visualize the effect of a
212
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
213
+ information. If you need to get/convert offsets, you can use
214
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
215
+
216
+ Args:
217
+ sequence (:obj:`str`):
218
+ A string to normalize
219
+
220
+ Returns:
221
+ :obj:`str`: A string after normalization
222
+ """
223
+ pass
224
+
225
+ class NFD(Normalizer):
226
+ """
227
+ NFD Unicode Normalizer
228
+ """
229
+ def __init__(self):
230
+ pass
231
+
232
+ def normalize(self, normalized):
233
+ """
234
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
235
+
236
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
237
+ keep track of the alignment information. If you just want to see the result
238
+ of the normalization on a raw string, you can use
239
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
240
+
241
+ Args:
242
+ normalized (:class:`~tokenizers.NormalizedString`):
243
+ The normalized string on which to apply this
244
+ :class:`~tokenizers.normalizers.Normalizer`
245
+ """
246
+ pass
247
+
248
+ def normalize_str(self, sequence):
249
+ """
250
+ Normalize the given string
251
+
252
+ This method provides a way to visualize the effect of a
253
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
254
+ information. If you need to get/convert offsets, you can use
255
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
256
+
257
+ Args:
258
+ sequence (:obj:`str`):
259
+ A string to normalize
260
+
261
+ Returns:
262
+ :obj:`str`: A string after normalization
263
+ """
264
+ pass
265
+
266
+ class NFKC(Normalizer):
267
+ """
268
+ NFKC Unicode Normalizer
269
+ """
270
+ def __init__(self):
271
+ pass
272
+
273
+ def normalize(self, normalized):
274
+ """
275
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
276
+
277
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
278
+ keep track of the alignment information. If you just want to see the result
279
+ of the normalization on a raw string, you can use
280
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
281
+
282
+ Args:
283
+ normalized (:class:`~tokenizers.NormalizedString`):
284
+ The normalized string on which to apply this
285
+ :class:`~tokenizers.normalizers.Normalizer`
286
+ """
287
+ pass
288
+
289
+ def normalize_str(self, sequence):
290
+ """
291
+ Normalize the given string
292
+
293
+ This method provides a way to visualize the effect of a
294
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
295
+ information. If you need to get/convert offsets, you can use
296
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
297
+
298
+ Args:
299
+ sequence (:obj:`str`):
300
+ A string to normalize
301
+
302
+ Returns:
303
+ :obj:`str`: A string after normalization
304
+ """
305
+ pass
306
+
307
+ class NFKD(Normalizer):
308
+ """
309
+ NFKD Unicode Normalizer
310
+ """
311
+ def __init__(self):
312
+ pass
313
+
314
+ def normalize(self, normalized):
315
+ """
316
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
317
+
318
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
319
+ keep track of the alignment information. If you just want to see the result
320
+ of the normalization on a raw string, you can use
321
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
322
+
323
+ Args:
324
+ normalized (:class:`~tokenizers.NormalizedString`):
325
+ The normalized string on which to apply this
326
+ :class:`~tokenizers.normalizers.Normalizer`
327
+ """
328
+ pass
329
+
330
+ def normalize_str(self, sequence):
331
+ """
332
+ Normalize the given string
333
+
334
+ This method provides a way to visualize the effect of a
335
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
336
+ information. If you need to get/convert offsets, you can use
337
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
338
+
339
+ Args:
340
+ sequence (:obj:`str`):
341
+ A string to normalize
342
+
343
+ Returns:
344
+ :obj:`str`: A string after normalization
345
+ """
346
+ pass
347
+
348
+ class Nmt(Normalizer):
349
+ """
350
+ Nmt normalizer
351
+ """
352
+ def __init__(self):
353
+ pass
354
+
355
+ def normalize(self, normalized):
356
+ """
357
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
358
+
359
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
360
+ keep track of the alignment information. If you just want to see the result
361
+ of the normalization on a raw string, you can use
362
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
363
+
364
+ Args:
365
+ normalized (:class:`~tokenizers.NormalizedString`):
366
+ The normalized string on which to apply this
367
+ :class:`~tokenizers.normalizers.Normalizer`
368
+ """
369
+ pass
370
+
371
+ def normalize_str(self, sequence):
372
+ """
373
+ Normalize the given string
374
+
375
+ This method provides a way to visualize the effect of a
376
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
377
+ information. If you need to get/convert offsets, you can use
378
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
379
+
380
+ Args:
381
+ sequence (:obj:`str`):
382
+ A string to normalize
383
+
384
+ Returns:
385
+ :obj:`str`: A string after normalization
386
+ """
387
+ pass
388
+
389
+ class Precompiled(Normalizer):
390
+ """
391
+ Precompiled normalizer
392
+ Don't use manually it is used for compatiblity for SentencePiece.
393
+ """
394
+ def __init__(self, precompiled_charsmap):
395
+ pass
396
+
397
+ def normalize(self, normalized):
398
+ """
399
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
400
+
401
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
402
+ keep track of the alignment information. If you just want to see the result
403
+ of the normalization on a raw string, you can use
404
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
405
+
406
+ Args:
407
+ normalized (:class:`~tokenizers.NormalizedString`):
408
+ The normalized string on which to apply this
409
+ :class:`~tokenizers.normalizers.Normalizer`
410
+ """
411
+ pass
412
+
413
+ def normalize_str(self, sequence):
414
+ """
415
+ Normalize the given string
416
+
417
+ This method provides a way to visualize the effect of a
418
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
419
+ information. If you need to get/convert offsets, you can use
420
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
421
+
422
+ Args:
423
+ sequence (:obj:`str`):
424
+ A string to normalize
425
+
426
+ Returns:
427
+ :obj:`str`: A string after normalization
428
+ """
429
+ pass
430
+
431
+ class Prepend(Normalizer):
432
+ """
433
+ Prepend normalizer
434
+ """
435
+ def __init__(self, prepend):
436
+ pass
437
+
438
+ def normalize(self, normalized):
439
+ """
440
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
441
+
442
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
443
+ keep track of the alignment information. If you just want to see the result
444
+ of the normalization on a raw string, you can use
445
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
446
+
447
+ Args:
448
+ normalized (:class:`~tokenizers.NormalizedString`):
449
+ The normalized string on which to apply this
450
+ :class:`~tokenizers.normalizers.Normalizer`
451
+ """
452
+ pass
453
+
454
+ def normalize_str(self, sequence):
455
+ """
456
+ Normalize the given string
457
+
458
+ This method provides a way to visualize the effect of a
459
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
460
+ information. If you need to get/convert offsets, you can use
461
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
462
+
463
+ Args:
464
+ sequence (:obj:`str`):
465
+ A string to normalize
466
+
467
+ Returns:
468
+ :obj:`str`: A string after normalization
469
+ """
470
+ pass
471
+
472
+ class Replace(Normalizer):
473
+ """
474
+ Replace normalizer
475
+ """
476
+ def __init__(self, pattern, content):
477
+ pass
478
+
479
+ def normalize(self, normalized):
480
+ """
481
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
482
+
483
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
484
+ keep track of the alignment information. If you just want to see the result
485
+ of the normalization on a raw string, you can use
486
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
487
+
488
+ Args:
489
+ normalized (:class:`~tokenizers.NormalizedString`):
490
+ The normalized string on which to apply this
491
+ :class:`~tokenizers.normalizers.Normalizer`
492
+ """
493
+ pass
494
+
495
+ def normalize_str(self, sequence):
496
+ """
497
+ Normalize the given string
498
+
499
+ This method provides a way to visualize the effect of a
500
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
501
+ information. If you need to get/convert offsets, you can use
502
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
503
+
504
+ Args:
505
+ sequence (:obj:`str`):
506
+ A string to normalize
507
+
508
+ Returns:
509
+ :obj:`str`: A string after normalization
510
+ """
511
+ pass
512
+
513
+ class Sequence(Normalizer):
514
+ """
515
+ Allows concatenating multiple other Normalizer as a Sequence.
516
+ All the normalizers run in sequence in the given order
517
+
518
+ Args:
519
+ normalizers (:obj:`List[Normalizer]`):
520
+ A list of Normalizer to be run as a sequence
521
+ """
522
+ def normalize(self, normalized):
523
+ """
524
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
525
+
526
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
527
+ keep track of the alignment information. If you just want to see the result
528
+ of the normalization on a raw string, you can use
529
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
530
+
531
+ Args:
532
+ normalized (:class:`~tokenizers.NormalizedString`):
533
+ The normalized string on which to apply this
534
+ :class:`~tokenizers.normalizers.Normalizer`
535
+ """
536
+ pass
537
+
538
+ def normalize_str(self, sequence):
539
+ """
540
+ Normalize the given string
541
+
542
+ This method provides a way to visualize the effect of a
543
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
544
+ information. If you need to get/convert offsets, you can use
545
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
546
+
547
+ Args:
548
+ sequence (:obj:`str`):
549
+ A string to normalize
550
+
551
+ Returns:
552
+ :obj:`str`: A string after normalization
553
+ """
554
+ pass
555
+
556
+ class Strip(Normalizer):
557
+ """
558
+ Strip normalizer
559
+ """
560
+ def __init__(self, left=True, right=True):
561
+ pass
562
+
563
+ def normalize(self, normalized):
564
+ """
565
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
566
+
567
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
568
+ keep track of the alignment information. If you just want to see the result
569
+ of the normalization on a raw string, you can use
570
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
571
+
572
+ Args:
573
+ normalized (:class:`~tokenizers.NormalizedString`):
574
+ The normalized string on which to apply this
575
+ :class:`~tokenizers.normalizers.Normalizer`
576
+ """
577
+ pass
578
+
579
+ def normalize_str(self, sequence):
580
+ """
581
+ Normalize the given string
582
+
583
+ This method provides a way to visualize the effect of a
584
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
585
+ information. If you need to get/convert offsets, you can use
586
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
587
+
588
+ Args:
589
+ sequence (:obj:`str`):
590
+ A string to normalize
591
+
592
+ Returns:
593
+ :obj:`str`: A string after normalization
594
+ """
595
+ pass
596
+
597
+ class StripAccents(Normalizer):
598
+ """
599
+ StripAccents normalizer
600
+ """
601
+ def __init__(self):
602
+ pass
603
+
604
+ def normalize(self, normalized):
605
+ """
606
+ Normalize a :class:`~tokenizers.NormalizedString` in-place
607
+
608
+ This method allows to modify a :class:`~tokenizers.NormalizedString` to
609
+ keep track of the alignment information. If you just want to see the result
610
+ of the normalization on a raw string, you can use
611
+ :meth:`~tokenizers.normalizers.Normalizer.normalize_str`
612
+
613
+ Args:
614
+ normalized (:class:`~tokenizers.NormalizedString`):
615
+ The normalized string on which to apply this
616
+ :class:`~tokenizers.normalizers.Normalizer`
617
+ """
618
+ pass
619
+
620
+ def normalize_str(self, sequence):
621
+ """
622
+ Normalize the given string
623
+
624
+ This method provides a way to visualize the effect of a
625
+ :class:`~tokenizers.normalizers.Normalizer` but it does not keep track of the alignment
626
+ information. If you need to get/convert offsets, you can use
627
+ :meth:`~tokenizers.normalizers.Normalizer.normalize`
628
+
629
+ Args:
630
+ sequence (:obj:`str`):
631
+ A string to normalize
632
+
633
+ Returns:
634
+ :obj:`str`: A string after normalization
635
+ """
636
+ pass
vlmpy310/lib/python3.10/site-packages/tokenizers/trainers/__init__.pyi ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated content DO NOT EDIT
2
+ class Trainer:
3
+ """
4
+ Base class for all trainers
5
+
6
+ This class is not supposed to be instantiated directly. Instead, any implementation of a
7
+ Trainer will return an instance of this class when instantiated.
8
+ """
9
+
10
+ class BpeTrainer(Trainer):
11
+ """
12
+ Trainer capable of training a BPE model
13
+
14
+ Args:
15
+ vocab_size (:obj:`int`, `optional`):
16
+ The size of the final vocabulary, including all tokens and alphabet.
17
+
18
+ min_frequency (:obj:`int`, `optional`):
19
+ The minimum frequency a pair should have in order to be merged.
20
+
21
+ show_progress (:obj:`bool`, `optional`):
22
+ Whether to show progress bars while training.
23
+
24
+ special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`):
25
+ A list of special tokens the model should know of.
26
+
27
+ limit_alphabet (:obj:`int`, `optional`):
28
+ The maximum different characters to keep in the alphabet.
29
+
30
+ initial_alphabet (:obj:`List[str]`, `optional`):
31
+ A list of characters to include in the initial alphabet, even
32
+ if not seen in the training dataset.
33
+ If the strings contain more than one character, only the first one
34
+ is kept.
35
+
36
+ continuing_subword_prefix (:obj:`str`, `optional`):
37
+ A prefix to be used for every subword that is not a beginning-of-word.
38
+
39
+ end_of_word_suffix (:obj:`str`, `optional`):
40
+ A suffix to be used for every subword that is a end-of-word.
41
+
42
+ max_token_length (:obj:`int`, `optional`):
43
+ Prevents creating tokens longer than the specified size.
44
+ This can help with reducing polluting your vocabulary with
45
+ highly repetitive tokens like `======` for wikipedia
46
+
47
+ """
48
+
49
+ class UnigramTrainer(Trainer):
50
+ """
51
+ Trainer capable of training a Unigram model
52
+
53
+ Args:
54
+ vocab_size (:obj:`int`):
55
+ The size of the final vocabulary, including all tokens and alphabet.
56
+
57
+ show_progress (:obj:`bool`):
58
+ Whether to show progress bars while training.
59
+
60
+ special_tokens (:obj:`List[Union[str, AddedToken]]`):
61
+ A list of special tokens the model should know of.
62
+
63
+ initial_alphabet (:obj:`List[str]`):
64
+ A list of characters to include in the initial alphabet, even
65
+ if not seen in the training dataset.
66
+ If the strings contain more than one character, only the first one
67
+ is kept.
68
+
69
+ shrinking_factor (:obj:`float`):
70
+ The shrinking factor used at each step of the training to prune the
71
+ vocabulary.
72
+
73
+ unk_token (:obj:`str`):
74
+ The token used for out-of-vocabulary tokens.
75
+
76
+ max_piece_length (:obj:`int`):
77
+ The maximum length of a given token.
78
+
79
+ n_sub_iterations (:obj:`int`):
80
+ The number of iterations of the EM algorithm to perform before
81
+ pruning the vocabulary.
82
+ """
83
+ def __init__(
84
+ self,
85
+ vocab_size=8000,
86
+ show_progress=True,
87
+ special_tokens=[],
88
+ shrinking_factor=0.75,
89
+ unk_token=None,
90
+ max_piece_length=16,
91
+ n_sub_iterations=2,
92
+ ):
93
+ pass
94
+
95
+ class WordLevelTrainer(Trainer):
96
+ """
97
+ Trainer capable of training a WorldLevel model
98
+
99
+ Args:
100
+ vocab_size (:obj:`int`, `optional`):
101
+ The size of the final vocabulary, including all tokens and alphabet.
102
+
103
+ min_frequency (:obj:`int`, `optional`):
104
+ The minimum frequency a pair should have in order to be merged.
105
+
106
+ show_progress (:obj:`bool`, `optional`):
107
+ Whether to show progress bars while training.
108
+
109
+ special_tokens (:obj:`List[Union[str, AddedToken]]`):
110
+ A list of special tokens the model should know of.
111
+ """
112
+
113
+ class WordPieceTrainer(Trainer):
114
+ """
115
+ Trainer capable of training a WordPiece model
116
+
117
+ Args:
118
+ vocab_size (:obj:`int`, `optional`):
119
+ The size of the final vocabulary, including all tokens and alphabet.
120
+
121
+ min_frequency (:obj:`int`, `optional`):
122
+ The minimum frequency a pair should have in order to be merged.
123
+
124
+ show_progress (:obj:`bool`, `optional`):
125
+ Whether to show progress bars while training.
126
+
127
+ special_tokens (:obj:`List[Union[str, AddedToken]]`, `optional`):
128
+ A list of special tokens the model should know of.
129
+
130
+ limit_alphabet (:obj:`int`, `optional`):
131
+ The maximum different characters to keep in the alphabet.
132
+
133
+ initial_alphabet (:obj:`List[str]`, `optional`):
134
+ A list of characters to include in the initial alphabet, even
135
+ if not seen in the training dataset.
136
+ If the strings contain more than one character, only the first one
137
+ is kept.
138
+
139
+ continuing_subword_prefix (:obj:`str`, `optional`):
140
+ A prefix to be used for every subword that is not a beginning-of-word.
141
+
142
+ end_of_word_suffix (:obj:`str`, `optional`):
143
+ A suffix to be used for every subword that is a end-of-word.
144
+ """
145
+ def __init__(
146
+ self,
147
+ vocab_size=30000,
148
+ min_frequency=0,
149
+ show_progress=True,
150
+ special_tokens=[],
151
+ limit_alphabet=None,
152
+ initial_alphabet=[],
153
+ continuing_subword_prefix="##",
154
+ end_of_word_suffix=None,
155
+ ):
156
+ pass
vlmpy310/lib/python3.10/site-packages/tokenizers/trainers/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (319 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import warnings
3
+ from modulefinder import Module
4
+
5
+ import torch
6
+ from torchvision import _meta_registrations, datasets, io, models, ops, transforms, utils
7
+
8
+ from .extension import _HAS_OPS
9
+
10
+ try:
11
+ from .version import __version__ # noqa: F401
12
+ except ImportError:
13
+ pass
14
+
15
+
16
+ # Check if torchvision is being imported within the root folder
17
+ if not _HAS_OPS and os.path.dirname(os.path.realpath(__file__)) == os.path.join(
18
+ os.path.realpath(os.getcwd()), "torchvision"
19
+ ):
20
+ message = (
21
+ "You are importing torchvision within its own root folder ({}). "
22
+ "This is not expected to work and may give errors. Please exit the "
23
+ "torchvision project source and relaunch your python interpreter."
24
+ )
25
+ warnings.warn(message.format(os.getcwd()))
26
+
27
+ _image_backend = "PIL"
28
+
29
+ _video_backend = "pyav"
30
+
31
+
32
+ def set_image_backend(backend):
33
+ """
34
+ Specifies the package used to load images.
35
+
36
+ Args:
37
+ backend (string): Name of the image backend. one of {'PIL', 'accimage'}.
38
+ The :mod:`accimage` package uses the Intel IPP library. It is
39
+ generally faster than PIL, but does not support as many operations.
40
+ """
41
+ global _image_backend
42
+ if backend not in ["PIL", "accimage"]:
43
+ raise ValueError(f"Invalid backend '{backend}'. Options are 'PIL' and 'accimage'")
44
+ _image_backend = backend
45
+
46
+
47
+ def get_image_backend():
48
+ """
49
+ Gets the name of the package used to load images
50
+ """
51
+ return _image_backend
52
+
53
+
54
+ def set_video_backend(backend):
55
+ """
56
+ Specifies the package used to decode videos.
57
+
58
+ Args:
59
+ backend (string): Name of the video backend. one of {'pyav', 'video_reader'}.
60
+ The :mod:`pyav` package uses the 3rd party PyAv library. It is a Pythonic
61
+ binding for the FFmpeg libraries.
62
+ The :mod:`video_reader` package includes a native C++ implementation on
63
+ top of FFMPEG libraries, and a python API of TorchScript custom operator.
64
+ It generally decodes faster than :mod:`pyav`, but is perhaps less robust.
65
+
66
+ .. note::
67
+ Building with FFMPEG is disabled by default in the latest `main`. If you want to use the 'video_reader'
68
+ backend, please compile torchvision from source.
69
+ """
70
+ global _video_backend
71
+ if backend not in ["pyav", "video_reader", "cuda"]:
72
+ raise ValueError("Invalid video backend '%s'. Options are 'pyav', 'video_reader' and 'cuda'" % backend)
73
+ if backend == "video_reader" and not io._HAS_VIDEO_OPT:
74
+ # TODO: better messages
75
+ message = "video_reader video backend is not available. Please compile torchvision from source and try again"
76
+ raise RuntimeError(message)
77
+ elif backend == "cuda" and not io._HAS_GPU_VIDEO_DECODER:
78
+ # TODO: better messages
79
+ message = "cuda video backend is not available."
80
+ raise RuntimeError(message)
81
+ else:
82
+ _video_backend = backend
83
+
84
+
85
+ def get_video_backend():
86
+ """
87
+ Returns the currently active video backend used to decode videos.
88
+
89
+ Returns:
90
+ str: Name of the video backend. one of {'pyav', 'video_reader'}.
91
+ """
92
+
93
+ return _video_backend
94
+
95
+
96
+ def _is_tracing():
97
+ return torch._C._get_tracing_state()
98
+
99
+
100
+ def disable_beta_transforms_warning():
101
+ # Noop, only exists to avoid breaking existing code.
102
+ # See https://github.com/pytorch/vision/issues/7896
103
+ pass
vlmpy310/lib/python3.10/site-packages/torchvision/_internally_replaced_utils.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.machinery
2
+ import os
3
+
4
+ from torch.hub import _get_torch_home
5
+
6
+
7
+ _HOME = os.path.join(_get_torch_home(), "datasets", "vision")
8
+ _USE_SHARDED_DATASETS = False
9
+
10
+
11
+ def _download_file_from_remote_location(fpath: str, url: str) -> None:
12
+ pass
13
+
14
+
15
+ def _is_remote_location_available() -> bool:
16
+ return False
17
+
18
+
19
+ try:
20
+ from torch.hub import load_state_dict_from_url # noqa: 401
21
+ except ImportError:
22
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url # noqa: 401
23
+
24
+
25
+ def _get_extension_path(lib_name):
26
+
27
+ lib_dir = os.path.dirname(__file__)
28
+ if os.name == "nt":
29
+ # Register the main torchvision library location on the default DLL path
30
+ import ctypes
31
+
32
+ kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True)
33
+ with_load_library_flags = hasattr(kernel32, "AddDllDirectory")
34
+ prev_error_mode = kernel32.SetErrorMode(0x0001)
35
+
36
+ if with_load_library_flags:
37
+ kernel32.AddDllDirectory.restype = ctypes.c_void_p
38
+
39
+ os.add_dll_directory(lib_dir)
40
+
41
+ kernel32.SetErrorMode(prev_error_mode)
42
+
43
+ loader_details = (importlib.machinery.ExtensionFileLoader, importlib.machinery.EXTENSION_SUFFIXES)
44
+
45
+ extfinder = importlib.machinery.FileFinder(lib_dir, loader_details)
46
+ ext_specs = extfinder.find_spec(lib_name)
47
+ if ext_specs is None:
48
+ raise ImportError
49
+
50
+ return ext_specs.origin
vlmpy310/lib/python3.10/site-packages/torchvision/_meta_registrations.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+
3
+ import torch
4
+ import torch._custom_ops
5
+ import torch.library
6
+
7
+ # Ensure that torch.ops.torchvision is visible
8
+ import torchvision.extension # noqa: F401
9
+
10
+
11
+ @functools.lru_cache(None)
12
+ def get_meta_lib():
13
+ return torch.library.Library("torchvision", "IMPL", "Meta")
14
+
15
+
16
+ def register_meta(op_name, overload_name="default"):
17
+ def wrapper(fn):
18
+ if torchvision.extension._has_ops():
19
+ get_meta_lib().impl(getattr(getattr(torch.ops.torchvision, op_name), overload_name), fn)
20
+ return fn
21
+
22
+ return wrapper
23
+
24
+
25
+ @register_meta("roi_align")
26
+ def meta_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio, aligned):
27
+ torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]")
28
+ torch._check(
29
+ input.dtype == rois.dtype,
30
+ lambda: (
31
+ "Expected tensor for input to have the same type as tensor for rois; "
32
+ f"but type {input.dtype} does not equal {rois.dtype}"
33
+ ),
34
+ )
35
+ num_rois = rois.size(0)
36
+ channels = input.size(1)
37
+ return input.new_empty((num_rois, channels, pooled_height, pooled_width))
38
+
39
+
40
+ @register_meta("_roi_align_backward")
41
+ def meta_roi_align_backward(
42
+ grad, rois, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width, sampling_ratio, aligned
43
+ ):
44
+ torch._check(
45
+ grad.dtype == rois.dtype,
46
+ lambda: (
47
+ "Expected tensor for grad to have the same type as tensor for rois; "
48
+ f"but type {grad.dtype} does not equal {rois.dtype}"
49
+ ),
50
+ )
51
+ return grad.new_empty((batch_size, channels, height, width))
52
+
53
+
54
+ @register_meta("ps_roi_align")
55
+ def meta_ps_roi_align(input, rois, spatial_scale, pooled_height, pooled_width, sampling_ratio):
56
+ torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]")
57
+ torch._check(
58
+ input.dtype == rois.dtype,
59
+ lambda: (
60
+ "Expected tensor for input to have the same type as tensor for rois; "
61
+ f"but type {input.dtype} does not equal {rois.dtype}"
62
+ ),
63
+ )
64
+ channels = input.size(1)
65
+ torch._check(
66
+ channels % (pooled_height * pooled_width) == 0,
67
+ "input channels must be a multiple of pooling height * pooling width",
68
+ )
69
+
70
+ num_rois = rois.size(0)
71
+ out_size = (num_rois, channels // (pooled_height * pooled_width), pooled_height, pooled_width)
72
+ return input.new_empty(out_size), torch.empty(out_size, dtype=torch.int32, device="meta")
73
+
74
+
75
+ @register_meta("_ps_roi_align_backward")
76
+ def meta_ps_roi_align_backward(
77
+ grad,
78
+ rois,
79
+ channel_mapping,
80
+ spatial_scale,
81
+ pooled_height,
82
+ pooled_width,
83
+ sampling_ratio,
84
+ batch_size,
85
+ channels,
86
+ height,
87
+ width,
88
+ ):
89
+ torch._check(
90
+ grad.dtype == rois.dtype,
91
+ lambda: (
92
+ "Expected tensor for grad to have the same type as tensor for rois; "
93
+ f"but type {grad.dtype} does not equal {rois.dtype}"
94
+ ),
95
+ )
96
+ return grad.new_empty((batch_size, channels, height, width))
97
+
98
+
99
+ @register_meta("roi_pool")
100
+ def meta_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width):
101
+ torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]")
102
+ torch._check(
103
+ input.dtype == rois.dtype,
104
+ lambda: (
105
+ "Expected tensor for input to have the same type as tensor for rois; "
106
+ f"but type {input.dtype} does not equal {rois.dtype}"
107
+ ),
108
+ )
109
+ num_rois = rois.size(0)
110
+ channels = input.size(1)
111
+ out_size = (num_rois, channels, pooled_height, pooled_width)
112
+ return input.new_empty(out_size), torch.empty(out_size, device="meta", dtype=torch.int32)
113
+
114
+
115
+ @register_meta("_roi_pool_backward")
116
+ def meta_roi_pool_backward(
117
+ grad, rois, argmax, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width
118
+ ):
119
+ torch._check(
120
+ grad.dtype == rois.dtype,
121
+ lambda: (
122
+ "Expected tensor for grad to have the same type as tensor for rois; "
123
+ f"but type {grad.dtype} does not equal {rois.dtype}"
124
+ ),
125
+ )
126
+ return grad.new_empty((batch_size, channels, height, width))
127
+
128
+
129
+ @register_meta("ps_roi_pool")
130
+ def meta_ps_roi_pool(input, rois, spatial_scale, pooled_height, pooled_width):
131
+ torch._check(rois.size(1) == 5, lambda: "rois must have shape as Tensor[K, 5]")
132
+ torch._check(
133
+ input.dtype == rois.dtype,
134
+ lambda: (
135
+ "Expected tensor for input to have the same type as tensor for rois; "
136
+ f"but type {input.dtype} does not equal {rois.dtype}"
137
+ ),
138
+ )
139
+ channels = input.size(1)
140
+ torch._check(
141
+ channels % (pooled_height * pooled_width) == 0,
142
+ "input channels must be a multiple of pooling height * pooling width",
143
+ )
144
+ num_rois = rois.size(0)
145
+ out_size = (num_rois, channels // (pooled_height * pooled_width), pooled_height, pooled_width)
146
+ return input.new_empty(out_size), torch.empty(out_size, device="meta", dtype=torch.int32)
147
+
148
+
149
+ @register_meta("_ps_roi_pool_backward")
150
+ def meta_ps_roi_pool_backward(
151
+ grad, rois, channel_mapping, spatial_scale, pooled_height, pooled_width, batch_size, channels, height, width
152
+ ):
153
+ torch._check(
154
+ grad.dtype == rois.dtype,
155
+ lambda: (
156
+ "Expected tensor for grad to have the same type as tensor for rois; "
157
+ f"but type {grad.dtype} does not equal {rois.dtype}"
158
+ ),
159
+ )
160
+ return grad.new_empty((batch_size, channels, height, width))
161
+
162
+
163
+ @torch._custom_ops.impl_abstract("torchvision::nms")
164
+ def meta_nms(dets, scores, iou_threshold):
165
+ torch._check(dets.dim() == 2, lambda: f"boxes should be a 2d tensor, got {dets.dim()}D")
166
+ torch._check(dets.size(1) == 4, lambda: f"boxes should have 4 elements in dimension 1, got {dets.size(1)}")
167
+ torch._check(scores.dim() == 1, lambda: f"scores should be a 1d tensor, got {scores.dim()}")
168
+ torch._check(
169
+ dets.size(0) == scores.size(0),
170
+ lambda: f"boxes and scores should have same number of elements in dimension 0, got {dets.size(0)} and {scores.size(0)}",
171
+ )
172
+ ctx = torch._custom_ops.get_ctx()
173
+ num_to_keep = ctx.create_unbacked_symint()
174
+ return dets.new_empty(num_to_keep, dtype=torch.long)
175
+
176
+
177
+ @register_meta("deform_conv2d")
178
+ def meta_deform_conv2d(
179
+ input,
180
+ weight,
181
+ offset,
182
+ mask,
183
+ bias,
184
+ stride_h,
185
+ stride_w,
186
+ pad_h,
187
+ pad_w,
188
+ dil_h,
189
+ dil_w,
190
+ n_weight_grps,
191
+ n_offset_grps,
192
+ use_mask,
193
+ ):
194
+
195
+ out_height, out_width = offset.shape[-2:]
196
+ out_channels = weight.shape[0]
197
+ batch_size = input.shape[0]
198
+ return input.new_empty((batch_size, out_channels, out_height, out_width))
199
+
200
+
201
+ @register_meta("_deform_conv2d_backward")
202
+ def meta_deform_conv2d_backward(
203
+ grad,
204
+ input,
205
+ weight,
206
+ offset,
207
+ mask,
208
+ bias,
209
+ stride_h,
210
+ stride_w,
211
+ pad_h,
212
+ pad_w,
213
+ dilation_h,
214
+ dilation_w,
215
+ groups,
216
+ offset_groups,
217
+ use_mask,
218
+ ):
219
+
220
+ grad_input = input.new_empty(input.shape)
221
+ grad_weight = weight.new_empty(weight.shape)
222
+ grad_offset = offset.new_empty(offset.shape)
223
+ grad_mask = mask.new_empty(mask.shape)
224
+ grad_bias = bias.new_empty(bias.shape)
225
+ return grad_input, grad_weight, grad_offset, grad_mask, grad_bias
vlmpy310/lib/python3.10/site-packages/torchvision/_utils.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import enum
2
+ from typing import Sequence, Type, TypeVar
3
+
4
+ T = TypeVar("T", bound=enum.Enum)
5
+
6
+
7
+ class StrEnumMeta(enum.EnumMeta):
8
+ auto = enum.auto
9
+
10
+ def from_str(self: Type[T], member: str) -> T: # type: ignore[misc]
11
+ try:
12
+ return self[member]
13
+ except KeyError:
14
+ # TODO: use `add_suggestion` from torchvision.prototype.utils._internal to improve the error message as
15
+ # soon as it is migrated.
16
+ raise ValueError(f"Unknown value '{member}' for {self.__name__}.") from None
17
+
18
+
19
+ class StrEnum(enum.Enum, metaclass=StrEnumMeta):
20
+ pass
21
+
22
+
23
+ def sequence_to_str(seq: Sequence, separate_last: str = "") -> str:
24
+ if not seq:
25
+ return ""
26
+ if len(seq) == 1:
27
+ return f"'{seq[0]}'"
28
+
29
+ head = "'" + "', '".join([str(item) for item in seq[:-1]]) + "'"
30
+ tail = f"{'' if separate_last and len(seq) == 2 else ','} {separate_last}'{seq[-1]}'"
31
+
32
+ return head + tail
vlmpy310/lib/python3.10/site-packages/torchvision/extension.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+
4
+ import torch
5
+
6
+ from ._internally_replaced_utils import _get_extension_path
7
+
8
+
9
+ _HAS_OPS = False
10
+
11
+
12
+ def _has_ops():
13
+ return False
14
+
15
+
16
+ try:
17
+ # On Windows Python-3.8.x has `os.add_dll_directory` call,
18
+ # which is called to configure dll search path.
19
+ # To find cuda related dlls we need to make sure the
20
+ # conda environment/bin path is configured Please take a look:
21
+ # https://stackoverflow.com/questions/59330863/cant-import-dll-module-in-python
22
+ # Please note: if some path can't be added using add_dll_directory we simply ignore this path
23
+ if os.name == "nt" and sys.version_info < (3, 9):
24
+ env_path = os.environ["PATH"]
25
+ path_arr = env_path.split(";")
26
+ for path in path_arr:
27
+ if os.path.exists(path):
28
+ try:
29
+ os.add_dll_directory(path) # type: ignore[attr-defined]
30
+ except Exception:
31
+ pass
32
+
33
+ lib_path = _get_extension_path("_C")
34
+ torch.ops.load_library(lib_path)
35
+ _HAS_OPS = True
36
+
37
+ def _has_ops(): # noqa: F811
38
+ return True
39
+
40
+ except (ImportError, OSError):
41
+ pass
42
+
43
+
44
+ def _assert_has_ops():
45
+ if not _has_ops():
46
+ raise RuntimeError(
47
+ "Couldn't load custom C++ ops. This can happen if your PyTorch and "
48
+ "torchvision versions are incompatible, or if you had errors while compiling "
49
+ "torchvision from source. For further information on the compatible versions, check "
50
+ "https://github.com/pytorch/vision#installation for the compatibility matrix. "
51
+ "Please check your PyTorch version with torch.__version__ and your torchvision "
52
+ "version with torchvision.__version__ and verify if they are compatible, and if not "
53
+ "please reinstall torchvision so that it matches your PyTorch install."
54
+ )
55
+
56
+
57
+ def _check_cuda_version():
58
+ """
59
+ Make sure that CUDA versions match between the pytorch install and torchvision install
60
+ """
61
+ if not _HAS_OPS:
62
+ return -1
63
+ from torch.version import cuda as torch_version_cuda
64
+
65
+ _version = torch.ops.torchvision._cuda_version()
66
+ if _version != -1 and torch_version_cuda is not None:
67
+ tv_version = str(_version)
68
+ if int(tv_version) < 10000:
69
+ tv_major = int(tv_version[0])
70
+ tv_minor = int(tv_version[2])
71
+ else:
72
+ tv_major = int(tv_version[0:2])
73
+ tv_minor = int(tv_version[3])
74
+ t_version = torch_version_cuda.split(".")
75
+ t_major = int(t_version[0])
76
+ t_minor = int(t_version[1])
77
+ if t_major != tv_major:
78
+ raise RuntimeError(
79
+ "Detected that PyTorch and torchvision were compiled with different CUDA major versions. "
80
+ f"PyTorch has CUDA Version={t_major}.{t_minor} and torchvision has "
81
+ f"CUDA Version={tv_major}.{tv_minor}. "
82
+ "Please reinstall the torchvision that matches your PyTorch install."
83
+ )
84
+ return _version
85
+
86
+
87
+ def _load_library(lib_name):
88
+ lib_path = _get_extension_path(lib_name)
89
+ torch.ops.load_library(lib_path)
90
+
91
+
92
+ _check_cuda_version()
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .transforms import *
2
+ from .autoaugment import *
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (226 Bytes). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_functional_pil.cpython-310.pyc ADDED
Binary file (9.71 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_functional_tensor.cpython-310.pyc ADDED
Binary file (24.8 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_functional_video.cpython-310.pyc ADDED
Binary file (4.05 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_presets.cpython-310.pyc ADDED
Binary file (7.67 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/_transforms_video.cpython-310.pyc ADDED
Binary file (6.44 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/autoaugment.cpython-310.pyc ADDED
Binary file (20.1 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/functional.cpython-310.pyc ADDED
Binary file (55.2 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/__pycache__/transforms.cpython-310.pyc ADDED
Binary file (82.9 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_functional_pil.py ADDED
@@ -0,0 +1,393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numbers
2
+ from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ from PIL import Image, ImageEnhance, ImageOps
7
+
8
+ try:
9
+ import accimage
10
+ except ImportError:
11
+ accimage = None
12
+
13
+
14
+ @torch.jit.unused
15
+ def _is_pil_image(img: Any) -> bool:
16
+ if accimage is not None:
17
+ return isinstance(img, (Image.Image, accimage.Image))
18
+ else:
19
+ return isinstance(img, Image.Image)
20
+
21
+
22
+ @torch.jit.unused
23
+ def get_dimensions(img: Any) -> List[int]:
24
+ if _is_pil_image(img):
25
+ if hasattr(img, "getbands"):
26
+ channels = len(img.getbands())
27
+ else:
28
+ channels = img.channels
29
+ width, height = img.size
30
+ return [channels, height, width]
31
+ raise TypeError(f"Unexpected type {type(img)}")
32
+
33
+
34
+ @torch.jit.unused
35
+ def get_image_size(img: Any) -> List[int]:
36
+ if _is_pil_image(img):
37
+ return list(img.size)
38
+ raise TypeError(f"Unexpected type {type(img)}")
39
+
40
+
41
+ @torch.jit.unused
42
+ def get_image_num_channels(img: Any) -> int:
43
+ if _is_pil_image(img):
44
+ if hasattr(img, "getbands"):
45
+ return len(img.getbands())
46
+ else:
47
+ return img.channels
48
+ raise TypeError(f"Unexpected type {type(img)}")
49
+
50
+
51
+ @torch.jit.unused
52
+ def hflip(img: Image.Image) -> Image.Image:
53
+ if not _is_pil_image(img):
54
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
55
+
56
+ return img.transpose(Image.FLIP_LEFT_RIGHT)
57
+
58
+
59
+ @torch.jit.unused
60
+ def vflip(img: Image.Image) -> Image.Image:
61
+ if not _is_pil_image(img):
62
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
63
+
64
+ return img.transpose(Image.FLIP_TOP_BOTTOM)
65
+
66
+
67
+ @torch.jit.unused
68
+ def adjust_brightness(img: Image.Image, brightness_factor: float) -> Image.Image:
69
+ if not _is_pil_image(img):
70
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
71
+
72
+ enhancer = ImageEnhance.Brightness(img)
73
+ img = enhancer.enhance(brightness_factor)
74
+ return img
75
+
76
+
77
+ @torch.jit.unused
78
+ def adjust_contrast(img: Image.Image, contrast_factor: float) -> Image.Image:
79
+ if not _is_pil_image(img):
80
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
81
+
82
+ enhancer = ImageEnhance.Contrast(img)
83
+ img = enhancer.enhance(contrast_factor)
84
+ return img
85
+
86
+
87
+ @torch.jit.unused
88
+ def adjust_saturation(img: Image.Image, saturation_factor: float) -> Image.Image:
89
+ if not _is_pil_image(img):
90
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
91
+
92
+ enhancer = ImageEnhance.Color(img)
93
+ img = enhancer.enhance(saturation_factor)
94
+ return img
95
+
96
+
97
+ @torch.jit.unused
98
+ def adjust_hue(img: Image.Image, hue_factor: float) -> Image.Image:
99
+ if not (-0.5 <= hue_factor <= 0.5):
100
+ raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].")
101
+
102
+ if not _is_pil_image(img):
103
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
104
+
105
+ input_mode = img.mode
106
+ if input_mode in {"L", "1", "I", "F"}:
107
+ return img
108
+
109
+ h, s, v = img.convert("HSV").split()
110
+
111
+ np_h = np.array(h, dtype=np.uint8)
112
+ # uint8 addition take cares of rotation across boundaries
113
+ with np.errstate(over="ignore"):
114
+ np_h += np.uint8(hue_factor * 255)
115
+ h = Image.fromarray(np_h, "L")
116
+
117
+ img = Image.merge("HSV", (h, s, v)).convert(input_mode)
118
+ return img
119
+
120
+
121
+ @torch.jit.unused
122
+ def adjust_gamma(
123
+ img: Image.Image,
124
+ gamma: float,
125
+ gain: float = 1.0,
126
+ ) -> Image.Image:
127
+
128
+ if not _is_pil_image(img):
129
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
130
+
131
+ if gamma < 0:
132
+ raise ValueError("Gamma should be a non-negative real number")
133
+
134
+ input_mode = img.mode
135
+ img = img.convert("RGB")
136
+ gamma_map = [int((255 + 1 - 1e-3) * gain * pow(ele / 255.0, gamma)) for ele in range(256)] * 3
137
+ img = img.point(gamma_map) # use PIL's point-function to accelerate this part
138
+
139
+ img = img.convert(input_mode)
140
+ return img
141
+
142
+
143
+ @torch.jit.unused
144
+ def pad(
145
+ img: Image.Image,
146
+ padding: Union[int, List[int], Tuple[int, ...]],
147
+ fill: Optional[Union[float, List[float], Tuple[float, ...]]] = 0,
148
+ padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant",
149
+ ) -> Image.Image:
150
+
151
+ if not _is_pil_image(img):
152
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
153
+
154
+ if not isinstance(padding, (numbers.Number, tuple, list)):
155
+ raise TypeError("Got inappropriate padding arg")
156
+ if fill is not None and not isinstance(fill, (numbers.Number, tuple, list)):
157
+ raise TypeError("Got inappropriate fill arg")
158
+ if not isinstance(padding_mode, str):
159
+ raise TypeError("Got inappropriate padding_mode arg")
160
+
161
+ if isinstance(padding, list):
162
+ padding = tuple(padding)
163
+
164
+ if isinstance(padding, tuple) and len(padding) not in [1, 2, 4]:
165
+ raise ValueError(f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple")
166
+
167
+ if isinstance(padding, tuple) and len(padding) == 1:
168
+ # Compatibility with `functional_tensor.pad`
169
+ padding = padding[0]
170
+
171
+ if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
172
+ raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")
173
+
174
+ if padding_mode == "constant":
175
+ opts = _parse_fill(fill, img, name="fill")
176
+ if img.mode == "P":
177
+ palette = img.getpalette()
178
+ image = ImageOps.expand(img, border=padding, **opts)
179
+ image.putpalette(palette)
180
+ return image
181
+
182
+ return ImageOps.expand(img, border=padding, **opts)
183
+ else:
184
+ if isinstance(padding, int):
185
+ pad_left = pad_right = pad_top = pad_bottom = padding
186
+ if isinstance(padding, tuple) and len(padding) == 2:
187
+ pad_left = pad_right = padding[0]
188
+ pad_top = pad_bottom = padding[1]
189
+ if isinstance(padding, tuple) and len(padding) == 4:
190
+ pad_left = padding[0]
191
+ pad_top = padding[1]
192
+ pad_right = padding[2]
193
+ pad_bottom = padding[3]
194
+
195
+ p = [pad_left, pad_top, pad_right, pad_bottom]
196
+ cropping = -np.minimum(p, 0)
197
+
198
+ if cropping.any():
199
+ crop_left, crop_top, crop_right, crop_bottom = cropping
200
+ img = img.crop((crop_left, crop_top, img.width - crop_right, img.height - crop_bottom))
201
+
202
+ pad_left, pad_top, pad_right, pad_bottom = np.maximum(p, 0)
203
+
204
+ if img.mode == "P":
205
+ palette = img.getpalette()
206
+ img = np.asarray(img)
207
+ img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), mode=padding_mode)
208
+ img = Image.fromarray(img)
209
+ img.putpalette(palette)
210
+ return img
211
+
212
+ img = np.asarray(img)
213
+ # RGB image
214
+ if len(img.shape) == 3:
215
+ img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right), (0, 0)), padding_mode)
216
+ # Grayscale image
217
+ if len(img.shape) == 2:
218
+ img = np.pad(img, ((pad_top, pad_bottom), (pad_left, pad_right)), padding_mode)
219
+
220
+ return Image.fromarray(img)
221
+
222
+
223
+ @torch.jit.unused
224
+ def crop(
225
+ img: Image.Image,
226
+ top: int,
227
+ left: int,
228
+ height: int,
229
+ width: int,
230
+ ) -> Image.Image:
231
+
232
+ if not _is_pil_image(img):
233
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
234
+
235
+ return img.crop((left, top, left + width, top + height))
236
+
237
+
238
+ @torch.jit.unused
239
+ def resize(
240
+ img: Image.Image,
241
+ size: Union[List[int], int],
242
+ interpolation: int = Image.BILINEAR,
243
+ ) -> Image.Image:
244
+
245
+ if not _is_pil_image(img):
246
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
247
+ if not (isinstance(size, list) and len(size) == 2):
248
+ raise TypeError(f"Got inappropriate size arg: {size}")
249
+
250
+ return img.resize(tuple(size[::-1]), interpolation)
251
+
252
+
253
+ @torch.jit.unused
254
+ def _parse_fill(
255
+ fill: Optional[Union[float, List[float], Tuple[float, ...]]],
256
+ img: Image.Image,
257
+ name: str = "fillcolor",
258
+ ) -> Dict[str, Optional[Union[float, List[float], Tuple[float, ...]]]]:
259
+
260
+ # Process fill color for affine transforms
261
+ num_channels = get_image_num_channels(img)
262
+ if fill is None:
263
+ fill = 0
264
+ if isinstance(fill, (int, float)) and num_channels > 1:
265
+ fill = tuple([fill] * num_channels)
266
+ if isinstance(fill, (list, tuple)):
267
+ if len(fill) == 1:
268
+ fill = fill * num_channels
269
+ elif len(fill) != num_channels:
270
+ msg = "The number of elements in 'fill' does not match the number of channels of the image ({} != {})"
271
+ raise ValueError(msg.format(len(fill), num_channels))
272
+
273
+ fill = tuple(fill) # type: ignore[arg-type]
274
+
275
+ if img.mode != "F":
276
+ if isinstance(fill, (list, tuple)):
277
+ fill = tuple(int(x) for x in fill)
278
+ else:
279
+ fill = int(fill)
280
+
281
+ return {name: fill}
282
+
283
+
284
+ @torch.jit.unused
285
+ def affine(
286
+ img: Image.Image,
287
+ matrix: List[float],
288
+ interpolation: int = Image.NEAREST,
289
+ fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None,
290
+ ) -> Image.Image:
291
+
292
+ if not _is_pil_image(img):
293
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
294
+
295
+ output_size = img.size
296
+ opts = _parse_fill(fill, img)
297
+ return img.transform(output_size, Image.AFFINE, matrix, interpolation, **opts)
298
+
299
+
300
+ @torch.jit.unused
301
+ def rotate(
302
+ img: Image.Image,
303
+ angle: float,
304
+ interpolation: int = Image.NEAREST,
305
+ expand: bool = False,
306
+ center: Optional[Tuple[int, int]] = None,
307
+ fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None,
308
+ ) -> Image.Image:
309
+
310
+ if not _is_pil_image(img):
311
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
312
+
313
+ opts = _parse_fill(fill, img)
314
+ return img.rotate(angle, interpolation, expand, center, **opts)
315
+
316
+
317
+ @torch.jit.unused
318
+ def perspective(
319
+ img: Image.Image,
320
+ perspective_coeffs: List[float],
321
+ interpolation: int = Image.BICUBIC,
322
+ fill: Optional[Union[int, float, Sequence[int], Sequence[float]]] = None,
323
+ ) -> Image.Image:
324
+
325
+ if not _is_pil_image(img):
326
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
327
+
328
+ opts = _parse_fill(fill, img)
329
+
330
+ return img.transform(img.size, Image.PERSPECTIVE, perspective_coeffs, interpolation, **opts)
331
+
332
+
333
+ @torch.jit.unused
334
+ def to_grayscale(img: Image.Image, num_output_channels: int) -> Image.Image:
335
+ if not _is_pil_image(img):
336
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
337
+
338
+ if num_output_channels == 1:
339
+ img = img.convert("L")
340
+ elif num_output_channels == 3:
341
+ img = img.convert("L")
342
+ np_img = np.array(img, dtype=np.uint8)
343
+ np_img = np.dstack([np_img, np_img, np_img])
344
+ img = Image.fromarray(np_img, "RGB")
345
+ else:
346
+ raise ValueError("num_output_channels should be either 1 or 3")
347
+
348
+ return img
349
+
350
+
351
+ @torch.jit.unused
352
+ def invert(img: Image.Image) -> Image.Image:
353
+ if not _is_pil_image(img):
354
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
355
+ return ImageOps.invert(img)
356
+
357
+
358
+ @torch.jit.unused
359
+ def posterize(img: Image.Image, bits: int) -> Image.Image:
360
+ if not _is_pil_image(img):
361
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
362
+ return ImageOps.posterize(img, bits)
363
+
364
+
365
+ @torch.jit.unused
366
+ def solarize(img: Image.Image, threshold: int) -> Image.Image:
367
+ if not _is_pil_image(img):
368
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
369
+ return ImageOps.solarize(img, threshold)
370
+
371
+
372
+ @torch.jit.unused
373
+ def adjust_sharpness(img: Image.Image, sharpness_factor: float) -> Image.Image:
374
+ if not _is_pil_image(img):
375
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
376
+
377
+ enhancer = ImageEnhance.Sharpness(img)
378
+ img = enhancer.enhance(sharpness_factor)
379
+ return img
380
+
381
+
382
+ @torch.jit.unused
383
+ def autocontrast(img: Image.Image) -> Image.Image:
384
+ if not _is_pil_image(img):
385
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
386
+ return ImageOps.autocontrast(img)
387
+
388
+
389
+ @torch.jit.unused
390
+ def equalize(img: Image.Image) -> Image.Image:
391
+ if not _is_pil_image(img):
392
+ raise TypeError(f"img should be PIL Image. Got {type(img)}")
393
+ return ImageOps.equalize(img)
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_functional_tensor.py ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch import Tensor
6
+ from torch.nn.functional import conv2d, grid_sample, interpolate, pad as torch_pad
7
+
8
+
9
+ def _is_tensor_a_torch_image(x: Tensor) -> bool:
10
+ return x.ndim >= 2
11
+
12
+
13
+ def _assert_image_tensor(img: Tensor) -> None:
14
+ if not _is_tensor_a_torch_image(img):
15
+ raise TypeError("Tensor is not a torch image.")
16
+
17
+
18
+ def get_dimensions(img: Tensor) -> List[int]:
19
+ _assert_image_tensor(img)
20
+ channels = 1 if img.ndim == 2 else img.shape[-3]
21
+ height, width = img.shape[-2:]
22
+ return [channels, height, width]
23
+
24
+
25
+ def get_image_size(img: Tensor) -> List[int]:
26
+ # Returns (w, h) of tensor image
27
+ _assert_image_tensor(img)
28
+ return [img.shape[-1], img.shape[-2]]
29
+
30
+
31
+ def get_image_num_channels(img: Tensor) -> int:
32
+ _assert_image_tensor(img)
33
+ if img.ndim == 2:
34
+ return 1
35
+ elif img.ndim > 2:
36
+ return img.shape[-3]
37
+
38
+ raise TypeError(f"Input ndim should be 2 or more. Got {img.ndim}")
39
+
40
+
41
+ def _max_value(dtype: torch.dtype) -> int:
42
+ if dtype == torch.uint8:
43
+ return 255
44
+ elif dtype == torch.int8:
45
+ return 127
46
+ elif dtype == torch.int16:
47
+ return 32767
48
+ elif dtype == torch.int32:
49
+ return 2147483647
50
+ elif dtype == torch.int64:
51
+ return 9223372036854775807
52
+ else:
53
+ # This is only here for completeness. This value is implicitly assumed in a lot of places so changing it is not
54
+ # easy.
55
+ return 1
56
+
57
+
58
+ def _assert_channels(img: Tensor, permitted: List[int]) -> None:
59
+ c = get_dimensions(img)[0]
60
+ if c not in permitted:
61
+ raise TypeError(f"Input image tensor permitted channel values are {permitted}, but found {c}")
62
+
63
+
64
+ def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor:
65
+ if image.dtype == dtype:
66
+ return image
67
+
68
+ if image.is_floating_point():
69
+
70
+ # TODO: replace with dtype.is_floating_point when torchscript supports it
71
+ if torch.tensor(0, dtype=dtype).is_floating_point():
72
+ return image.to(dtype)
73
+
74
+ # float to int
75
+ if (image.dtype == torch.float32 and dtype in (torch.int32, torch.int64)) or (
76
+ image.dtype == torch.float64 and dtype == torch.int64
77
+ ):
78
+ msg = f"The cast from {image.dtype} to {dtype} cannot be performed safely."
79
+ raise RuntimeError(msg)
80
+
81
+ # https://github.com/pytorch/vision/pull/2078#issuecomment-612045321
82
+ # For data in the range 0-1, (float * 255).to(uint) is only 255
83
+ # when float is exactly 1.0.
84
+ # `max + 1 - epsilon` provides more evenly distributed mapping of
85
+ # ranges of floats to ints.
86
+ eps = 1e-3
87
+ max_val = float(_max_value(dtype))
88
+ result = image.mul(max_val + 1.0 - eps)
89
+ return result.to(dtype)
90
+ else:
91
+ input_max = float(_max_value(image.dtype))
92
+
93
+ # int to float
94
+ # TODO: replace with dtype.is_floating_point when torchscript supports it
95
+ if torch.tensor(0, dtype=dtype).is_floating_point():
96
+ image = image.to(dtype)
97
+ return image / input_max
98
+
99
+ output_max = float(_max_value(dtype))
100
+
101
+ # int to int
102
+ if input_max > output_max:
103
+ # factor should be forced to int for torch jit script
104
+ # otherwise factor is a float and image // factor can produce different results
105
+ factor = int((input_max + 1) // (output_max + 1))
106
+ image = torch.div(image, factor, rounding_mode="floor")
107
+ return image.to(dtype)
108
+ else:
109
+ # factor should be forced to int for torch jit script
110
+ # otherwise factor is a float and image * factor can produce different results
111
+ factor = int((output_max + 1) // (input_max + 1))
112
+ image = image.to(dtype)
113
+ return image * factor
114
+
115
+
116
+ def vflip(img: Tensor) -> Tensor:
117
+ _assert_image_tensor(img)
118
+
119
+ return img.flip(-2)
120
+
121
+
122
+ def hflip(img: Tensor) -> Tensor:
123
+ _assert_image_tensor(img)
124
+
125
+ return img.flip(-1)
126
+
127
+
128
+ def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
129
+ _assert_image_tensor(img)
130
+
131
+ _, h, w = get_dimensions(img)
132
+ right = left + width
133
+ bottom = top + height
134
+
135
+ if left < 0 or top < 0 or right > w or bottom > h:
136
+ padding_ltrb = [
137
+ max(-left + min(0, right), 0),
138
+ max(-top + min(0, bottom), 0),
139
+ max(right - max(w, left), 0),
140
+ max(bottom - max(h, top), 0),
141
+ ]
142
+ return pad(img[..., max(top, 0) : bottom, max(left, 0) : right], padding_ltrb, fill=0)
143
+ return img[..., top:bottom, left:right]
144
+
145
+
146
+ def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor:
147
+ if img.ndim < 3:
148
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
149
+ _assert_channels(img, [1, 3])
150
+
151
+ if num_output_channels not in (1, 3):
152
+ raise ValueError("num_output_channels should be either 1 or 3")
153
+
154
+ if img.shape[-3] == 3:
155
+ r, g, b = img.unbind(dim=-3)
156
+ # This implementation closely follows the TF one:
157
+ # https://github.com/tensorflow/tensorflow/blob/v2.3.0/tensorflow/python/ops/image_ops_impl.py#L2105-L2138
158
+ l_img = (0.2989 * r + 0.587 * g + 0.114 * b).to(img.dtype)
159
+ l_img = l_img.unsqueeze(dim=-3)
160
+ else:
161
+ l_img = img.clone()
162
+
163
+ if num_output_channels == 3:
164
+ return l_img.expand(img.shape)
165
+
166
+ return l_img
167
+
168
+
169
+ def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor:
170
+ if brightness_factor < 0:
171
+ raise ValueError(f"brightness_factor ({brightness_factor}) is not non-negative.")
172
+
173
+ _assert_image_tensor(img)
174
+
175
+ _assert_channels(img, [1, 3])
176
+
177
+ return _blend(img, torch.zeros_like(img), brightness_factor)
178
+
179
+
180
+ def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor:
181
+ if contrast_factor < 0:
182
+ raise ValueError(f"contrast_factor ({contrast_factor}) is not non-negative.")
183
+
184
+ _assert_image_tensor(img)
185
+
186
+ _assert_channels(img, [3, 1])
187
+ c = get_dimensions(img)[0]
188
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
189
+ if c == 3:
190
+ mean = torch.mean(rgb_to_grayscale(img).to(dtype), dim=(-3, -2, -1), keepdim=True)
191
+ else:
192
+ mean = torch.mean(img.to(dtype), dim=(-3, -2, -1), keepdim=True)
193
+
194
+ return _blend(img, mean, contrast_factor)
195
+
196
+
197
+ def adjust_hue(img: Tensor, hue_factor: float) -> Tensor:
198
+ if not (-0.5 <= hue_factor <= 0.5):
199
+ raise ValueError(f"hue_factor ({hue_factor}) is not in [-0.5, 0.5].")
200
+
201
+ if not (isinstance(img, torch.Tensor)):
202
+ raise TypeError("Input img should be Tensor image")
203
+
204
+ _assert_image_tensor(img)
205
+
206
+ _assert_channels(img, [1, 3])
207
+ if get_dimensions(img)[0] == 1: # Match PIL behaviour
208
+ return img
209
+
210
+ orig_dtype = img.dtype
211
+ img = convert_image_dtype(img, torch.float32)
212
+
213
+ img = _rgb2hsv(img)
214
+ h, s, v = img.unbind(dim=-3)
215
+ h = (h + hue_factor) % 1.0
216
+ img = torch.stack((h, s, v), dim=-3)
217
+ img_hue_adj = _hsv2rgb(img)
218
+
219
+ return convert_image_dtype(img_hue_adj, orig_dtype)
220
+
221
+
222
+ def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor:
223
+ if saturation_factor < 0:
224
+ raise ValueError(f"saturation_factor ({saturation_factor}) is not non-negative.")
225
+
226
+ _assert_image_tensor(img)
227
+
228
+ _assert_channels(img, [1, 3])
229
+
230
+ if get_dimensions(img)[0] == 1: # Match PIL behaviour
231
+ return img
232
+
233
+ return _blend(img, rgb_to_grayscale(img), saturation_factor)
234
+
235
+
236
+ def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor:
237
+ if not isinstance(img, torch.Tensor):
238
+ raise TypeError("Input img should be a Tensor.")
239
+
240
+ _assert_channels(img, [1, 3])
241
+
242
+ if gamma < 0:
243
+ raise ValueError("Gamma should be a non-negative real number")
244
+
245
+ result = img
246
+ dtype = img.dtype
247
+ if not torch.is_floating_point(img):
248
+ result = convert_image_dtype(result, torch.float32)
249
+
250
+ result = (gain * result**gamma).clamp(0, 1)
251
+
252
+ result = convert_image_dtype(result, dtype)
253
+ return result
254
+
255
+
256
+ def _blend(img1: Tensor, img2: Tensor, ratio: float) -> Tensor:
257
+ ratio = float(ratio)
258
+ bound = _max_value(img1.dtype)
259
+ return (ratio * img1 + (1.0 - ratio) * img2).clamp(0, bound).to(img1.dtype)
260
+
261
+
262
+ def _rgb2hsv(img: Tensor) -> Tensor:
263
+ r, g, b = img.unbind(dim=-3)
264
+
265
+ # Implementation is based on https://github.com/python-pillow/Pillow/blob/4174d4267616897df3746d315d5a2d0f82c656ee/
266
+ # src/libImaging/Convert.c#L330
267
+ maxc = torch.max(img, dim=-3).values
268
+ minc = torch.min(img, dim=-3).values
269
+
270
+ # The algorithm erases S and H channel where `maxc = minc`. This avoids NaN
271
+ # from happening in the results, because
272
+ # + S channel has division by `maxc`, which is zero only if `maxc = minc`
273
+ # + H channel has division by `(maxc - minc)`.
274
+ #
275
+ # Instead of overwriting NaN afterwards, we just prevent it from occurring, so
276
+ # we don't need to deal with it in case we save the NaN in a buffer in
277
+ # backprop, if it is ever supported, but it doesn't hurt to do so.
278
+ eqc = maxc == minc
279
+
280
+ cr = maxc - minc
281
+ # Since `eqc => cr = 0`, replacing denominator with 1 when `eqc` is fine.
282
+ ones = torch.ones_like(maxc)
283
+ s = cr / torch.where(eqc, ones, maxc)
284
+ # Note that `eqc => maxc = minc = r = g = b`. So the following calculation
285
+ # of `h` would reduce to `bc - gc + 2 + rc - bc + 4 + rc - bc = 6` so it
286
+ # would not matter what values `rc`, `gc`, and `bc` have here, and thus
287
+ # replacing denominator with 1 when `eqc` is fine.
288
+ cr_divisor = torch.where(eqc, ones, cr)
289
+ rc = (maxc - r) / cr_divisor
290
+ gc = (maxc - g) / cr_divisor
291
+ bc = (maxc - b) / cr_divisor
292
+
293
+ hr = (maxc == r) * (bc - gc)
294
+ hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc)
295
+ hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc)
296
+ h = hr + hg + hb
297
+ h = torch.fmod((h / 6.0 + 1.0), 1.0)
298
+ return torch.stack((h, s, maxc), dim=-3)
299
+
300
+
301
+ def _hsv2rgb(img: Tensor) -> Tensor:
302
+ h, s, v = img.unbind(dim=-3)
303
+ i = torch.floor(h * 6.0)
304
+ f = (h * 6.0) - i
305
+ i = i.to(dtype=torch.int32)
306
+
307
+ p = torch.clamp((v * (1.0 - s)), 0.0, 1.0)
308
+ q = torch.clamp((v * (1.0 - s * f)), 0.0, 1.0)
309
+ t = torch.clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0)
310
+ i = i % 6
311
+
312
+ mask = i.unsqueeze(dim=-3) == torch.arange(6, device=i.device).view(-1, 1, 1)
313
+
314
+ a1 = torch.stack((v, q, p, p, t, v), dim=-3)
315
+ a2 = torch.stack((t, v, v, q, p, p), dim=-3)
316
+ a3 = torch.stack((p, p, t, v, v, q), dim=-3)
317
+ a4 = torch.stack((a1, a2, a3), dim=-4)
318
+
319
+ return torch.einsum("...ijk, ...xijk -> ...xjk", mask.to(dtype=img.dtype), a4)
320
+
321
+
322
+ def _pad_symmetric(img: Tensor, padding: List[int]) -> Tensor:
323
+ # padding is left, right, top, bottom
324
+
325
+ # crop if needed
326
+ if padding[0] < 0 or padding[1] < 0 or padding[2] < 0 or padding[3] < 0:
327
+ neg_min_padding = [-min(x, 0) for x in padding]
328
+ crop_left, crop_right, crop_top, crop_bottom = neg_min_padding
329
+ img = img[..., crop_top : img.shape[-2] - crop_bottom, crop_left : img.shape[-1] - crop_right]
330
+ padding = [max(x, 0) for x in padding]
331
+
332
+ in_sizes = img.size()
333
+
334
+ _x_indices = [i for i in range(in_sizes[-1])] # [0, 1, 2, 3, ...]
335
+ left_indices = [i for i in range(padding[0] - 1, -1, -1)] # e.g. [3, 2, 1, 0]
336
+ right_indices = [-(i + 1) for i in range(padding[1])] # e.g. [-1, -2, -3]
337
+ x_indices = torch.tensor(left_indices + _x_indices + right_indices, device=img.device)
338
+
339
+ _y_indices = [i for i in range(in_sizes[-2])]
340
+ top_indices = [i for i in range(padding[2] - 1, -1, -1)]
341
+ bottom_indices = [-(i + 1) for i in range(padding[3])]
342
+ y_indices = torch.tensor(top_indices + _y_indices + bottom_indices, device=img.device)
343
+
344
+ ndim = img.ndim
345
+ if ndim == 3:
346
+ return img[:, y_indices[:, None], x_indices[None, :]]
347
+ elif ndim == 4:
348
+ return img[:, :, y_indices[:, None], x_indices[None, :]]
349
+ else:
350
+ raise RuntimeError("Symmetric padding of N-D tensors are not supported yet")
351
+
352
+
353
+ def _parse_pad_padding(padding: Union[int, List[int]]) -> List[int]:
354
+ if isinstance(padding, int):
355
+ if torch.jit.is_scripting():
356
+ # This maybe unreachable
357
+ raise ValueError("padding can't be an int while torchscripting, set it as a list [value, ]")
358
+ pad_left = pad_right = pad_top = pad_bottom = padding
359
+ elif len(padding) == 1:
360
+ pad_left = pad_right = pad_top = pad_bottom = padding[0]
361
+ elif len(padding) == 2:
362
+ pad_left = pad_right = padding[0]
363
+ pad_top = pad_bottom = padding[1]
364
+ else:
365
+ pad_left = padding[0]
366
+ pad_top = padding[1]
367
+ pad_right = padding[2]
368
+ pad_bottom = padding[3]
369
+
370
+ return [pad_left, pad_right, pad_top, pad_bottom]
371
+
372
+
373
+ def pad(
374
+ img: Tensor, padding: Union[int, List[int]], fill: Optional[Union[int, float]] = 0, padding_mode: str = "constant"
375
+ ) -> Tensor:
376
+ _assert_image_tensor(img)
377
+
378
+ if fill is None:
379
+ fill = 0
380
+
381
+ if not isinstance(padding, (int, tuple, list)):
382
+ raise TypeError("Got inappropriate padding arg")
383
+ if not isinstance(fill, (int, float)):
384
+ raise TypeError("Got inappropriate fill arg")
385
+ if not isinstance(padding_mode, str):
386
+ raise TypeError("Got inappropriate padding_mode arg")
387
+
388
+ if isinstance(padding, tuple):
389
+ padding = list(padding)
390
+
391
+ if isinstance(padding, list):
392
+ # TODO: Jit is failing on loading this op when scripted and saved
393
+ # https://github.com/pytorch/pytorch/issues/81100
394
+ if len(padding) not in [1, 2, 4]:
395
+ raise ValueError(
396
+ f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple"
397
+ )
398
+
399
+ if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
400
+ raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")
401
+
402
+ p = _parse_pad_padding(padding)
403
+
404
+ if padding_mode == "edge":
405
+ # remap padding_mode str
406
+ padding_mode = "replicate"
407
+ elif padding_mode == "symmetric":
408
+ # route to another implementation
409
+ return _pad_symmetric(img, p)
410
+
411
+ need_squeeze = False
412
+ if img.ndim < 4:
413
+ img = img.unsqueeze(dim=0)
414
+ need_squeeze = True
415
+
416
+ out_dtype = img.dtype
417
+ need_cast = False
418
+ if (padding_mode != "constant") and img.dtype not in (torch.float32, torch.float64):
419
+ # Here we temporarily cast input tensor to float
420
+ # until pytorch issue is resolved :
421
+ # https://github.com/pytorch/pytorch/issues/40763
422
+ need_cast = True
423
+ img = img.to(torch.float32)
424
+
425
+ if padding_mode in ("reflect", "replicate"):
426
+ img = torch_pad(img, p, mode=padding_mode)
427
+ else:
428
+ img = torch_pad(img, p, mode=padding_mode, value=float(fill))
429
+
430
+ if need_squeeze:
431
+ img = img.squeeze(dim=0)
432
+
433
+ if need_cast:
434
+ img = img.to(out_dtype)
435
+
436
+ return img
437
+
438
+
439
+ def resize(
440
+ img: Tensor,
441
+ size: List[int],
442
+ interpolation: str = "bilinear",
443
+ antialias: Optional[bool] = True,
444
+ ) -> Tensor:
445
+ _assert_image_tensor(img)
446
+
447
+ if isinstance(size, tuple):
448
+ size = list(size)
449
+
450
+ if antialias is None:
451
+ antialias = False
452
+
453
+ if antialias and interpolation not in ["bilinear", "bicubic"]:
454
+ # We manually set it to False to avoid an error downstream in interpolate()
455
+ # This behaviour is documented: the parameter is irrelevant for modes
456
+ # that are not bilinear or bicubic. We used to raise an error here, but
457
+ # now we don't as True is the default.
458
+ antialias = False
459
+
460
+ img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [torch.float32, torch.float64])
461
+
462
+ # Define align_corners to avoid warnings
463
+ align_corners = False if interpolation in ["bilinear", "bicubic"] else None
464
+
465
+ img = interpolate(img, size=size, mode=interpolation, align_corners=align_corners, antialias=antialias)
466
+
467
+ if interpolation == "bicubic" and out_dtype == torch.uint8:
468
+ img = img.clamp(min=0, max=255)
469
+
470
+ img = _cast_squeeze_out(img, need_cast=need_cast, need_squeeze=need_squeeze, out_dtype=out_dtype)
471
+
472
+ return img
473
+
474
+
475
+ def _assert_grid_transform_inputs(
476
+ img: Tensor,
477
+ matrix: Optional[List[float]],
478
+ interpolation: str,
479
+ fill: Optional[Union[int, float, List[float]]],
480
+ supported_interpolation_modes: List[str],
481
+ coeffs: Optional[List[float]] = None,
482
+ ) -> None:
483
+
484
+ if not (isinstance(img, torch.Tensor)):
485
+ raise TypeError("Input img should be Tensor")
486
+
487
+ _assert_image_tensor(img)
488
+
489
+ if matrix is not None and not isinstance(matrix, list):
490
+ raise TypeError("Argument matrix should be a list")
491
+
492
+ if matrix is not None and len(matrix) != 6:
493
+ raise ValueError("Argument matrix should have 6 float values")
494
+
495
+ if coeffs is not None and len(coeffs) != 8:
496
+ raise ValueError("Argument coeffs should have 8 float values")
497
+
498
+ if fill is not None and not isinstance(fill, (int, float, tuple, list)):
499
+ warnings.warn("Argument fill should be either int, float, tuple or list")
500
+
501
+ # Check fill
502
+ num_channels = get_dimensions(img)[0]
503
+ if fill is not None and isinstance(fill, (tuple, list)) and len(fill) > 1 and len(fill) != num_channels:
504
+ msg = (
505
+ "The number of elements in 'fill' cannot broadcast to match the number of "
506
+ "channels of the image ({} != {})"
507
+ )
508
+ raise ValueError(msg.format(len(fill), num_channels))
509
+
510
+ if interpolation not in supported_interpolation_modes:
511
+ raise ValueError(f"Interpolation mode '{interpolation}' is unsupported with Tensor input")
512
+
513
+
514
+ def _cast_squeeze_in(img: Tensor, req_dtypes: List[torch.dtype]) -> Tuple[Tensor, bool, bool, torch.dtype]:
515
+ need_squeeze = False
516
+ # make image NCHW
517
+ if img.ndim < 4:
518
+ img = img.unsqueeze(dim=0)
519
+ need_squeeze = True
520
+
521
+ out_dtype = img.dtype
522
+ need_cast = False
523
+ if out_dtype not in req_dtypes:
524
+ need_cast = True
525
+ req_dtype = req_dtypes[0]
526
+ img = img.to(req_dtype)
527
+ return img, need_cast, need_squeeze, out_dtype
528
+
529
+
530
+ def _cast_squeeze_out(img: Tensor, need_cast: bool, need_squeeze: bool, out_dtype: torch.dtype) -> Tensor:
531
+ if need_squeeze:
532
+ img = img.squeeze(dim=0)
533
+
534
+ if need_cast:
535
+ if out_dtype in (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64):
536
+ # it is better to round before cast
537
+ img = torch.round(img)
538
+ img = img.to(out_dtype)
539
+
540
+ return img
541
+
542
+
543
+ def _apply_grid_transform(
544
+ img: Tensor, grid: Tensor, mode: str, fill: Optional[Union[int, float, List[float]]]
545
+ ) -> Tensor:
546
+
547
+ img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [grid.dtype])
548
+
549
+ if img.shape[0] > 1:
550
+ # Apply same grid to a batch of images
551
+ grid = grid.expand(img.shape[0], grid.shape[1], grid.shape[2], grid.shape[3])
552
+
553
+ # Append a dummy mask for customized fill colors, should be faster than grid_sample() twice
554
+ if fill is not None:
555
+ mask = torch.ones((img.shape[0], 1, img.shape[2], img.shape[3]), dtype=img.dtype, device=img.device)
556
+ img = torch.cat((img, mask), dim=1)
557
+
558
+ img = grid_sample(img, grid, mode=mode, padding_mode="zeros", align_corners=False)
559
+
560
+ # Fill with required color
561
+ if fill is not None:
562
+ mask = img[:, -1:, :, :] # N * 1 * H * W
563
+ img = img[:, :-1, :, :] # N * C * H * W
564
+ mask = mask.expand_as(img)
565
+ fill_list, len_fill = (fill, len(fill)) if isinstance(fill, (tuple, list)) else ([float(fill)], 1)
566
+ fill_img = torch.tensor(fill_list, dtype=img.dtype, device=img.device).view(1, len_fill, 1, 1).expand_as(img)
567
+ if mode == "nearest":
568
+ mask = mask < 0.5
569
+ img[mask] = fill_img[mask]
570
+ else: # 'bilinear'
571
+ img = img * mask + (1.0 - mask) * fill_img
572
+
573
+ img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype)
574
+ return img
575
+
576
+
577
+ def _gen_affine_grid(
578
+ theta: Tensor,
579
+ w: int,
580
+ h: int,
581
+ ow: int,
582
+ oh: int,
583
+ ) -> Tensor:
584
+ # https://github.com/pytorch/pytorch/blob/74b65c32be68b15dc7c9e8bb62459efbfbde33d8/aten/src/ATen/native/
585
+ # AffineGridGenerator.cpp#L18
586
+ # Difference with AffineGridGenerator is that:
587
+ # 1) we normalize grid values after applying theta
588
+ # 2) we can normalize by other image size, such that it covers "extend" option like in PIL.Image.rotate
589
+
590
+ d = 0.5
591
+ base_grid = torch.empty(1, oh, ow, 3, dtype=theta.dtype, device=theta.device)
592
+ x_grid = torch.linspace(-ow * 0.5 + d, ow * 0.5 + d - 1, steps=ow, device=theta.device)
593
+ base_grid[..., 0].copy_(x_grid)
594
+ y_grid = torch.linspace(-oh * 0.5 + d, oh * 0.5 + d - 1, steps=oh, device=theta.device).unsqueeze_(-1)
595
+ base_grid[..., 1].copy_(y_grid)
596
+ base_grid[..., 2].fill_(1)
597
+
598
+ rescaled_theta = theta.transpose(1, 2) / torch.tensor([0.5 * w, 0.5 * h], dtype=theta.dtype, device=theta.device)
599
+ output_grid = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta)
600
+ return output_grid.view(1, oh, ow, 2)
601
+
602
+
603
+ def affine(
604
+ img: Tensor,
605
+ matrix: List[float],
606
+ interpolation: str = "nearest",
607
+ fill: Optional[Union[int, float, List[float]]] = None,
608
+ ) -> Tensor:
609
+ _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"])
610
+
611
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
612
+ theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3)
613
+ shape = img.shape
614
+ # grid will be generated on the same device as theta and img
615
+ grid = _gen_affine_grid(theta, w=shape[-1], h=shape[-2], ow=shape[-1], oh=shape[-2])
616
+ return _apply_grid_transform(img, grid, interpolation, fill=fill)
617
+
618
+
619
+ def _compute_affine_output_size(matrix: List[float], w: int, h: int) -> Tuple[int, int]:
620
+
621
+ # Inspired of PIL implementation:
622
+ # https://github.com/python-pillow/Pillow/blob/11de3318867e4398057373ee9f12dcb33db7335c/src/PIL/Image.py#L2054
623
+
624
+ # pts are Top-Left, Top-Right, Bottom-Left, Bottom-Right points.
625
+ # Points are shifted due to affine matrix torch convention about
626
+ # the center point. Center is (0, 0) for image center pivot point (w * 0.5, h * 0.5)
627
+ pts = torch.tensor(
628
+ [
629
+ [-0.5 * w, -0.5 * h, 1.0],
630
+ [-0.5 * w, 0.5 * h, 1.0],
631
+ [0.5 * w, 0.5 * h, 1.0],
632
+ [0.5 * w, -0.5 * h, 1.0],
633
+ ]
634
+ )
635
+ theta = torch.tensor(matrix, dtype=torch.float).view(2, 3)
636
+ new_pts = torch.matmul(pts, theta.T)
637
+ min_vals, _ = new_pts.min(dim=0)
638
+ max_vals, _ = new_pts.max(dim=0)
639
+
640
+ # shift points to [0, w] and [0, h] interval to match PIL results
641
+ min_vals += torch.tensor((w * 0.5, h * 0.5))
642
+ max_vals += torch.tensor((w * 0.5, h * 0.5))
643
+
644
+ # Truncate precision to 1e-4 to avoid ceil of Xe-15 to 1.0
645
+ tol = 1e-4
646
+ cmax = torch.ceil((max_vals / tol).trunc_() * tol)
647
+ cmin = torch.floor((min_vals / tol).trunc_() * tol)
648
+ size = cmax - cmin
649
+ return int(size[0]), int(size[1]) # w, h
650
+
651
+
652
+ def rotate(
653
+ img: Tensor,
654
+ matrix: List[float],
655
+ interpolation: str = "nearest",
656
+ expand: bool = False,
657
+ fill: Optional[Union[int, float, List[float]]] = None,
658
+ ) -> Tensor:
659
+ _assert_grid_transform_inputs(img, matrix, interpolation, fill, ["nearest", "bilinear"])
660
+ w, h = img.shape[-1], img.shape[-2]
661
+ ow, oh = _compute_affine_output_size(matrix, w, h) if expand else (w, h)
662
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
663
+ theta = torch.tensor(matrix, dtype=dtype, device=img.device).reshape(1, 2, 3)
664
+ # grid will be generated on the same device as theta and img
665
+ grid = _gen_affine_grid(theta, w=w, h=h, ow=ow, oh=oh)
666
+
667
+ return _apply_grid_transform(img, grid, interpolation, fill=fill)
668
+
669
+
670
+ def _perspective_grid(coeffs: List[float], ow: int, oh: int, dtype: torch.dtype, device: torch.device) -> Tensor:
671
+ # https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/
672
+ # src/libImaging/Geometry.c#L394
673
+
674
+ #
675
+ # x_out = (coeffs[0] * x + coeffs[1] * y + coeffs[2]) / (coeffs[6] * x + coeffs[7] * y + 1)
676
+ # y_out = (coeffs[3] * x + coeffs[4] * y + coeffs[5]) / (coeffs[6] * x + coeffs[7] * y + 1)
677
+ #
678
+ theta1 = torch.tensor(
679
+ [[[coeffs[0], coeffs[1], coeffs[2]], [coeffs[3], coeffs[4], coeffs[5]]]], dtype=dtype, device=device
680
+ )
681
+ theta2 = torch.tensor([[[coeffs[6], coeffs[7], 1.0], [coeffs[6], coeffs[7], 1.0]]], dtype=dtype, device=device)
682
+
683
+ d = 0.5
684
+ base_grid = torch.empty(1, oh, ow, 3, dtype=dtype, device=device)
685
+ x_grid = torch.linspace(d, ow * 1.0 + d - 1.0, steps=ow, device=device)
686
+ base_grid[..., 0].copy_(x_grid)
687
+ y_grid = torch.linspace(d, oh * 1.0 + d - 1.0, steps=oh, device=device).unsqueeze_(-1)
688
+ base_grid[..., 1].copy_(y_grid)
689
+ base_grid[..., 2].fill_(1)
690
+
691
+ rescaled_theta1 = theta1.transpose(1, 2) / torch.tensor([0.5 * ow, 0.5 * oh], dtype=dtype, device=device)
692
+ output_grid1 = base_grid.view(1, oh * ow, 3).bmm(rescaled_theta1)
693
+ output_grid2 = base_grid.view(1, oh * ow, 3).bmm(theta2.transpose(1, 2))
694
+
695
+ output_grid = output_grid1 / output_grid2 - 1.0
696
+ return output_grid.view(1, oh, ow, 2)
697
+
698
+
699
+ def perspective(
700
+ img: Tensor,
701
+ perspective_coeffs: List[float],
702
+ interpolation: str = "bilinear",
703
+ fill: Optional[Union[int, float, List[float]]] = None,
704
+ ) -> Tensor:
705
+ if not (isinstance(img, torch.Tensor)):
706
+ raise TypeError("Input img should be Tensor.")
707
+
708
+ _assert_image_tensor(img)
709
+
710
+ _assert_grid_transform_inputs(
711
+ img,
712
+ matrix=None,
713
+ interpolation=interpolation,
714
+ fill=fill,
715
+ supported_interpolation_modes=["nearest", "bilinear"],
716
+ coeffs=perspective_coeffs,
717
+ )
718
+
719
+ ow, oh = img.shape[-1], img.shape[-2]
720
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
721
+ grid = _perspective_grid(perspective_coeffs, ow=ow, oh=oh, dtype=dtype, device=img.device)
722
+ return _apply_grid_transform(img, grid, interpolation, fill=fill)
723
+
724
+
725
+ def _get_gaussian_kernel1d(kernel_size: int, sigma: float) -> Tensor:
726
+ ksize_half = (kernel_size - 1) * 0.5
727
+
728
+ x = torch.linspace(-ksize_half, ksize_half, steps=kernel_size)
729
+ pdf = torch.exp(-0.5 * (x / sigma).pow(2))
730
+ kernel1d = pdf / pdf.sum()
731
+
732
+ return kernel1d
733
+
734
+
735
+ def _get_gaussian_kernel2d(
736
+ kernel_size: List[int], sigma: List[float], dtype: torch.dtype, device: torch.device
737
+ ) -> Tensor:
738
+ kernel1d_x = _get_gaussian_kernel1d(kernel_size[0], sigma[0]).to(device, dtype=dtype)
739
+ kernel1d_y = _get_gaussian_kernel1d(kernel_size[1], sigma[1]).to(device, dtype=dtype)
740
+ kernel2d = torch.mm(kernel1d_y[:, None], kernel1d_x[None, :])
741
+ return kernel2d
742
+
743
+
744
+ def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: List[float]) -> Tensor:
745
+ if not (isinstance(img, torch.Tensor)):
746
+ raise TypeError(f"img should be Tensor. Got {type(img)}")
747
+
748
+ _assert_image_tensor(img)
749
+
750
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
751
+ kernel = _get_gaussian_kernel2d(kernel_size, sigma, dtype=dtype, device=img.device)
752
+ kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1])
753
+
754
+ img, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype])
755
+
756
+ # padding = (left, right, top, bottom)
757
+ padding = [kernel_size[0] // 2, kernel_size[0] // 2, kernel_size[1] // 2, kernel_size[1] // 2]
758
+ img = torch_pad(img, padding, mode="reflect")
759
+ img = conv2d(img, kernel, groups=img.shape[-3])
760
+
761
+ img = _cast_squeeze_out(img, need_cast, need_squeeze, out_dtype)
762
+ return img
763
+
764
+
765
+ def invert(img: Tensor) -> Tensor:
766
+
767
+ _assert_image_tensor(img)
768
+
769
+ if img.ndim < 3:
770
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
771
+
772
+ _assert_channels(img, [1, 3])
773
+
774
+ return _max_value(img.dtype) - img
775
+
776
+
777
+ def posterize(img: Tensor, bits: int) -> Tensor:
778
+
779
+ _assert_image_tensor(img)
780
+
781
+ if img.ndim < 3:
782
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
783
+ if img.dtype != torch.uint8:
784
+ raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}")
785
+
786
+ _assert_channels(img, [1, 3])
787
+ mask = -int(2 ** (8 - bits)) # JIT-friendly for: ~(2 ** (8 - bits) - 1)
788
+ return img & mask
789
+
790
+
791
+ def solarize(img: Tensor, threshold: float) -> Tensor:
792
+
793
+ _assert_image_tensor(img)
794
+
795
+ if img.ndim < 3:
796
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
797
+
798
+ _assert_channels(img, [1, 3])
799
+
800
+ if threshold > _max_value(img.dtype):
801
+ raise TypeError("Threshold should be less than bound of img.")
802
+
803
+ inverted_img = invert(img)
804
+ return torch.where(img >= threshold, inverted_img, img)
805
+
806
+
807
+ def _blurred_degenerate_image(img: Tensor) -> Tensor:
808
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
809
+
810
+ kernel = torch.ones((3, 3), dtype=dtype, device=img.device)
811
+ kernel[1, 1] = 5.0
812
+ kernel /= kernel.sum()
813
+ kernel = kernel.expand(img.shape[-3], 1, kernel.shape[0], kernel.shape[1])
814
+
815
+ result_tmp, need_cast, need_squeeze, out_dtype = _cast_squeeze_in(img, [kernel.dtype])
816
+ result_tmp = conv2d(result_tmp, kernel, groups=result_tmp.shape[-3])
817
+ result_tmp = _cast_squeeze_out(result_tmp, need_cast, need_squeeze, out_dtype)
818
+
819
+ result = img.clone()
820
+ result[..., 1:-1, 1:-1] = result_tmp
821
+
822
+ return result
823
+
824
+
825
+ def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor:
826
+ if sharpness_factor < 0:
827
+ raise ValueError(f"sharpness_factor ({sharpness_factor}) is not non-negative.")
828
+
829
+ _assert_image_tensor(img)
830
+
831
+ _assert_channels(img, [1, 3])
832
+
833
+ if img.size(-1) <= 2 or img.size(-2) <= 2:
834
+ return img
835
+
836
+ return _blend(img, _blurred_degenerate_image(img), sharpness_factor)
837
+
838
+
839
+ def autocontrast(img: Tensor) -> Tensor:
840
+
841
+ _assert_image_tensor(img)
842
+
843
+ if img.ndim < 3:
844
+ raise TypeError(f"Input image tensor should have at least 3 dimensions, but found {img.ndim}")
845
+
846
+ _assert_channels(img, [1, 3])
847
+
848
+ bound = _max_value(img.dtype)
849
+ dtype = img.dtype if torch.is_floating_point(img) else torch.float32
850
+
851
+ minimum = img.amin(dim=(-2, -1), keepdim=True).to(dtype)
852
+ maximum = img.amax(dim=(-2, -1), keepdim=True).to(dtype)
853
+ scale = bound / (maximum - minimum)
854
+ eq_idxs = torch.isfinite(scale).logical_not()
855
+ minimum[eq_idxs] = 0
856
+ scale[eq_idxs] = 1
857
+
858
+ return ((img - minimum) * scale).clamp(0, bound).to(img.dtype)
859
+
860
+
861
+ def _scale_channel(img_chan: Tensor) -> Tensor:
862
+ # TODO: we should expect bincount to always be faster than histc, but this
863
+ # isn't always the case. Once
864
+ # https://github.com/pytorch/pytorch/issues/53194 is fixed, remove the if
865
+ # block and only use bincount.
866
+ if img_chan.is_cuda:
867
+ hist = torch.histc(img_chan.to(torch.float32), bins=256, min=0, max=255)
868
+ else:
869
+ hist = torch.bincount(img_chan.reshape(-1), minlength=256)
870
+
871
+ nonzero_hist = hist[hist != 0]
872
+ step = torch.div(nonzero_hist[:-1].sum(), 255, rounding_mode="floor")
873
+ if step == 0:
874
+ return img_chan
875
+
876
+ lut = torch.div(torch.cumsum(hist, 0) + torch.div(step, 2, rounding_mode="floor"), step, rounding_mode="floor")
877
+ lut = torch.nn.functional.pad(lut, [1, 0])[:-1].clamp(0, 255)
878
+
879
+ return lut[img_chan.to(torch.int64)].to(torch.uint8)
880
+
881
+
882
+ def _equalize_single_image(img: Tensor) -> Tensor:
883
+ return torch.stack([_scale_channel(img[c]) for c in range(img.size(0))])
884
+
885
+
886
+ def equalize(img: Tensor) -> Tensor:
887
+
888
+ _assert_image_tensor(img)
889
+
890
+ if not (3 <= img.ndim <= 4):
891
+ raise TypeError(f"Input image tensor should have 3 or 4 dimensions, but found {img.ndim}")
892
+ if img.dtype != torch.uint8:
893
+ raise TypeError(f"Only torch.uint8 image tensors are supported, but found {img.dtype}")
894
+
895
+ _assert_channels(img, [1, 3])
896
+
897
+ if img.ndim == 3:
898
+ return _equalize_single_image(img)
899
+
900
+ return torch.stack([_equalize_single_image(x) for x in img])
901
+
902
+
903
+ def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool = False) -> Tensor:
904
+ _assert_image_tensor(tensor)
905
+
906
+ if not tensor.is_floating_point():
907
+ raise TypeError(f"Input tensor should be a float tensor. Got {tensor.dtype}.")
908
+
909
+ if tensor.ndim < 3:
910
+ raise ValueError(
911
+ f"Expected tensor to be a tensor image of size (..., C, H, W). Got tensor.size() = {tensor.size()}"
912
+ )
913
+
914
+ if not inplace:
915
+ tensor = tensor.clone()
916
+
917
+ dtype = tensor.dtype
918
+ mean = torch.as_tensor(mean, dtype=dtype, device=tensor.device)
919
+ std = torch.as_tensor(std, dtype=dtype, device=tensor.device)
920
+ if (std == 0).any():
921
+ raise ValueError(f"std evaluated to zero after conversion to {dtype}, leading to division by zero.")
922
+ if mean.ndim == 1:
923
+ mean = mean.view(-1, 1, 1)
924
+ if std.ndim == 1:
925
+ std = std.view(-1, 1, 1)
926
+ return tensor.sub_(mean).div_(std)
927
+
928
+
929
+ def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor:
930
+ _assert_image_tensor(img)
931
+
932
+ if not inplace:
933
+ img = img.clone()
934
+
935
+ img[..., i : i + h, j : j + w] = v
936
+ return img
937
+
938
+
939
+ def _create_identity_grid(size: List[int]) -> Tensor:
940
+ hw_space = [torch.linspace((-s + 1) / s, (s - 1) / s, s) for s in size]
941
+ grid_y, grid_x = torch.meshgrid(hw_space, indexing="ij")
942
+ return torch.stack([grid_x, grid_y], -1).unsqueeze(0) # 1 x H x W x 2
943
+
944
+
945
+ def elastic_transform(
946
+ img: Tensor,
947
+ displacement: Tensor,
948
+ interpolation: str = "bilinear",
949
+ fill: Optional[Union[int, float, List[float]]] = None,
950
+ ) -> Tensor:
951
+
952
+ if not (isinstance(img, torch.Tensor)):
953
+ raise TypeError(f"img should be Tensor. Got {type(img)}")
954
+
955
+ size = list(img.shape[-2:])
956
+ displacement = displacement.to(img.device)
957
+
958
+ identity_grid = _create_identity_grid(size)
959
+ grid = identity_grid.to(img.device) + displacement
960
+ return _apply_grid_transform(img, grid, interpolation, fill)
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_functional_video.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+
3
+ import torch
4
+
5
+
6
+ warnings.warn(
7
+ "The 'torchvision.transforms._functional_video' module is deprecated since 0.12 and will be removed in the future. "
8
+ "Please use the 'torchvision.transforms.functional' module instead."
9
+ )
10
+
11
+
12
+ def _is_tensor_video_clip(clip):
13
+ if not torch.is_tensor(clip):
14
+ raise TypeError("clip should be Tensor. Got %s" % type(clip))
15
+
16
+ if not clip.ndimension() == 4:
17
+ raise ValueError("clip should be 4D. Got %dD" % clip.dim())
18
+
19
+ return True
20
+
21
+
22
+ def crop(clip, i, j, h, w):
23
+ """
24
+ Args:
25
+ clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
26
+ """
27
+ if len(clip.size()) != 4:
28
+ raise ValueError("clip should be a 4D tensor")
29
+ return clip[..., i : i + h, j : j + w]
30
+
31
+
32
+ def resize(clip, target_size, interpolation_mode):
33
+ if len(target_size) != 2:
34
+ raise ValueError(f"target size should be tuple (height, width), instead got {target_size}")
35
+ return torch.nn.functional.interpolate(clip, size=target_size, mode=interpolation_mode, align_corners=False)
36
+
37
+
38
+ def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"):
39
+ """
40
+ Do spatial cropping and resizing to the video clip
41
+ Args:
42
+ clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
43
+ i (int): i in (i,j) i.e coordinates of the upper left corner.
44
+ j (int): j in (i,j) i.e coordinates of the upper left corner.
45
+ h (int): Height of the cropped region.
46
+ w (int): Width of the cropped region.
47
+ size (tuple(int, int)): height and width of resized clip
48
+ Returns:
49
+ clip (torch.tensor): Resized and cropped clip. Size is (C, T, H, W)
50
+ """
51
+ if not _is_tensor_video_clip(clip):
52
+ raise ValueError("clip should be a 4D torch.tensor")
53
+ clip = crop(clip, i, j, h, w)
54
+ clip = resize(clip, size, interpolation_mode)
55
+ return clip
56
+
57
+
58
+ def center_crop(clip, crop_size):
59
+ if not _is_tensor_video_clip(clip):
60
+ raise ValueError("clip should be a 4D torch.tensor")
61
+ h, w = clip.size(-2), clip.size(-1)
62
+ th, tw = crop_size
63
+ if h < th or w < tw:
64
+ raise ValueError("height and width must be no smaller than crop_size")
65
+
66
+ i = int(round((h - th) / 2.0))
67
+ j = int(round((w - tw) / 2.0))
68
+ return crop(clip, i, j, th, tw)
69
+
70
+
71
+ def to_tensor(clip):
72
+ """
73
+ Convert tensor data type from uint8 to float, divide value by 255.0 and
74
+ permute the dimensions of clip tensor
75
+ Args:
76
+ clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
77
+ Return:
78
+ clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W)
79
+ """
80
+ _is_tensor_video_clip(clip)
81
+ if not clip.dtype == torch.uint8:
82
+ raise TypeError("clip tensor should have data type uint8. Got %s" % str(clip.dtype))
83
+ return clip.float().permute(3, 0, 1, 2) / 255.0
84
+
85
+
86
+ def normalize(clip, mean, std, inplace=False):
87
+ """
88
+ Args:
89
+ clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
90
+ mean (tuple): pixel RGB mean. Size is (3)
91
+ std (tuple): pixel standard deviation. Size is (3)
92
+ Returns:
93
+ normalized clip (torch.tensor): Size is (C, T, H, W)
94
+ """
95
+ if not _is_tensor_video_clip(clip):
96
+ raise ValueError("clip should be a 4D torch.tensor")
97
+ if not inplace:
98
+ clip = clip.clone()
99
+ mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device)
100
+ std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device)
101
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
102
+ return clip
103
+
104
+
105
+ def hflip(clip):
106
+ """
107
+ Args:
108
+ clip (torch.tensor): Video clip to be normalized. Size is (C, T, H, W)
109
+ Returns:
110
+ flipped clip (torch.tensor): Size is (C, T, H, W)
111
+ """
112
+ if not _is_tensor_video_clip(clip):
113
+ raise ValueError("clip should be a 4D torch.tensor")
114
+ return clip.flip(-1)
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_presets.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This file is part of the private API. Please do not use directly these classes as they will be modified on
3
+ future versions without warning. The classes should be accessed only via the transforms argument of Weights.
4
+ """
5
+ from typing import Optional, Tuple
6
+
7
+ import torch
8
+ from torch import nn, Tensor
9
+
10
+ from . import functional as F, InterpolationMode
11
+
12
+
13
+ __all__ = [
14
+ "ObjectDetection",
15
+ "ImageClassification",
16
+ "VideoClassification",
17
+ "SemanticSegmentation",
18
+ "OpticalFlow",
19
+ ]
20
+
21
+
22
+ class ObjectDetection(nn.Module):
23
+ def forward(self, img: Tensor) -> Tensor:
24
+ if not isinstance(img, Tensor):
25
+ img = F.pil_to_tensor(img)
26
+ return F.convert_image_dtype(img, torch.float)
27
+
28
+ def __repr__(self) -> str:
29
+ return self.__class__.__name__ + "()"
30
+
31
+ def describe(self) -> str:
32
+ return (
33
+ "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. "
34
+ "The images are rescaled to ``[0.0, 1.0]``."
35
+ )
36
+
37
+
38
+ class ImageClassification(nn.Module):
39
+ def __init__(
40
+ self,
41
+ *,
42
+ crop_size: int,
43
+ resize_size: int = 256,
44
+ mean: Tuple[float, ...] = (0.485, 0.456, 0.406),
45
+ std: Tuple[float, ...] = (0.229, 0.224, 0.225),
46
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
47
+ antialias: Optional[bool] = True,
48
+ ) -> None:
49
+ super().__init__()
50
+ self.crop_size = [crop_size]
51
+ self.resize_size = [resize_size]
52
+ self.mean = list(mean)
53
+ self.std = list(std)
54
+ self.interpolation = interpolation
55
+ self.antialias = antialias
56
+
57
+ def forward(self, img: Tensor) -> Tensor:
58
+ img = F.resize(img, self.resize_size, interpolation=self.interpolation, antialias=self.antialias)
59
+ img = F.center_crop(img, self.crop_size)
60
+ if not isinstance(img, Tensor):
61
+ img = F.pil_to_tensor(img)
62
+ img = F.convert_image_dtype(img, torch.float)
63
+ img = F.normalize(img, mean=self.mean, std=self.std)
64
+ return img
65
+
66
+ def __repr__(self) -> str:
67
+ format_string = self.__class__.__name__ + "("
68
+ format_string += f"\n crop_size={self.crop_size}"
69
+ format_string += f"\n resize_size={self.resize_size}"
70
+ format_string += f"\n mean={self.mean}"
71
+ format_string += f"\n std={self.std}"
72
+ format_string += f"\n interpolation={self.interpolation}"
73
+ format_string += "\n)"
74
+ return format_string
75
+
76
+ def describe(self) -> str:
77
+ return (
78
+ "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. "
79
+ f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``, "
80
+ f"followed by a central crop of ``crop_size={self.crop_size}``. Finally the values are first rescaled to "
81
+ f"``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and ``std={self.std}``."
82
+ )
83
+
84
+
85
+ class VideoClassification(nn.Module):
86
+ def __init__(
87
+ self,
88
+ *,
89
+ crop_size: Tuple[int, int],
90
+ resize_size: Tuple[int, int],
91
+ mean: Tuple[float, ...] = (0.43216, 0.394666, 0.37645),
92
+ std: Tuple[float, ...] = (0.22803, 0.22145, 0.216989),
93
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
94
+ ) -> None:
95
+ super().__init__()
96
+ self.crop_size = list(crop_size)
97
+ self.resize_size = list(resize_size)
98
+ self.mean = list(mean)
99
+ self.std = list(std)
100
+ self.interpolation = interpolation
101
+
102
+ def forward(self, vid: Tensor) -> Tensor:
103
+ need_squeeze = False
104
+ if vid.ndim < 5:
105
+ vid = vid.unsqueeze(dim=0)
106
+ need_squeeze = True
107
+
108
+ N, T, C, H, W = vid.shape
109
+ vid = vid.view(-1, C, H, W)
110
+ # We hard-code antialias=False to preserve results after we changed
111
+ # its default from None to True (see
112
+ # https://github.com/pytorch/vision/pull/7160)
113
+ # TODO: we could re-train the video models with antialias=True?
114
+ vid = F.resize(vid, self.resize_size, interpolation=self.interpolation, antialias=False)
115
+ vid = F.center_crop(vid, self.crop_size)
116
+ vid = F.convert_image_dtype(vid, torch.float)
117
+ vid = F.normalize(vid, mean=self.mean, std=self.std)
118
+ H, W = self.crop_size
119
+ vid = vid.view(N, T, C, H, W)
120
+ vid = vid.permute(0, 2, 1, 3, 4) # (N, T, C, H, W) => (N, C, T, H, W)
121
+
122
+ if need_squeeze:
123
+ vid = vid.squeeze(dim=0)
124
+ return vid
125
+
126
+ def __repr__(self) -> str:
127
+ format_string = self.__class__.__name__ + "("
128
+ format_string += f"\n crop_size={self.crop_size}"
129
+ format_string += f"\n resize_size={self.resize_size}"
130
+ format_string += f"\n mean={self.mean}"
131
+ format_string += f"\n std={self.std}"
132
+ format_string += f"\n interpolation={self.interpolation}"
133
+ format_string += "\n)"
134
+ return format_string
135
+
136
+ def describe(self) -> str:
137
+ return (
138
+ "Accepts batched ``(B, T, C, H, W)`` and single ``(T, C, H, W)`` video frame ``torch.Tensor`` objects. "
139
+ f"The frames are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``, "
140
+ f"followed by a central crop of ``crop_size={self.crop_size}``. Finally the values are first rescaled to "
141
+ f"``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and ``std={self.std}``. Finally the output "
142
+ "dimensions are permuted to ``(..., C, T, H, W)`` tensors."
143
+ )
144
+
145
+
146
+ class SemanticSegmentation(nn.Module):
147
+ def __init__(
148
+ self,
149
+ *,
150
+ resize_size: Optional[int],
151
+ mean: Tuple[float, ...] = (0.485, 0.456, 0.406),
152
+ std: Tuple[float, ...] = (0.229, 0.224, 0.225),
153
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
154
+ antialias: Optional[bool] = True,
155
+ ) -> None:
156
+ super().__init__()
157
+ self.resize_size = [resize_size] if resize_size is not None else None
158
+ self.mean = list(mean)
159
+ self.std = list(std)
160
+ self.interpolation = interpolation
161
+ self.antialias = antialias
162
+
163
+ def forward(self, img: Tensor) -> Tensor:
164
+ if isinstance(self.resize_size, list):
165
+ img = F.resize(img, self.resize_size, interpolation=self.interpolation, antialias=self.antialias)
166
+ if not isinstance(img, Tensor):
167
+ img = F.pil_to_tensor(img)
168
+ img = F.convert_image_dtype(img, torch.float)
169
+ img = F.normalize(img, mean=self.mean, std=self.std)
170
+ return img
171
+
172
+ def __repr__(self) -> str:
173
+ format_string = self.__class__.__name__ + "("
174
+ format_string += f"\n resize_size={self.resize_size}"
175
+ format_string += f"\n mean={self.mean}"
176
+ format_string += f"\n std={self.std}"
177
+ format_string += f"\n interpolation={self.interpolation}"
178
+ format_string += "\n)"
179
+ return format_string
180
+
181
+ def describe(self) -> str:
182
+ return (
183
+ "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. "
184
+ f"The images are resized to ``resize_size={self.resize_size}`` using ``interpolation={self.interpolation}``. "
185
+ f"Finally the values are first rescaled to ``[0.0, 1.0]`` and then normalized using ``mean={self.mean}`` and "
186
+ f"``std={self.std}``."
187
+ )
188
+
189
+
190
+ class OpticalFlow(nn.Module):
191
+ def forward(self, img1: Tensor, img2: Tensor) -> Tuple[Tensor, Tensor]:
192
+ if not isinstance(img1, Tensor):
193
+ img1 = F.pil_to_tensor(img1)
194
+ if not isinstance(img2, Tensor):
195
+ img2 = F.pil_to_tensor(img2)
196
+
197
+ img1 = F.convert_image_dtype(img1, torch.float)
198
+ img2 = F.convert_image_dtype(img2, torch.float)
199
+
200
+ # map [0, 1] into [-1, 1]
201
+ img1 = F.normalize(img1, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
202
+ img2 = F.normalize(img2, mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
203
+
204
+ img1 = img1.contiguous()
205
+ img2 = img2.contiguous()
206
+
207
+ return img1, img2
208
+
209
+ def __repr__(self) -> str:
210
+ return self.__class__.__name__ + "()"
211
+
212
+ def describe(self) -> str:
213
+ return (
214
+ "Accepts ``PIL.Image``, batched ``(B, C, H, W)`` and single ``(C, H, W)`` image ``torch.Tensor`` objects. "
215
+ "The images are rescaled to ``[-1.0, 1.0]``."
216
+ )
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/_transforms_video.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import numbers
4
+ import random
5
+ import warnings
6
+
7
+ from torchvision.transforms import RandomCrop, RandomResizedCrop
8
+
9
+ from . import _functional_video as F
10
+
11
+
12
+ __all__ = [
13
+ "RandomCropVideo",
14
+ "RandomResizedCropVideo",
15
+ "CenterCropVideo",
16
+ "NormalizeVideo",
17
+ "ToTensorVideo",
18
+ "RandomHorizontalFlipVideo",
19
+ ]
20
+
21
+
22
+ warnings.warn(
23
+ "The 'torchvision.transforms._transforms_video' module is deprecated since 0.12 and will be removed in the future. "
24
+ "Please use the 'torchvision.transforms' module instead."
25
+ )
26
+
27
+
28
+ class RandomCropVideo(RandomCrop):
29
+ def __init__(self, size):
30
+ if isinstance(size, numbers.Number):
31
+ self.size = (int(size), int(size))
32
+ else:
33
+ self.size = size
34
+
35
+ def __call__(self, clip):
36
+ """
37
+ Args:
38
+ clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
39
+ Returns:
40
+ torch.tensor: randomly cropped/resized video clip.
41
+ size is (C, T, OH, OW)
42
+ """
43
+ i, j, h, w = self.get_params(clip, self.size)
44
+ return F.crop(clip, i, j, h, w)
45
+
46
+ def __repr__(self) -> str:
47
+ return f"{self.__class__.__name__}(size={self.size})"
48
+
49
+
50
+ class RandomResizedCropVideo(RandomResizedCrop):
51
+ def __init__(
52
+ self,
53
+ size,
54
+ scale=(0.08, 1.0),
55
+ ratio=(3.0 / 4.0, 4.0 / 3.0),
56
+ interpolation_mode="bilinear",
57
+ ):
58
+ if isinstance(size, tuple):
59
+ if len(size) != 2:
60
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
61
+ self.size = size
62
+ else:
63
+ self.size = (size, size)
64
+
65
+ self.interpolation_mode = interpolation_mode
66
+ self.scale = scale
67
+ self.ratio = ratio
68
+
69
+ def __call__(self, clip):
70
+ """
71
+ Args:
72
+ clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
73
+ Returns:
74
+ torch.tensor: randomly cropped/resized video clip.
75
+ size is (C, T, H, W)
76
+ """
77
+ i, j, h, w = self.get_params(clip, self.scale, self.ratio)
78
+ return F.resized_crop(clip, i, j, h, w, self.size, self.interpolation_mode)
79
+
80
+ def __repr__(self) -> str:
81
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}, scale={self.scale}, ratio={self.ratio})"
82
+
83
+
84
+ class CenterCropVideo:
85
+ def __init__(self, crop_size):
86
+ if isinstance(crop_size, numbers.Number):
87
+ self.crop_size = (int(crop_size), int(crop_size))
88
+ else:
89
+ self.crop_size = crop_size
90
+
91
+ def __call__(self, clip):
92
+ """
93
+ Args:
94
+ clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
95
+ Returns:
96
+ torch.tensor: central cropping of video clip. Size is
97
+ (C, T, crop_size, crop_size)
98
+ """
99
+ return F.center_crop(clip, self.crop_size)
100
+
101
+ def __repr__(self) -> str:
102
+ return f"{self.__class__.__name__}(crop_size={self.crop_size})"
103
+
104
+
105
+ class NormalizeVideo:
106
+ """
107
+ Normalize the video clip by mean subtraction and division by standard deviation
108
+ Args:
109
+ mean (3-tuple): pixel RGB mean
110
+ std (3-tuple): pixel RGB standard deviation
111
+ inplace (boolean): whether do in-place normalization
112
+ """
113
+
114
+ def __init__(self, mean, std, inplace=False):
115
+ self.mean = mean
116
+ self.std = std
117
+ self.inplace = inplace
118
+
119
+ def __call__(self, clip):
120
+ """
121
+ Args:
122
+ clip (torch.tensor): video clip to be normalized. Size is (C, T, H, W)
123
+ """
124
+ return F.normalize(clip, self.mean, self.std, self.inplace)
125
+
126
+ def __repr__(self) -> str:
127
+ return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})"
128
+
129
+
130
+ class ToTensorVideo:
131
+ """
132
+ Convert tensor data type from uint8 to float, divide value by 255.0 and
133
+ permute the dimensions of clip tensor
134
+ """
135
+
136
+ def __init__(self):
137
+ pass
138
+
139
+ def __call__(self, clip):
140
+ """
141
+ Args:
142
+ clip (torch.tensor, dtype=torch.uint8): Size is (T, H, W, C)
143
+ Return:
144
+ clip (torch.tensor, dtype=torch.float): Size is (C, T, H, W)
145
+ """
146
+ return F.to_tensor(clip)
147
+
148
+ def __repr__(self) -> str:
149
+ return self.__class__.__name__
150
+
151
+
152
+ class RandomHorizontalFlipVideo:
153
+ """
154
+ Flip the video clip along the horizontal direction with a given probability
155
+ Args:
156
+ p (float): probability of the clip being flipped. Default value is 0.5
157
+ """
158
+
159
+ def __init__(self, p=0.5):
160
+ self.p = p
161
+
162
+ def __call__(self, clip):
163
+ """
164
+ Args:
165
+ clip (torch.tensor): Size is (C, T, H, W)
166
+ Return:
167
+ clip (torch.tensor): Size is (C, T, H, W)
168
+ """
169
+ if random.random() < self.p:
170
+ clip = F.hflip(clip)
171
+ return clip
172
+
173
+ def __repr__(self) -> str:
174
+ return f"{self.__class__.__name__}(p={self.p})"
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/autoaugment.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from enum import Enum
3
+ from typing import Dict, List, Optional, Tuple
4
+
5
+ import torch
6
+ from torch import Tensor
7
+
8
+ from . import functional as F, InterpolationMode
9
+
10
+ __all__ = ["AutoAugmentPolicy", "AutoAugment", "RandAugment", "TrivialAugmentWide", "AugMix"]
11
+
12
+
13
+ def _apply_op(
14
+ img: Tensor, op_name: str, magnitude: float, interpolation: InterpolationMode, fill: Optional[List[float]]
15
+ ):
16
+ if op_name == "ShearX":
17
+ # magnitude should be arctan(magnitude)
18
+ # official autoaug: (1, level, 0, 0, 1, 0)
19
+ # https://github.com/tensorflow/models/blob/dd02069717128186b88afa8d857ce57d17957f03/research/autoaugment/augmentation_transforms.py#L290
20
+ # compared to
21
+ # torchvision: (1, tan(level), 0, 0, 1, 0)
22
+ # https://github.com/pytorch/vision/blob/0c2373d0bba3499e95776e7936e207d8a1676e65/torchvision/transforms/functional.py#L976
23
+ img = F.affine(
24
+ img,
25
+ angle=0.0,
26
+ translate=[0, 0],
27
+ scale=1.0,
28
+ shear=[math.degrees(math.atan(magnitude)), 0.0],
29
+ interpolation=interpolation,
30
+ fill=fill,
31
+ center=[0, 0],
32
+ )
33
+ elif op_name == "ShearY":
34
+ # magnitude should be arctan(magnitude)
35
+ # See above
36
+ img = F.affine(
37
+ img,
38
+ angle=0.0,
39
+ translate=[0, 0],
40
+ scale=1.0,
41
+ shear=[0.0, math.degrees(math.atan(magnitude))],
42
+ interpolation=interpolation,
43
+ fill=fill,
44
+ center=[0, 0],
45
+ )
46
+ elif op_name == "TranslateX":
47
+ img = F.affine(
48
+ img,
49
+ angle=0.0,
50
+ translate=[int(magnitude), 0],
51
+ scale=1.0,
52
+ interpolation=interpolation,
53
+ shear=[0.0, 0.0],
54
+ fill=fill,
55
+ )
56
+ elif op_name == "TranslateY":
57
+ img = F.affine(
58
+ img,
59
+ angle=0.0,
60
+ translate=[0, int(magnitude)],
61
+ scale=1.0,
62
+ interpolation=interpolation,
63
+ shear=[0.0, 0.0],
64
+ fill=fill,
65
+ )
66
+ elif op_name == "Rotate":
67
+ img = F.rotate(img, magnitude, interpolation=interpolation, fill=fill)
68
+ elif op_name == "Brightness":
69
+ img = F.adjust_brightness(img, 1.0 + magnitude)
70
+ elif op_name == "Color":
71
+ img = F.adjust_saturation(img, 1.0 + magnitude)
72
+ elif op_name == "Contrast":
73
+ img = F.adjust_contrast(img, 1.0 + magnitude)
74
+ elif op_name == "Sharpness":
75
+ img = F.adjust_sharpness(img, 1.0 + magnitude)
76
+ elif op_name == "Posterize":
77
+ img = F.posterize(img, int(magnitude))
78
+ elif op_name == "Solarize":
79
+ img = F.solarize(img, magnitude)
80
+ elif op_name == "AutoContrast":
81
+ img = F.autocontrast(img)
82
+ elif op_name == "Equalize":
83
+ img = F.equalize(img)
84
+ elif op_name == "Invert":
85
+ img = F.invert(img)
86
+ elif op_name == "Identity":
87
+ pass
88
+ else:
89
+ raise ValueError(f"The provided operator {op_name} is not recognized.")
90
+ return img
91
+
92
+
93
+ class AutoAugmentPolicy(Enum):
94
+ """AutoAugment policies learned on different datasets.
95
+ Available policies are IMAGENET, CIFAR10 and SVHN.
96
+ """
97
+
98
+ IMAGENET = "imagenet"
99
+ CIFAR10 = "cifar10"
100
+ SVHN = "svhn"
101
+
102
+
103
+ # FIXME: Eliminate copy-pasted code for fill standardization and _augmentation_space() by moving stuff on a base class
104
+ class AutoAugment(torch.nn.Module):
105
+ r"""AutoAugment data augmentation method based on
106
+ `"AutoAugment: Learning Augmentation Strategies from Data" <https://arxiv.org/pdf/1805.09501.pdf>`_.
107
+ If the image is torch Tensor, it should be of type torch.uint8, and it is expected
108
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
109
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
110
+
111
+ Args:
112
+ policy (AutoAugmentPolicy): Desired policy enum defined by
113
+ :class:`torchvision.transforms.autoaugment.AutoAugmentPolicy`. Default is ``AutoAugmentPolicy.IMAGENET``.
114
+ interpolation (InterpolationMode): Desired interpolation enum defined by
115
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
116
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
117
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
118
+ image. If given a number, the value is used for all bands respectively.
119
+ """
120
+
121
+ def __init__(
122
+ self,
123
+ policy: AutoAugmentPolicy = AutoAugmentPolicy.IMAGENET,
124
+ interpolation: InterpolationMode = InterpolationMode.NEAREST,
125
+ fill: Optional[List[float]] = None,
126
+ ) -> None:
127
+ super().__init__()
128
+ self.policy = policy
129
+ self.interpolation = interpolation
130
+ self.fill = fill
131
+ self.policies = self._get_policies(policy)
132
+
133
+ def _get_policies(
134
+ self, policy: AutoAugmentPolicy
135
+ ) -> List[Tuple[Tuple[str, float, Optional[int]], Tuple[str, float, Optional[int]]]]:
136
+ if policy == AutoAugmentPolicy.IMAGENET:
137
+ return [
138
+ (("Posterize", 0.4, 8), ("Rotate", 0.6, 9)),
139
+ (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)),
140
+ (("Equalize", 0.8, None), ("Equalize", 0.6, None)),
141
+ (("Posterize", 0.6, 7), ("Posterize", 0.6, 6)),
142
+ (("Equalize", 0.4, None), ("Solarize", 0.2, 4)),
143
+ (("Equalize", 0.4, None), ("Rotate", 0.8, 8)),
144
+ (("Solarize", 0.6, 3), ("Equalize", 0.6, None)),
145
+ (("Posterize", 0.8, 5), ("Equalize", 1.0, None)),
146
+ (("Rotate", 0.2, 3), ("Solarize", 0.6, 8)),
147
+ (("Equalize", 0.6, None), ("Posterize", 0.4, 6)),
148
+ (("Rotate", 0.8, 8), ("Color", 0.4, 0)),
149
+ (("Rotate", 0.4, 9), ("Equalize", 0.6, None)),
150
+ (("Equalize", 0.0, None), ("Equalize", 0.8, None)),
151
+ (("Invert", 0.6, None), ("Equalize", 1.0, None)),
152
+ (("Color", 0.6, 4), ("Contrast", 1.0, 8)),
153
+ (("Rotate", 0.8, 8), ("Color", 1.0, 2)),
154
+ (("Color", 0.8, 8), ("Solarize", 0.8, 7)),
155
+ (("Sharpness", 0.4, 7), ("Invert", 0.6, None)),
156
+ (("ShearX", 0.6, 5), ("Equalize", 1.0, None)),
157
+ (("Color", 0.4, 0), ("Equalize", 0.6, None)),
158
+ (("Equalize", 0.4, None), ("Solarize", 0.2, 4)),
159
+ (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)),
160
+ (("Invert", 0.6, None), ("Equalize", 1.0, None)),
161
+ (("Color", 0.6, 4), ("Contrast", 1.0, 8)),
162
+ (("Equalize", 0.8, None), ("Equalize", 0.6, None)),
163
+ ]
164
+ elif policy == AutoAugmentPolicy.CIFAR10:
165
+ return [
166
+ (("Invert", 0.1, None), ("Contrast", 0.2, 6)),
167
+ (("Rotate", 0.7, 2), ("TranslateX", 0.3, 9)),
168
+ (("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)),
169
+ (("ShearY", 0.5, 8), ("TranslateY", 0.7, 9)),
170
+ (("AutoContrast", 0.5, None), ("Equalize", 0.9, None)),
171
+ (("ShearY", 0.2, 7), ("Posterize", 0.3, 7)),
172
+ (("Color", 0.4, 3), ("Brightness", 0.6, 7)),
173
+ (("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)),
174
+ (("Equalize", 0.6, None), ("Equalize", 0.5, None)),
175
+ (("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)),
176
+ (("Color", 0.7, 7), ("TranslateX", 0.5, 8)),
177
+ (("Equalize", 0.3, None), ("AutoContrast", 0.4, None)),
178
+ (("TranslateY", 0.4, 3), ("Sharpness", 0.2, 6)),
179
+ (("Brightness", 0.9, 6), ("Color", 0.2, 8)),
180
+ (("Solarize", 0.5, 2), ("Invert", 0.0, None)),
181
+ (("Equalize", 0.2, None), ("AutoContrast", 0.6, None)),
182
+ (("Equalize", 0.2, None), ("Equalize", 0.6, None)),
183
+ (("Color", 0.9, 9), ("Equalize", 0.6, None)),
184
+ (("AutoContrast", 0.8, None), ("Solarize", 0.2, 8)),
185
+ (("Brightness", 0.1, 3), ("Color", 0.7, 0)),
186
+ (("Solarize", 0.4, 5), ("AutoContrast", 0.9, None)),
187
+ (("TranslateY", 0.9, 9), ("TranslateY", 0.7, 9)),
188
+ (("AutoContrast", 0.9, None), ("Solarize", 0.8, 3)),
189
+ (("Equalize", 0.8, None), ("Invert", 0.1, None)),
190
+ (("TranslateY", 0.7, 9), ("AutoContrast", 0.9, None)),
191
+ ]
192
+ elif policy == AutoAugmentPolicy.SVHN:
193
+ return [
194
+ (("ShearX", 0.9, 4), ("Invert", 0.2, None)),
195
+ (("ShearY", 0.9, 8), ("Invert", 0.7, None)),
196
+ (("Equalize", 0.6, None), ("Solarize", 0.6, 6)),
197
+ (("Invert", 0.9, None), ("Equalize", 0.6, None)),
198
+ (("Equalize", 0.6, None), ("Rotate", 0.9, 3)),
199
+ (("ShearX", 0.9, 4), ("AutoContrast", 0.8, None)),
200
+ (("ShearY", 0.9, 8), ("Invert", 0.4, None)),
201
+ (("ShearY", 0.9, 5), ("Solarize", 0.2, 6)),
202
+ (("Invert", 0.9, None), ("AutoContrast", 0.8, None)),
203
+ (("Equalize", 0.6, None), ("Rotate", 0.9, 3)),
204
+ (("ShearX", 0.9, 4), ("Solarize", 0.3, 3)),
205
+ (("ShearY", 0.8, 8), ("Invert", 0.7, None)),
206
+ (("Equalize", 0.9, None), ("TranslateY", 0.6, 6)),
207
+ (("Invert", 0.9, None), ("Equalize", 0.6, None)),
208
+ (("Contrast", 0.3, 3), ("Rotate", 0.8, 4)),
209
+ (("Invert", 0.8, None), ("TranslateY", 0.0, 2)),
210
+ (("ShearY", 0.7, 6), ("Solarize", 0.4, 8)),
211
+ (("Invert", 0.6, None), ("Rotate", 0.8, 4)),
212
+ (("ShearY", 0.3, 7), ("TranslateX", 0.9, 3)),
213
+ (("ShearX", 0.1, 6), ("Invert", 0.6, None)),
214
+ (("Solarize", 0.7, 2), ("TranslateY", 0.6, 7)),
215
+ (("ShearY", 0.8, 4), ("Invert", 0.8, None)),
216
+ (("ShearX", 0.7, 9), ("TranslateY", 0.8, 3)),
217
+ (("ShearY", 0.8, 5), ("AutoContrast", 0.7, None)),
218
+ (("ShearX", 0.7, 2), ("Invert", 0.1, None)),
219
+ ]
220
+ else:
221
+ raise ValueError(f"The provided policy {policy} is not recognized.")
222
+
223
+ def _augmentation_space(self, num_bins: int, image_size: Tuple[int, int]) -> Dict[str, Tuple[Tensor, bool]]:
224
+ return {
225
+ # op_name: (magnitudes, signed)
226
+ "ShearX": (torch.linspace(0.0, 0.3, num_bins), True),
227
+ "ShearY": (torch.linspace(0.0, 0.3, num_bins), True),
228
+ "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True),
229
+ "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True),
230
+ "Rotate": (torch.linspace(0.0, 30.0, num_bins), True),
231
+ "Brightness": (torch.linspace(0.0, 0.9, num_bins), True),
232
+ "Color": (torch.linspace(0.0, 0.9, num_bins), True),
233
+ "Contrast": (torch.linspace(0.0, 0.9, num_bins), True),
234
+ "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True),
235
+ "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False),
236
+ "Solarize": (torch.linspace(255.0, 0.0, num_bins), False),
237
+ "AutoContrast": (torch.tensor(0.0), False),
238
+ "Equalize": (torch.tensor(0.0), False),
239
+ "Invert": (torch.tensor(0.0), False),
240
+ }
241
+
242
+ @staticmethod
243
+ def get_params(transform_num: int) -> Tuple[int, Tensor, Tensor]:
244
+ """Get parameters for autoaugment transformation
245
+
246
+ Returns:
247
+ params required by the autoaugment transformation
248
+ """
249
+ policy_id = int(torch.randint(transform_num, (1,)).item())
250
+ probs = torch.rand((2,))
251
+ signs = torch.randint(2, (2,))
252
+
253
+ return policy_id, probs, signs
254
+
255
+ def forward(self, img: Tensor) -> Tensor:
256
+ """
257
+ img (PIL Image or Tensor): Image to be transformed.
258
+
259
+ Returns:
260
+ PIL Image or Tensor: AutoAugmented image.
261
+ """
262
+ fill = self.fill
263
+ channels, height, width = F.get_dimensions(img)
264
+ if isinstance(img, Tensor):
265
+ if isinstance(fill, (int, float)):
266
+ fill = [float(fill)] * channels
267
+ elif fill is not None:
268
+ fill = [float(f) for f in fill]
269
+
270
+ transform_id, probs, signs = self.get_params(len(self.policies))
271
+
272
+ op_meta = self._augmentation_space(10, (height, width))
273
+ for i, (op_name, p, magnitude_id) in enumerate(self.policies[transform_id]):
274
+ if probs[i] <= p:
275
+ magnitudes, signed = op_meta[op_name]
276
+ magnitude = float(magnitudes[magnitude_id].item()) if magnitude_id is not None else 0.0
277
+ if signed and signs[i] == 0:
278
+ magnitude *= -1.0
279
+ img = _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill)
280
+
281
+ return img
282
+
283
+ def __repr__(self) -> str:
284
+ return f"{self.__class__.__name__}(policy={self.policy}, fill={self.fill})"
285
+
286
+
287
+ class RandAugment(torch.nn.Module):
288
+ r"""RandAugment data augmentation method based on
289
+ `"RandAugment: Practical automated data augmentation with a reduced search space"
290
+ <https://arxiv.org/abs/1909.13719>`_.
291
+ If the image is torch Tensor, it should be of type torch.uint8, and it is expected
292
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
293
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
294
+
295
+ Args:
296
+ num_ops (int): Number of augmentation transformations to apply sequentially.
297
+ magnitude (int): Magnitude for all the transformations.
298
+ num_magnitude_bins (int): The number of different magnitude values.
299
+ interpolation (InterpolationMode): Desired interpolation enum defined by
300
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
301
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
302
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
303
+ image. If given a number, the value is used for all bands respectively.
304
+ """
305
+
306
+ def __init__(
307
+ self,
308
+ num_ops: int = 2,
309
+ magnitude: int = 9,
310
+ num_magnitude_bins: int = 31,
311
+ interpolation: InterpolationMode = InterpolationMode.NEAREST,
312
+ fill: Optional[List[float]] = None,
313
+ ) -> None:
314
+ super().__init__()
315
+ self.num_ops = num_ops
316
+ self.magnitude = magnitude
317
+ self.num_magnitude_bins = num_magnitude_bins
318
+ self.interpolation = interpolation
319
+ self.fill = fill
320
+
321
+ def _augmentation_space(self, num_bins: int, image_size: Tuple[int, int]) -> Dict[str, Tuple[Tensor, bool]]:
322
+ return {
323
+ # op_name: (magnitudes, signed)
324
+ "Identity": (torch.tensor(0.0), False),
325
+ "ShearX": (torch.linspace(0.0, 0.3, num_bins), True),
326
+ "ShearY": (torch.linspace(0.0, 0.3, num_bins), True),
327
+ "TranslateX": (torch.linspace(0.0, 150.0 / 331.0 * image_size[1], num_bins), True),
328
+ "TranslateY": (torch.linspace(0.0, 150.0 / 331.0 * image_size[0], num_bins), True),
329
+ "Rotate": (torch.linspace(0.0, 30.0, num_bins), True),
330
+ "Brightness": (torch.linspace(0.0, 0.9, num_bins), True),
331
+ "Color": (torch.linspace(0.0, 0.9, num_bins), True),
332
+ "Contrast": (torch.linspace(0.0, 0.9, num_bins), True),
333
+ "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True),
334
+ "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False),
335
+ "Solarize": (torch.linspace(255.0, 0.0, num_bins), False),
336
+ "AutoContrast": (torch.tensor(0.0), False),
337
+ "Equalize": (torch.tensor(0.0), False),
338
+ }
339
+
340
+ def forward(self, img: Tensor) -> Tensor:
341
+ """
342
+ img (PIL Image or Tensor): Image to be transformed.
343
+
344
+ Returns:
345
+ PIL Image or Tensor: Transformed image.
346
+ """
347
+ fill = self.fill
348
+ channels, height, width = F.get_dimensions(img)
349
+ if isinstance(img, Tensor):
350
+ if isinstance(fill, (int, float)):
351
+ fill = [float(fill)] * channels
352
+ elif fill is not None:
353
+ fill = [float(f) for f in fill]
354
+
355
+ op_meta = self._augmentation_space(self.num_magnitude_bins, (height, width))
356
+ for _ in range(self.num_ops):
357
+ op_index = int(torch.randint(len(op_meta), (1,)).item())
358
+ op_name = list(op_meta.keys())[op_index]
359
+ magnitudes, signed = op_meta[op_name]
360
+ magnitude = float(magnitudes[self.magnitude].item()) if magnitudes.ndim > 0 else 0.0
361
+ if signed and torch.randint(2, (1,)):
362
+ magnitude *= -1.0
363
+ img = _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill)
364
+
365
+ return img
366
+
367
+ def __repr__(self) -> str:
368
+ s = (
369
+ f"{self.__class__.__name__}("
370
+ f"num_ops={self.num_ops}"
371
+ f", magnitude={self.magnitude}"
372
+ f", num_magnitude_bins={self.num_magnitude_bins}"
373
+ f", interpolation={self.interpolation}"
374
+ f", fill={self.fill}"
375
+ f")"
376
+ )
377
+ return s
378
+
379
+
380
+ class TrivialAugmentWide(torch.nn.Module):
381
+ r"""Dataset-independent data-augmentation with TrivialAugment Wide, as described in
382
+ `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" <https://arxiv.org/abs/2103.10158>`_.
383
+ If the image is torch Tensor, it should be of type torch.uint8, and it is expected
384
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
385
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
386
+
387
+ Args:
388
+ num_magnitude_bins (int): The number of different magnitude values.
389
+ interpolation (InterpolationMode): Desired interpolation enum defined by
390
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
391
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
392
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
393
+ image. If given a number, the value is used for all bands respectively.
394
+ """
395
+
396
+ def __init__(
397
+ self,
398
+ num_magnitude_bins: int = 31,
399
+ interpolation: InterpolationMode = InterpolationMode.NEAREST,
400
+ fill: Optional[List[float]] = None,
401
+ ) -> None:
402
+ super().__init__()
403
+ self.num_magnitude_bins = num_magnitude_bins
404
+ self.interpolation = interpolation
405
+ self.fill = fill
406
+
407
+ def _augmentation_space(self, num_bins: int) -> Dict[str, Tuple[Tensor, bool]]:
408
+ return {
409
+ # op_name: (magnitudes, signed)
410
+ "Identity": (torch.tensor(0.0), False),
411
+ "ShearX": (torch.linspace(0.0, 0.99, num_bins), True),
412
+ "ShearY": (torch.linspace(0.0, 0.99, num_bins), True),
413
+ "TranslateX": (torch.linspace(0.0, 32.0, num_bins), True),
414
+ "TranslateY": (torch.linspace(0.0, 32.0, num_bins), True),
415
+ "Rotate": (torch.linspace(0.0, 135.0, num_bins), True),
416
+ "Brightness": (torch.linspace(0.0, 0.99, num_bins), True),
417
+ "Color": (torch.linspace(0.0, 0.99, num_bins), True),
418
+ "Contrast": (torch.linspace(0.0, 0.99, num_bins), True),
419
+ "Sharpness": (torch.linspace(0.0, 0.99, num_bins), True),
420
+ "Posterize": (8 - (torch.arange(num_bins) / ((num_bins - 1) / 6)).round().int(), False),
421
+ "Solarize": (torch.linspace(255.0, 0.0, num_bins), False),
422
+ "AutoContrast": (torch.tensor(0.0), False),
423
+ "Equalize": (torch.tensor(0.0), False),
424
+ }
425
+
426
+ def forward(self, img: Tensor) -> Tensor:
427
+ """
428
+ img (PIL Image or Tensor): Image to be transformed.
429
+
430
+ Returns:
431
+ PIL Image or Tensor: Transformed image.
432
+ """
433
+ fill = self.fill
434
+ channels, height, width = F.get_dimensions(img)
435
+ if isinstance(img, Tensor):
436
+ if isinstance(fill, (int, float)):
437
+ fill = [float(fill)] * channels
438
+ elif fill is not None:
439
+ fill = [float(f) for f in fill]
440
+
441
+ op_meta = self._augmentation_space(self.num_magnitude_bins)
442
+ op_index = int(torch.randint(len(op_meta), (1,)).item())
443
+ op_name = list(op_meta.keys())[op_index]
444
+ magnitudes, signed = op_meta[op_name]
445
+ magnitude = (
446
+ float(magnitudes[torch.randint(len(magnitudes), (1,), dtype=torch.long)].item())
447
+ if magnitudes.ndim > 0
448
+ else 0.0
449
+ )
450
+ if signed and torch.randint(2, (1,)):
451
+ magnitude *= -1.0
452
+
453
+ return _apply_op(img, op_name, magnitude, interpolation=self.interpolation, fill=fill)
454
+
455
+ def __repr__(self) -> str:
456
+ s = (
457
+ f"{self.__class__.__name__}("
458
+ f"num_magnitude_bins={self.num_magnitude_bins}"
459
+ f", interpolation={self.interpolation}"
460
+ f", fill={self.fill}"
461
+ f")"
462
+ )
463
+ return s
464
+
465
+
466
+ class AugMix(torch.nn.Module):
467
+ r"""AugMix data augmentation method based on
468
+ `"AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty" <https://arxiv.org/abs/1912.02781>`_.
469
+ If the image is torch Tensor, it should be of type torch.uint8, and it is expected
470
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
471
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
472
+
473
+ Args:
474
+ severity (int): The severity of base augmentation operators. Default is ``3``.
475
+ mixture_width (int): The number of augmentation chains. Default is ``3``.
476
+ chain_depth (int): The depth of augmentation chains. A negative value denotes stochastic depth sampled from the interval [1, 3].
477
+ Default is ``-1``.
478
+ alpha (float): The hyperparameter for the probability distributions. Default is ``1.0``.
479
+ all_ops (bool): Use all operations (including brightness, contrast, color and sharpness). Default is ``True``.
480
+ interpolation (InterpolationMode): Desired interpolation enum defined by
481
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
482
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
483
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
484
+ image. If given a number, the value is used for all bands respectively.
485
+ """
486
+
487
+ def __init__(
488
+ self,
489
+ severity: int = 3,
490
+ mixture_width: int = 3,
491
+ chain_depth: int = -1,
492
+ alpha: float = 1.0,
493
+ all_ops: bool = True,
494
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
495
+ fill: Optional[List[float]] = None,
496
+ ) -> None:
497
+ super().__init__()
498
+ self._PARAMETER_MAX = 10
499
+ if not (1 <= severity <= self._PARAMETER_MAX):
500
+ raise ValueError(f"The severity must be between [1, {self._PARAMETER_MAX}]. Got {severity} instead.")
501
+ self.severity = severity
502
+ self.mixture_width = mixture_width
503
+ self.chain_depth = chain_depth
504
+ self.alpha = alpha
505
+ self.all_ops = all_ops
506
+ self.interpolation = interpolation
507
+ self.fill = fill
508
+
509
+ def _augmentation_space(self, num_bins: int, image_size: Tuple[int, int]) -> Dict[str, Tuple[Tensor, bool]]:
510
+ s = {
511
+ # op_name: (magnitudes, signed)
512
+ "ShearX": (torch.linspace(0.0, 0.3, num_bins), True),
513
+ "ShearY": (torch.linspace(0.0, 0.3, num_bins), True),
514
+ "TranslateX": (torch.linspace(0.0, image_size[1] / 3.0, num_bins), True),
515
+ "TranslateY": (torch.linspace(0.0, image_size[0] / 3.0, num_bins), True),
516
+ "Rotate": (torch.linspace(0.0, 30.0, num_bins), True),
517
+ "Posterize": (4 - (torch.arange(num_bins) / ((num_bins - 1) / 4)).round().int(), False),
518
+ "Solarize": (torch.linspace(255.0, 0.0, num_bins), False),
519
+ "AutoContrast": (torch.tensor(0.0), False),
520
+ "Equalize": (torch.tensor(0.0), False),
521
+ }
522
+ if self.all_ops:
523
+ s.update(
524
+ {
525
+ "Brightness": (torch.linspace(0.0, 0.9, num_bins), True),
526
+ "Color": (torch.linspace(0.0, 0.9, num_bins), True),
527
+ "Contrast": (torch.linspace(0.0, 0.9, num_bins), True),
528
+ "Sharpness": (torch.linspace(0.0, 0.9, num_bins), True),
529
+ }
530
+ )
531
+ return s
532
+
533
+ @torch.jit.unused
534
+ def _pil_to_tensor(self, img) -> Tensor:
535
+ return F.pil_to_tensor(img)
536
+
537
+ @torch.jit.unused
538
+ def _tensor_to_pil(self, img: Tensor):
539
+ return F.to_pil_image(img)
540
+
541
+ def _sample_dirichlet(self, params: Tensor) -> Tensor:
542
+ # Must be on a separate method so that we can overwrite it in tests.
543
+ return torch._sample_dirichlet(params)
544
+
545
+ def forward(self, orig_img: Tensor) -> Tensor:
546
+ """
547
+ img (PIL Image or Tensor): Image to be transformed.
548
+
549
+ Returns:
550
+ PIL Image or Tensor: Transformed image.
551
+ """
552
+ fill = self.fill
553
+ channels, height, width = F.get_dimensions(orig_img)
554
+ if isinstance(orig_img, Tensor):
555
+ img = orig_img
556
+ if isinstance(fill, (int, float)):
557
+ fill = [float(fill)] * channels
558
+ elif fill is not None:
559
+ fill = [float(f) for f in fill]
560
+ else:
561
+ img = self._pil_to_tensor(orig_img)
562
+
563
+ op_meta = self._augmentation_space(self._PARAMETER_MAX, (height, width))
564
+
565
+ orig_dims = list(img.shape)
566
+ batch = img.view([1] * max(4 - img.ndim, 0) + orig_dims)
567
+ batch_dims = [batch.size(0)] + [1] * (batch.ndim - 1)
568
+
569
+ # Sample the beta weights for combining the original and augmented image. To get Beta, we use a Dirichlet
570
+ # with 2 parameters. The 1st column stores the weights of the original and the 2nd the ones of augmented image.
571
+ m = self._sample_dirichlet(
572
+ torch.tensor([self.alpha, self.alpha], device=batch.device).expand(batch_dims[0], -1)
573
+ )
574
+
575
+ # Sample the mixing weights and combine them with the ones sampled from Beta for the augmented images.
576
+ combined_weights = self._sample_dirichlet(
577
+ torch.tensor([self.alpha] * self.mixture_width, device=batch.device).expand(batch_dims[0], -1)
578
+ ) * m[:, 1].view([batch_dims[0], -1])
579
+
580
+ mix = m[:, 0].view(batch_dims) * batch
581
+ for i in range(self.mixture_width):
582
+ aug = batch
583
+ depth = self.chain_depth if self.chain_depth > 0 else int(torch.randint(low=1, high=4, size=(1,)).item())
584
+ for _ in range(depth):
585
+ op_index = int(torch.randint(len(op_meta), (1,)).item())
586
+ op_name = list(op_meta.keys())[op_index]
587
+ magnitudes, signed = op_meta[op_name]
588
+ magnitude = (
589
+ float(magnitudes[torch.randint(self.severity, (1,), dtype=torch.long)].item())
590
+ if magnitudes.ndim > 0
591
+ else 0.0
592
+ )
593
+ if signed and torch.randint(2, (1,)):
594
+ magnitude *= -1.0
595
+ aug = _apply_op(aug, op_name, magnitude, interpolation=self.interpolation, fill=fill)
596
+ mix.add_(combined_weights[:, i].view(batch_dims) * aug)
597
+ mix = mix.view(orig_dims).to(dtype=img.dtype)
598
+
599
+ if not isinstance(orig_img, Tensor):
600
+ return self._tensor_to_pil(mix)
601
+ return mix
602
+
603
+ def __repr__(self) -> str:
604
+ s = (
605
+ f"{self.__class__.__name__}("
606
+ f"severity={self.severity}"
607
+ f", mixture_width={self.mixture_width}"
608
+ f", chain_depth={self.chain_depth}"
609
+ f", alpha={self.alpha}"
610
+ f", all_ops={self.all_ops}"
611
+ f", interpolation={self.interpolation}"
612
+ f", fill={self.fill}"
613
+ f")"
614
+ )
615
+ return s
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/functional.py ADDED
@@ -0,0 +1,1569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ import sys
4
+ import warnings
5
+ from enum import Enum
6
+ from typing import Any, List, Optional, Tuple, Union
7
+
8
+ import numpy as np
9
+ import torch
10
+ from PIL import Image
11
+ from torch import Tensor
12
+
13
+ try:
14
+ import accimage
15
+ except ImportError:
16
+ accimage = None
17
+
18
+ from ..utils import _log_api_usage_once
19
+ from . import _functional_pil as F_pil, _functional_tensor as F_t
20
+
21
+
22
+ class InterpolationMode(Enum):
23
+ """Interpolation modes
24
+ Available interpolation methods are ``nearest``, ``nearest-exact``, ``bilinear``, ``bicubic``, ``box``, ``hamming``,
25
+ and ``lanczos``.
26
+ """
27
+
28
+ NEAREST = "nearest"
29
+ NEAREST_EXACT = "nearest-exact"
30
+ BILINEAR = "bilinear"
31
+ BICUBIC = "bicubic"
32
+ # For PIL compatibility
33
+ BOX = "box"
34
+ HAMMING = "hamming"
35
+ LANCZOS = "lanczos"
36
+
37
+
38
+ # TODO: Once torchscript supports Enums with staticmethod
39
+ # this can be put into InterpolationMode as staticmethod
40
+ def _interpolation_modes_from_int(i: int) -> InterpolationMode:
41
+ inverse_modes_mapping = {
42
+ 0: InterpolationMode.NEAREST,
43
+ 2: InterpolationMode.BILINEAR,
44
+ 3: InterpolationMode.BICUBIC,
45
+ 4: InterpolationMode.BOX,
46
+ 5: InterpolationMode.HAMMING,
47
+ 1: InterpolationMode.LANCZOS,
48
+ }
49
+ return inverse_modes_mapping[i]
50
+
51
+
52
+ pil_modes_mapping = {
53
+ InterpolationMode.NEAREST: 0,
54
+ InterpolationMode.BILINEAR: 2,
55
+ InterpolationMode.BICUBIC: 3,
56
+ InterpolationMode.NEAREST_EXACT: 0,
57
+ InterpolationMode.BOX: 4,
58
+ InterpolationMode.HAMMING: 5,
59
+ InterpolationMode.LANCZOS: 1,
60
+ }
61
+
62
+ _is_pil_image = F_pil._is_pil_image
63
+
64
+
65
+ def get_dimensions(img: Tensor) -> List[int]:
66
+ """Returns the dimensions of an image as [channels, height, width].
67
+
68
+ Args:
69
+ img (PIL Image or Tensor): The image to be checked.
70
+
71
+ Returns:
72
+ List[int]: The image dimensions.
73
+ """
74
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
75
+ _log_api_usage_once(get_dimensions)
76
+ if isinstance(img, torch.Tensor):
77
+ return F_t.get_dimensions(img)
78
+
79
+ return F_pil.get_dimensions(img)
80
+
81
+
82
+ def get_image_size(img: Tensor) -> List[int]:
83
+ """Returns the size of an image as [width, height].
84
+
85
+ Args:
86
+ img (PIL Image or Tensor): The image to be checked.
87
+
88
+ Returns:
89
+ List[int]: The image size.
90
+ """
91
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
92
+ _log_api_usage_once(get_image_size)
93
+ if isinstance(img, torch.Tensor):
94
+ return F_t.get_image_size(img)
95
+
96
+ return F_pil.get_image_size(img)
97
+
98
+
99
+ def get_image_num_channels(img: Tensor) -> int:
100
+ """Returns the number of channels of an image.
101
+
102
+ Args:
103
+ img (PIL Image or Tensor): The image to be checked.
104
+
105
+ Returns:
106
+ int: The number of channels.
107
+ """
108
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
109
+ _log_api_usage_once(get_image_num_channels)
110
+ if isinstance(img, torch.Tensor):
111
+ return F_t.get_image_num_channels(img)
112
+
113
+ return F_pil.get_image_num_channels(img)
114
+
115
+
116
+ @torch.jit.unused
117
+ def _is_numpy(img: Any) -> bool:
118
+ return isinstance(img, np.ndarray)
119
+
120
+
121
+ @torch.jit.unused
122
+ def _is_numpy_image(img: Any) -> bool:
123
+ return img.ndim in {2, 3}
124
+
125
+
126
+ def to_tensor(pic) -> Tensor:
127
+ """Convert a ``PIL Image`` or ``numpy.ndarray`` to tensor.
128
+ This function does not support torchscript.
129
+
130
+ See :class:`~torchvision.transforms.ToTensor` for more details.
131
+
132
+ Args:
133
+ pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
134
+
135
+ Returns:
136
+ Tensor: Converted image.
137
+ """
138
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
139
+ _log_api_usage_once(to_tensor)
140
+ if not (F_pil._is_pil_image(pic) or _is_numpy(pic)):
141
+ raise TypeError(f"pic should be PIL Image or ndarray. Got {type(pic)}")
142
+
143
+ if _is_numpy(pic) and not _is_numpy_image(pic):
144
+ raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.")
145
+
146
+ default_float_dtype = torch.get_default_dtype()
147
+
148
+ if isinstance(pic, np.ndarray):
149
+ # handle numpy array
150
+ if pic.ndim == 2:
151
+ pic = pic[:, :, None]
152
+
153
+ img = torch.from_numpy(pic.transpose((2, 0, 1))).contiguous()
154
+ # backward compatibility
155
+ if isinstance(img, torch.ByteTensor):
156
+ return img.to(dtype=default_float_dtype).div(255)
157
+ else:
158
+ return img
159
+
160
+ if accimage is not None and isinstance(pic, accimage.Image):
161
+ nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
162
+ pic.copyto(nppic)
163
+ return torch.from_numpy(nppic).to(dtype=default_float_dtype)
164
+
165
+ # handle PIL Image
166
+ mode_to_nptype = {"I": np.int32, "I;16" if sys.byteorder == "little" else "I;16B": np.int16, "F": np.float32}
167
+ img = torch.from_numpy(np.array(pic, mode_to_nptype.get(pic.mode, np.uint8), copy=True))
168
+
169
+ if pic.mode == "1":
170
+ img = 255 * img
171
+ img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic))
172
+ # put it from HWC to CHW format
173
+ img = img.permute((2, 0, 1)).contiguous()
174
+ if isinstance(img, torch.ByteTensor):
175
+ return img.to(dtype=default_float_dtype).div(255)
176
+ else:
177
+ return img
178
+
179
+
180
+ def pil_to_tensor(pic: Any) -> Tensor:
181
+ """Convert a ``PIL Image`` to a tensor of the same type.
182
+ This function does not support torchscript.
183
+
184
+ See :class:`~torchvision.transforms.PILToTensor` for more details.
185
+
186
+ .. note::
187
+
188
+ A deep copy of the underlying array is performed.
189
+
190
+ Args:
191
+ pic (PIL Image): Image to be converted to tensor.
192
+
193
+ Returns:
194
+ Tensor: Converted image.
195
+ """
196
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
197
+ _log_api_usage_once(pil_to_tensor)
198
+ if not F_pil._is_pil_image(pic):
199
+ raise TypeError(f"pic should be PIL Image. Got {type(pic)}")
200
+
201
+ if accimage is not None and isinstance(pic, accimage.Image):
202
+ # accimage format is always uint8 internally, so always return uint8 here
203
+ nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.uint8)
204
+ pic.copyto(nppic)
205
+ return torch.as_tensor(nppic)
206
+
207
+ # handle PIL Image
208
+ img = torch.as_tensor(np.array(pic, copy=True))
209
+ img = img.view(pic.size[1], pic.size[0], F_pil.get_image_num_channels(pic))
210
+ # put it from HWC to CHW format
211
+ img = img.permute((2, 0, 1))
212
+ return img
213
+
214
+
215
+ def convert_image_dtype(image: torch.Tensor, dtype: torch.dtype = torch.float) -> torch.Tensor:
216
+ """Convert a tensor image to the given ``dtype`` and scale the values accordingly
217
+ This function does not support PIL Image.
218
+
219
+ Args:
220
+ image (torch.Tensor): Image to be converted
221
+ dtype (torch.dtype): Desired data type of the output
222
+
223
+ Returns:
224
+ Tensor: Converted image
225
+
226
+ .. note::
227
+
228
+ When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
229
+ If converted back and forth, this mismatch has no effect.
230
+
231
+ Raises:
232
+ RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
233
+ well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
234
+ overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
235
+ of the integer ``dtype``.
236
+ """
237
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
238
+ _log_api_usage_once(convert_image_dtype)
239
+ if not isinstance(image, torch.Tensor):
240
+ raise TypeError("Input img should be Tensor Image")
241
+
242
+ return F_t.convert_image_dtype(image, dtype)
243
+
244
+
245
+ def to_pil_image(pic, mode=None):
246
+ """Convert a tensor or an ndarray to PIL Image. This function does not support torchscript.
247
+
248
+ See :class:`~torchvision.transforms.ToPILImage` for more details.
249
+
250
+ Args:
251
+ pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
252
+ mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
253
+
254
+ .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
255
+
256
+ Returns:
257
+ PIL Image: Image converted to PIL Image.
258
+ """
259
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
260
+ _log_api_usage_once(to_pil_image)
261
+
262
+ if isinstance(pic, torch.Tensor):
263
+ if pic.ndim == 3:
264
+ pic = pic.permute((1, 2, 0))
265
+ pic = pic.numpy(force=True)
266
+ elif not isinstance(pic, np.ndarray):
267
+ raise TypeError(f"pic should be Tensor or ndarray. Got {type(pic)}.")
268
+
269
+ if pic.ndim == 2:
270
+ # if 2D image, add channel dimension (HWC)
271
+ pic = np.expand_dims(pic, 2)
272
+ if pic.ndim != 3:
273
+ raise ValueError(f"pic should be 2/3 dimensional. Got {pic.ndim} dimensions.")
274
+
275
+ if pic.shape[-1] > 4:
276
+ raise ValueError(f"pic should not have > 4 channels. Got {pic.shape[-1]} channels.")
277
+
278
+ npimg = pic
279
+
280
+ if np.issubdtype(npimg.dtype, np.floating) and mode != "F":
281
+ npimg = (npimg * 255).astype(np.uint8)
282
+
283
+ if npimg.shape[2] == 1:
284
+ expected_mode = None
285
+ npimg = npimg[:, :, 0]
286
+ if npimg.dtype == np.uint8:
287
+ expected_mode = "L"
288
+ elif npimg.dtype == np.int16:
289
+ expected_mode = "I;16" if sys.byteorder == "little" else "I;16B"
290
+ elif npimg.dtype == np.int32:
291
+ expected_mode = "I"
292
+ elif npimg.dtype == np.float32:
293
+ expected_mode = "F"
294
+ if mode is not None and mode != expected_mode:
295
+ raise ValueError(f"Incorrect mode ({mode}) supplied for input type {np.dtype}. Should be {expected_mode}")
296
+ mode = expected_mode
297
+
298
+ elif npimg.shape[2] == 2:
299
+ permitted_2_channel_modes = ["LA"]
300
+ if mode is not None and mode not in permitted_2_channel_modes:
301
+ raise ValueError(f"Only modes {permitted_2_channel_modes} are supported for 2D inputs")
302
+
303
+ if mode is None and npimg.dtype == np.uint8:
304
+ mode = "LA"
305
+
306
+ elif npimg.shape[2] == 4:
307
+ permitted_4_channel_modes = ["RGBA", "CMYK", "RGBX"]
308
+ if mode is not None and mode not in permitted_4_channel_modes:
309
+ raise ValueError(f"Only modes {permitted_4_channel_modes} are supported for 4D inputs")
310
+
311
+ if mode is None and npimg.dtype == np.uint8:
312
+ mode = "RGBA"
313
+ else:
314
+ permitted_3_channel_modes = ["RGB", "YCbCr", "HSV"]
315
+ if mode is not None and mode not in permitted_3_channel_modes:
316
+ raise ValueError(f"Only modes {permitted_3_channel_modes} are supported for 3D inputs")
317
+ if mode is None and npimg.dtype == np.uint8:
318
+ mode = "RGB"
319
+
320
+ if mode is None:
321
+ raise TypeError(f"Input type {npimg.dtype} is not supported")
322
+
323
+ return Image.fromarray(npimg, mode=mode)
324
+
325
+
326
+ def normalize(tensor: Tensor, mean: List[float], std: List[float], inplace: bool = False) -> Tensor:
327
+ """Normalize a float tensor image with mean and standard deviation.
328
+ This transform does not support PIL Image.
329
+
330
+ .. note::
331
+ This transform acts out of place by default, i.e., it does not mutates the input tensor.
332
+
333
+ See :class:`~torchvision.transforms.Normalize` for more details.
334
+
335
+ Args:
336
+ tensor (Tensor): Float tensor image of size (C, H, W) or (B, C, H, W) to be normalized.
337
+ mean (sequence): Sequence of means for each channel.
338
+ std (sequence): Sequence of standard deviations for each channel.
339
+ inplace(bool,optional): Bool to make this operation inplace.
340
+
341
+ Returns:
342
+ Tensor: Normalized Tensor image.
343
+ """
344
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
345
+ _log_api_usage_once(normalize)
346
+ if not isinstance(tensor, torch.Tensor):
347
+ raise TypeError(f"img should be Tensor Image. Got {type(tensor)}")
348
+
349
+ return F_t.normalize(tensor, mean=mean, std=std, inplace=inplace)
350
+
351
+
352
+ def _compute_resized_output_size(
353
+ image_size: Tuple[int, int], size: List[int], max_size: Optional[int] = None
354
+ ) -> List[int]:
355
+ if len(size) == 1: # specified size only for the smallest edge
356
+ h, w = image_size
357
+ short, long = (w, h) if w <= h else (h, w)
358
+ requested_new_short = size if isinstance(size, int) else size[0]
359
+
360
+ new_short, new_long = requested_new_short, int(requested_new_short * long / short)
361
+
362
+ if max_size is not None:
363
+ if max_size <= requested_new_short:
364
+ raise ValueError(
365
+ f"max_size = {max_size} must be strictly greater than the requested "
366
+ f"size for the smaller edge size = {size}"
367
+ )
368
+ if new_long > max_size:
369
+ new_short, new_long = int(max_size * new_short / new_long), max_size
370
+
371
+ new_w, new_h = (new_short, new_long) if w <= h else (new_long, new_short)
372
+ else: # specified both h and w
373
+ new_w, new_h = size[1], size[0]
374
+ return [new_h, new_w]
375
+
376
+
377
+ def resize(
378
+ img: Tensor,
379
+ size: List[int],
380
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
381
+ max_size: Optional[int] = None,
382
+ antialias: Optional[bool] = True,
383
+ ) -> Tensor:
384
+ r"""Resize the input image to the given size.
385
+ If the image is torch Tensor, it is expected
386
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
387
+
388
+ Args:
389
+ img (PIL Image or Tensor): Image to be resized.
390
+ size (sequence or int): Desired output size. If size is a sequence like
391
+ (h, w), the output size will be matched to this. If size is an int,
392
+ the smaller edge of the image will be matched to this number maintaining
393
+ the aspect ratio. i.e, if height > width, then image will be rescaled to
394
+ :math:`\left(\text{size} \times \frac{\text{height}}{\text{width}}, \text{size}\right)`.
395
+
396
+ .. note::
397
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
398
+ interpolation (InterpolationMode): Desired interpolation enum defined by
399
+ :class:`torchvision.transforms.InterpolationMode`.
400
+ Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
401
+ ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are
402
+ supported.
403
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
404
+ max_size (int, optional): The maximum allowed for the longer edge of
405
+ the resized image. If the longer edge of the image is greater
406
+ than ``max_size`` after being resized according to ``size``,
407
+ ``size`` will be overruled so that the longer edge is equal to
408
+ ``max_size``.
409
+ As a result, the smaller edge may be shorter than ``size``. This
410
+ is only supported if ``size`` is an int (or a sequence of length
411
+ 1 in torchscript mode).
412
+ antialias (bool, optional): Whether to apply antialiasing.
413
+ It only affects **tensors** with bilinear or bicubic modes and it is
414
+ ignored otherwise: on PIL images, antialiasing is always applied on
415
+ bilinear or bicubic modes; on other modes (for PIL images and
416
+ tensors), antialiasing makes no sense and this parameter is ignored.
417
+ Possible values are:
418
+
419
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
420
+ Other mode aren't affected. This is probably what you want to use.
421
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
422
+ images are still antialiased on bilinear or bicubic modes, because
423
+ PIL doesn't support no antialias.
424
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
425
+ PIL images. This value exists for legacy reasons and you probably
426
+ don't want to use it unless you really know what you are doing.
427
+
428
+ The default value changed from ``None`` to ``True`` in
429
+ v0.17, for the PIL and Tensor backends to be consistent.
430
+
431
+ Returns:
432
+ PIL Image or Tensor: Resized image.
433
+ """
434
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
435
+ _log_api_usage_once(resize)
436
+
437
+ if isinstance(interpolation, int):
438
+ interpolation = _interpolation_modes_from_int(interpolation)
439
+ elif not isinstance(interpolation, InterpolationMode):
440
+ raise TypeError(
441
+ "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
442
+ )
443
+
444
+ if isinstance(size, (list, tuple)):
445
+ if len(size) not in [1, 2]:
446
+ raise ValueError(
447
+ f"Size must be an int or a 1 or 2 element tuple/list, not a {len(size)} element tuple/list"
448
+ )
449
+ if max_size is not None and len(size) != 1:
450
+ raise ValueError(
451
+ "max_size should only be passed if size specifies the length of the smaller edge, "
452
+ "i.e. size should be an int or a sequence of length 1 in torchscript mode."
453
+ )
454
+
455
+ _, image_height, image_width = get_dimensions(img)
456
+ if isinstance(size, int):
457
+ size = [size]
458
+ output_size = _compute_resized_output_size((image_height, image_width), size, max_size)
459
+
460
+ if [image_height, image_width] == output_size:
461
+ return img
462
+
463
+ if not isinstance(img, torch.Tensor):
464
+ if antialias is False:
465
+ warnings.warn("Anti-alias option is always applied for PIL Image input. Argument antialias is ignored.")
466
+ pil_interpolation = pil_modes_mapping[interpolation]
467
+ return F_pil.resize(img, size=output_size, interpolation=pil_interpolation)
468
+
469
+ return F_t.resize(img, size=output_size, interpolation=interpolation.value, antialias=antialias)
470
+
471
+
472
+ def pad(img: Tensor, padding: List[int], fill: Union[int, float] = 0, padding_mode: str = "constant") -> Tensor:
473
+ r"""Pad the given image on all sides with the given "pad" value.
474
+ If the image is torch Tensor, it is expected
475
+ to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
476
+ at most 3 leading dimensions for mode edge,
477
+ and an arbitrary number of leading dimensions for mode constant
478
+
479
+ Args:
480
+ img (PIL Image or Tensor): Image to be padded.
481
+ padding (int or sequence): Padding on each border. If a single int is provided this
482
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
483
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
484
+ this is the padding for the left, top, right and bottom borders respectively.
485
+
486
+ .. note::
487
+ In torchscript mode padding as single int is not supported, use a sequence of
488
+ length 1: ``[padding, ]``.
489
+ fill (number or tuple): Pixel fill value for constant fill. Default is 0.
490
+ If a tuple of length 3, it is used to fill R, G, B channels respectively.
491
+ This value is only used when the padding_mode is constant.
492
+ Only number is supported for torch Tensor.
493
+ Only int or tuple value is supported for PIL Image.
494
+ padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
495
+ Default is constant.
496
+
497
+ - constant: pads with a constant value, this value is specified with fill
498
+
499
+ - edge: pads with the last value at the edge of the image.
500
+ If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2
501
+
502
+ - reflect: pads with reflection of image without repeating the last value on the edge.
503
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
504
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
505
+
506
+ - symmetric: pads with reflection of image repeating the last value on the edge.
507
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
508
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
509
+
510
+ Returns:
511
+ PIL Image or Tensor: Padded image.
512
+ """
513
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
514
+ _log_api_usage_once(pad)
515
+ if not isinstance(img, torch.Tensor):
516
+ return F_pil.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
517
+
518
+ return F_t.pad(img, padding=padding, fill=fill, padding_mode=padding_mode)
519
+
520
+
521
+ def crop(img: Tensor, top: int, left: int, height: int, width: int) -> Tensor:
522
+ """Crop the given image at specified location and output size.
523
+ If the image is torch Tensor, it is expected
524
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
525
+ If image size is smaller than output size along any edge, image is padded with 0 and then cropped.
526
+
527
+ Args:
528
+ img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
529
+ top (int): Vertical component of the top left corner of the crop box.
530
+ left (int): Horizontal component of the top left corner of the crop box.
531
+ height (int): Height of the crop box.
532
+ width (int): Width of the crop box.
533
+
534
+ Returns:
535
+ PIL Image or Tensor: Cropped image.
536
+ """
537
+
538
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
539
+ _log_api_usage_once(crop)
540
+ if not isinstance(img, torch.Tensor):
541
+ return F_pil.crop(img, top, left, height, width)
542
+
543
+ return F_t.crop(img, top, left, height, width)
544
+
545
+
546
+ def center_crop(img: Tensor, output_size: List[int]) -> Tensor:
547
+ """Crops the given image at the center.
548
+ If the image is torch Tensor, it is expected
549
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
550
+ If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
551
+
552
+ Args:
553
+ img (PIL Image or Tensor): Image to be cropped.
554
+ output_size (sequence or int): (height, width) of the crop box. If int or sequence with single int,
555
+ it is used for both directions.
556
+
557
+ Returns:
558
+ PIL Image or Tensor: Cropped image.
559
+ """
560
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
561
+ _log_api_usage_once(center_crop)
562
+ if isinstance(output_size, numbers.Number):
563
+ output_size = (int(output_size), int(output_size))
564
+ elif isinstance(output_size, (tuple, list)) and len(output_size) == 1:
565
+ output_size = (output_size[0], output_size[0])
566
+
567
+ _, image_height, image_width = get_dimensions(img)
568
+ crop_height, crop_width = output_size
569
+
570
+ if crop_width > image_width or crop_height > image_height:
571
+ padding_ltrb = [
572
+ (crop_width - image_width) // 2 if crop_width > image_width else 0,
573
+ (crop_height - image_height) // 2 if crop_height > image_height else 0,
574
+ (crop_width - image_width + 1) // 2 if crop_width > image_width else 0,
575
+ (crop_height - image_height + 1) // 2 if crop_height > image_height else 0,
576
+ ]
577
+ img = pad(img, padding_ltrb, fill=0) # PIL uses fill value 0
578
+ _, image_height, image_width = get_dimensions(img)
579
+ if crop_width == image_width and crop_height == image_height:
580
+ return img
581
+
582
+ crop_top = int(round((image_height - crop_height) / 2.0))
583
+ crop_left = int(round((image_width - crop_width) / 2.0))
584
+ return crop(img, crop_top, crop_left, crop_height, crop_width)
585
+
586
+
587
+ def resized_crop(
588
+ img: Tensor,
589
+ top: int,
590
+ left: int,
591
+ height: int,
592
+ width: int,
593
+ size: List[int],
594
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
595
+ antialias: Optional[bool] = True,
596
+ ) -> Tensor:
597
+ """Crop the given image and resize it to desired size.
598
+ If the image is torch Tensor, it is expected
599
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
600
+
601
+ Notably used in :class:`~torchvision.transforms.RandomResizedCrop`.
602
+
603
+ Args:
604
+ img (PIL Image or Tensor): Image to be cropped. (0,0) denotes the top left corner of the image.
605
+ top (int): Vertical component of the top left corner of the crop box.
606
+ left (int): Horizontal component of the top left corner of the crop box.
607
+ height (int): Height of the crop box.
608
+ width (int): Width of the crop box.
609
+ size (sequence or int): Desired output size. Same semantics as ``resize``.
610
+ interpolation (InterpolationMode): Desired interpolation enum defined by
611
+ :class:`torchvision.transforms.InterpolationMode`.
612
+ Default is ``InterpolationMode.BILINEAR``. If input is Tensor, only ``InterpolationMode.NEAREST``,
613
+ ``InterpolationMode.NEAREST_EXACT``, ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are
614
+ supported.
615
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
616
+ antialias (bool, optional): Whether to apply antialiasing.
617
+ It only affects **tensors** with bilinear or bicubic modes and it is
618
+ ignored otherwise: on PIL images, antialiasing is always applied on
619
+ bilinear or bicubic modes; on other modes (for PIL images and
620
+ tensors), antialiasing makes no sense and this parameter is ignored.
621
+ Possible values are:
622
+
623
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
624
+ Other mode aren't affected. This is probably what you want to use.
625
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
626
+ images are still antialiased on bilinear or bicubic modes, because
627
+ PIL doesn't support no antialias.
628
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
629
+ PIL images. This value exists for legacy reasons and you probably
630
+ don't want to use it unless you really know what you are doing.
631
+
632
+ The default value changed from ``None`` to ``True`` in
633
+ v0.17, for the PIL and Tensor backends to be consistent.
634
+ Returns:
635
+ PIL Image or Tensor: Cropped image.
636
+ """
637
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
638
+ _log_api_usage_once(resized_crop)
639
+ img = crop(img, top, left, height, width)
640
+ img = resize(img, size, interpolation, antialias=antialias)
641
+ return img
642
+
643
+
644
+ def hflip(img: Tensor) -> Tensor:
645
+ """Horizontally flip the given image.
646
+
647
+ Args:
648
+ img (PIL Image or Tensor): Image to be flipped. If img
649
+ is a Tensor, it is expected to be in [..., H, W] format,
650
+ where ... means it can have an arbitrary number of leading
651
+ dimensions.
652
+
653
+ Returns:
654
+ PIL Image or Tensor: Horizontally flipped image.
655
+ """
656
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
657
+ _log_api_usage_once(hflip)
658
+ if not isinstance(img, torch.Tensor):
659
+ return F_pil.hflip(img)
660
+
661
+ return F_t.hflip(img)
662
+
663
+
664
+ def _get_perspective_coeffs(startpoints: List[List[int]], endpoints: List[List[int]]) -> List[float]:
665
+ """Helper function to get the coefficients (a, b, c, d, e, f, g, h) for the perspective transforms.
666
+
667
+ In Perspective Transform each pixel (x, y) in the original image gets transformed as,
668
+ (x, y) -> ( (ax + by + c) / (gx + hy + 1), (dx + ey + f) / (gx + hy + 1) )
669
+
670
+ Args:
671
+ startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
672
+ ``[top-left, top-right, bottom-right, bottom-left]`` of the original image.
673
+ endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
674
+ ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image.
675
+
676
+ Returns:
677
+ octuple (a, b, c, d, e, f, g, h) for transforming each pixel.
678
+ """
679
+ a_matrix = torch.zeros(2 * len(startpoints), 8, dtype=torch.float)
680
+
681
+ for i, (p1, p2) in enumerate(zip(endpoints, startpoints)):
682
+ a_matrix[2 * i, :] = torch.tensor([p1[0], p1[1], 1, 0, 0, 0, -p2[0] * p1[0], -p2[0] * p1[1]])
683
+ a_matrix[2 * i + 1, :] = torch.tensor([0, 0, 0, p1[0], p1[1], 1, -p2[1] * p1[0], -p2[1] * p1[1]])
684
+
685
+ b_matrix = torch.tensor(startpoints, dtype=torch.float).view(8)
686
+ res = torch.linalg.lstsq(a_matrix, b_matrix, driver="gels").solution
687
+
688
+ output: List[float] = res.tolist()
689
+ return output
690
+
691
+
692
+ def perspective(
693
+ img: Tensor,
694
+ startpoints: List[List[int]],
695
+ endpoints: List[List[int]],
696
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
697
+ fill: Optional[List[float]] = None,
698
+ ) -> Tensor:
699
+ """Perform perspective transform of the given image.
700
+ If the image is torch Tensor, it is expected
701
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
702
+
703
+ Args:
704
+ img (PIL Image or Tensor): Image to be transformed.
705
+ startpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
706
+ ``[top-left, top-right, bottom-right, bottom-left]`` of the original image.
707
+ endpoints (list of list of ints): List containing four lists of two integers corresponding to four corners
708
+ ``[top-left, top-right, bottom-right, bottom-left]`` of the transformed image.
709
+ interpolation (InterpolationMode): Desired interpolation enum defined by
710
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
711
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
712
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
713
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
714
+ image. If given a number, the value is used for all bands respectively.
715
+
716
+ .. note::
717
+ In torchscript mode single int/float value is not supported, please use a sequence
718
+ of length 1: ``[value, ]``.
719
+
720
+ Returns:
721
+ PIL Image or Tensor: transformed Image.
722
+ """
723
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
724
+ _log_api_usage_once(perspective)
725
+
726
+ coeffs = _get_perspective_coeffs(startpoints, endpoints)
727
+
728
+ if isinstance(interpolation, int):
729
+ interpolation = _interpolation_modes_from_int(interpolation)
730
+ elif not isinstance(interpolation, InterpolationMode):
731
+ raise TypeError(
732
+ "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
733
+ )
734
+
735
+ if not isinstance(img, torch.Tensor):
736
+ pil_interpolation = pil_modes_mapping[interpolation]
737
+ return F_pil.perspective(img, coeffs, interpolation=pil_interpolation, fill=fill)
738
+
739
+ return F_t.perspective(img, coeffs, interpolation=interpolation.value, fill=fill)
740
+
741
+
742
+ def vflip(img: Tensor) -> Tensor:
743
+ """Vertically flip the given image.
744
+
745
+ Args:
746
+ img (PIL Image or Tensor): Image to be flipped. If img
747
+ is a Tensor, it is expected to be in [..., H, W] format,
748
+ where ... means it can have an arbitrary number of leading
749
+ dimensions.
750
+
751
+ Returns:
752
+ PIL Image or Tensor: Vertically flipped image.
753
+ """
754
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
755
+ _log_api_usage_once(vflip)
756
+ if not isinstance(img, torch.Tensor):
757
+ return F_pil.vflip(img)
758
+
759
+ return F_t.vflip(img)
760
+
761
+
762
+ def five_crop(img: Tensor, size: List[int]) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
763
+ """Crop the given image into four corners and the central crop.
764
+ If the image is torch Tensor, it is expected
765
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
766
+
767
+ .. Note::
768
+ This transform returns a tuple of images and there may be a
769
+ mismatch in the number of inputs and targets your ``Dataset`` returns.
770
+
771
+ Args:
772
+ img (PIL Image or Tensor): Image to be cropped.
773
+ size (sequence or int): Desired output size of the crop. If size is an
774
+ int instead of sequence like (h, w), a square crop (size, size) is
775
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
776
+
777
+ Returns:
778
+ tuple: tuple (tl, tr, bl, br, center)
779
+ Corresponding top left, top right, bottom left, bottom right and center crop.
780
+ """
781
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
782
+ _log_api_usage_once(five_crop)
783
+ if isinstance(size, numbers.Number):
784
+ size = (int(size), int(size))
785
+ elif isinstance(size, (tuple, list)) and len(size) == 1:
786
+ size = (size[0], size[0])
787
+
788
+ if len(size) != 2:
789
+ raise ValueError("Please provide only two dimensions (h, w) for size.")
790
+
791
+ _, image_height, image_width = get_dimensions(img)
792
+ crop_height, crop_width = size
793
+ if crop_width > image_width or crop_height > image_height:
794
+ msg = "Requested crop size {} is bigger than input size {}"
795
+ raise ValueError(msg.format(size, (image_height, image_width)))
796
+
797
+ tl = crop(img, 0, 0, crop_height, crop_width)
798
+ tr = crop(img, 0, image_width - crop_width, crop_height, crop_width)
799
+ bl = crop(img, image_height - crop_height, 0, crop_height, crop_width)
800
+ br = crop(img, image_height - crop_height, image_width - crop_width, crop_height, crop_width)
801
+
802
+ center = center_crop(img, [crop_height, crop_width])
803
+
804
+ return tl, tr, bl, br, center
805
+
806
+
807
+ def ten_crop(
808
+ img: Tensor, size: List[int], vertical_flip: bool = False
809
+ ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
810
+ """Generate ten cropped images from the given image.
811
+ Crop the given image into four corners and the central crop plus the
812
+ flipped version of these (horizontal flipping is used by default).
813
+ If the image is torch Tensor, it is expected
814
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
815
+
816
+ .. Note::
817
+ This transform returns a tuple of images and there may be a
818
+ mismatch in the number of inputs and targets your ``Dataset`` returns.
819
+
820
+ Args:
821
+ img (PIL Image or Tensor): Image to be cropped.
822
+ size (sequence or int): Desired output size of the crop. If size is an
823
+ int instead of sequence like (h, w), a square crop (size, size) is
824
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
825
+ vertical_flip (bool): Use vertical flipping instead of horizontal
826
+
827
+ Returns:
828
+ tuple: tuple (tl, tr, bl, br, center, tl_flip, tr_flip, bl_flip, br_flip, center_flip)
829
+ Corresponding top left, top right, bottom left, bottom right and
830
+ center crop and same for the flipped image.
831
+ """
832
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
833
+ _log_api_usage_once(ten_crop)
834
+ if isinstance(size, numbers.Number):
835
+ size = (int(size), int(size))
836
+ elif isinstance(size, (tuple, list)) and len(size) == 1:
837
+ size = (size[0], size[0])
838
+
839
+ if len(size) != 2:
840
+ raise ValueError("Please provide only two dimensions (h, w) for size.")
841
+
842
+ first_five = five_crop(img, size)
843
+
844
+ if vertical_flip:
845
+ img = vflip(img)
846
+ else:
847
+ img = hflip(img)
848
+
849
+ second_five = five_crop(img, size)
850
+ return first_five + second_five
851
+
852
+
853
+ def adjust_brightness(img: Tensor, brightness_factor: float) -> Tensor:
854
+ """Adjust brightness of an image.
855
+
856
+ Args:
857
+ img (PIL Image or Tensor): Image to be adjusted.
858
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
859
+ where ... means it can have an arbitrary number of leading dimensions.
860
+ brightness_factor (float): How much to adjust the brightness. Can be
861
+ any non-negative number. 0 gives a black image, 1 gives the
862
+ original image while 2 increases the brightness by a factor of 2.
863
+
864
+ Returns:
865
+ PIL Image or Tensor: Brightness adjusted image.
866
+ """
867
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
868
+ _log_api_usage_once(adjust_brightness)
869
+ if not isinstance(img, torch.Tensor):
870
+ return F_pil.adjust_brightness(img, brightness_factor)
871
+
872
+ return F_t.adjust_brightness(img, brightness_factor)
873
+
874
+
875
+ def adjust_contrast(img: Tensor, contrast_factor: float) -> Tensor:
876
+ """Adjust contrast of an image.
877
+
878
+ Args:
879
+ img (PIL Image or Tensor): Image to be adjusted.
880
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
881
+ where ... means it can have an arbitrary number of leading dimensions.
882
+ contrast_factor (float): How much to adjust the contrast. Can be any
883
+ non-negative number. 0 gives a solid gray image, 1 gives the
884
+ original image while 2 increases the contrast by a factor of 2.
885
+
886
+ Returns:
887
+ PIL Image or Tensor: Contrast adjusted image.
888
+ """
889
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
890
+ _log_api_usage_once(adjust_contrast)
891
+ if not isinstance(img, torch.Tensor):
892
+ return F_pil.adjust_contrast(img, contrast_factor)
893
+
894
+ return F_t.adjust_contrast(img, contrast_factor)
895
+
896
+
897
+ def adjust_saturation(img: Tensor, saturation_factor: float) -> Tensor:
898
+ """Adjust color saturation of an image.
899
+
900
+ Args:
901
+ img (PIL Image or Tensor): Image to be adjusted.
902
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
903
+ where ... means it can have an arbitrary number of leading dimensions.
904
+ saturation_factor (float): How much to adjust the saturation. 0 will
905
+ give a black and white image, 1 will give the original image while
906
+ 2 will enhance the saturation by a factor of 2.
907
+
908
+ Returns:
909
+ PIL Image or Tensor: Saturation adjusted image.
910
+ """
911
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
912
+ _log_api_usage_once(adjust_saturation)
913
+ if not isinstance(img, torch.Tensor):
914
+ return F_pil.adjust_saturation(img, saturation_factor)
915
+
916
+ return F_t.adjust_saturation(img, saturation_factor)
917
+
918
+
919
+ def adjust_hue(img: Tensor, hue_factor: float) -> Tensor:
920
+ """Adjust hue of an image.
921
+
922
+ The image hue is adjusted by converting the image to HSV and
923
+ cyclically shifting the intensities in the hue channel (H).
924
+ The image is then converted back to original image mode.
925
+
926
+ `hue_factor` is the amount of shift in H channel and must be in the
927
+ interval `[-0.5, 0.5]`.
928
+
929
+ See `Hue`_ for more details.
930
+
931
+ .. _Hue: https://en.wikipedia.org/wiki/Hue
932
+
933
+ Args:
934
+ img (PIL Image or Tensor): Image to be adjusted.
935
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
936
+ where ... means it can have an arbitrary number of leading dimensions.
937
+ If img is PIL Image mode "1", "I", "F" and modes with transparency (alpha channel) are not supported.
938
+ Note: the pixel values of the input image has to be non-negative for conversion to HSV space;
939
+ thus it does not work if you normalize your image to an interval with negative values,
940
+ or use an interpolation that generates negative values before using this function.
941
+ hue_factor (float): How much to shift the hue channel. Should be in
942
+ [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
943
+ HSV space in positive and negative direction respectively.
944
+ 0 means no shift. Therefore, both -0.5 and 0.5 will give an image
945
+ with complementary colors while 0 gives the original image.
946
+
947
+ Returns:
948
+ PIL Image or Tensor: Hue adjusted image.
949
+ """
950
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
951
+ _log_api_usage_once(adjust_hue)
952
+ if not isinstance(img, torch.Tensor):
953
+ return F_pil.adjust_hue(img, hue_factor)
954
+
955
+ return F_t.adjust_hue(img, hue_factor)
956
+
957
+
958
+ def adjust_gamma(img: Tensor, gamma: float, gain: float = 1) -> Tensor:
959
+ r"""Perform gamma correction on an image.
960
+
961
+ Also known as Power Law Transform. Intensities in RGB mode are adjusted
962
+ based on the following equation:
963
+
964
+ .. math::
965
+ I_{\text{out}} = 255 \times \text{gain} \times \left(\frac{I_{\text{in}}}{255}\right)^{\gamma}
966
+
967
+ See `Gamma Correction`_ for more details.
968
+
969
+ .. _Gamma Correction: https://en.wikipedia.org/wiki/Gamma_correction
970
+
971
+ Args:
972
+ img (PIL Image or Tensor): PIL Image to be adjusted.
973
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
974
+ where ... means it can have an arbitrary number of leading dimensions.
975
+ If img is PIL Image, modes with transparency (alpha channel) are not supported.
976
+ gamma (float): Non negative real number, same as :math:`\gamma` in the equation.
977
+ gamma larger than 1 make the shadows darker,
978
+ while gamma smaller than 1 make dark regions lighter.
979
+ gain (float): The constant multiplier.
980
+ Returns:
981
+ PIL Image or Tensor: Gamma correction adjusted image.
982
+ """
983
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
984
+ _log_api_usage_once(adjust_gamma)
985
+ if not isinstance(img, torch.Tensor):
986
+ return F_pil.adjust_gamma(img, gamma, gain)
987
+
988
+ return F_t.adjust_gamma(img, gamma, gain)
989
+
990
+
991
+ def _get_inverse_affine_matrix(
992
+ center: List[float], angle: float, translate: List[float], scale: float, shear: List[float], inverted: bool = True
993
+ ) -> List[float]:
994
+ # Helper method to compute inverse matrix for affine transformation
995
+
996
+ # Pillow requires inverse affine transformation matrix:
997
+ # Affine matrix is : M = T * C * RotateScaleShear * C^-1
998
+ #
999
+ # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1]
1000
+ # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1]
1001
+ # RotateScaleShear is rotation with scale and shear matrix
1002
+ #
1003
+ # RotateScaleShear(a, s, (sx, sy)) =
1004
+ # = R(a) * S(s) * SHy(sy) * SHx(sx)
1005
+ # = [ s*cos(a - sy)/cos(sy), s*(-cos(a - sy)*tan(sx)/cos(sy) - sin(a)), 0 ]
1006
+ # [ s*sin(a - sy)/cos(sy), s*(-sin(a - sy)*tan(sx)/cos(sy) + cos(a)), 0 ]
1007
+ # [ 0 , 0 , 1 ]
1008
+ # where R is a rotation matrix, S is a scaling matrix, and SHx and SHy are the shears:
1009
+ # SHx(s) = [1, -tan(s)] and SHy(s) = [1 , 0]
1010
+ # [0, 1 ] [-tan(s), 1]
1011
+ #
1012
+ # Thus, the inverse is M^-1 = C * RotateScaleShear^-1 * C^-1 * T^-1
1013
+
1014
+ rot = math.radians(angle)
1015
+ sx = math.radians(shear[0])
1016
+ sy = math.radians(shear[1])
1017
+
1018
+ cx, cy = center
1019
+ tx, ty = translate
1020
+
1021
+ # RSS without scaling
1022
+ a = math.cos(rot - sy) / math.cos(sy)
1023
+ b = -math.cos(rot - sy) * math.tan(sx) / math.cos(sy) - math.sin(rot)
1024
+ c = math.sin(rot - sy) / math.cos(sy)
1025
+ d = -math.sin(rot - sy) * math.tan(sx) / math.cos(sy) + math.cos(rot)
1026
+
1027
+ if inverted:
1028
+ # Inverted rotation matrix with scale and shear
1029
+ # det([[a, b], [c, d]]) == 1, since det(rotation) = 1 and det(shear) = 1
1030
+ matrix = [d, -b, 0.0, -c, a, 0.0]
1031
+ matrix = [x / scale for x in matrix]
1032
+ # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1
1033
+ matrix[2] += matrix[0] * (-cx - tx) + matrix[1] * (-cy - ty)
1034
+ matrix[5] += matrix[3] * (-cx - tx) + matrix[4] * (-cy - ty)
1035
+ # Apply center translation: C * RSS^-1 * C^-1 * T^-1
1036
+ matrix[2] += cx
1037
+ matrix[5] += cy
1038
+ else:
1039
+ matrix = [a, b, 0.0, c, d, 0.0]
1040
+ matrix = [x * scale for x in matrix]
1041
+ # Apply inverse of center translation: RSS * C^-1
1042
+ matrix[2] += matrix[0] * (-cx) + matrix[1] * (-cy)
1043
+ matrix[5] += matrix[3] * (-cx) + matrix[4] * (-cy)
1044
+ # Apply translation and center : T * C * RSS * C^-1
1045
+ matrix[2] += cx + tx
1046
+ matrix[5] += cy + ty
1047
+
1048
+ return matrix
1049
+
1050
+
1051
+ def rotate(
1052
+ img: Tensor,
1053
+ angle: float,
1054
+ interpolation: InterpolationMode = InterpolationMode.NEAREST,
1055
+ expand: bool = False,
1056
+ center: Optional[List[int]] = None,
1057
+ fill: Optional[List[float]] = None,
1058
+ ) -> Tensor:
1059
+ """Rotate the image by angle.
1060
+ If the image is torch Tensor, it is expected
1061
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
1062
+
1063
+ Args:
1064
+ img (PIL Image or Tensor): image to be rotated.
1065
+ angle (number): rotation angle value in degrees, counter-clockwise.
1066
+ interpolation (InterpolationMode): Desired interpolation enum defined by
1067
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
1068
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
1069
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1070
+ expand (bool, optional): Optional expansion flag.
1071
+ If true, expands the output image to make it large enough to hold the entire rotated image.
1072
+ If false or omitted, make the output image the same size as the input image.
1073
+ Note that the expand flag assumes rotation around the center and no translation.
1074
+ center (sequence, optional): Optional center of rotation. Origin is the upper left corner.
1075
+ Default is the center of the image.
1076
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
1077
+ image. If given a number, the value is used for all bands respectively.
1078
+
1079
+ .. note::
1080
+ In torchscript mode single int/float value is not supported, please use a sequence
1081
+ of length 1: ``[value, ]``.
1082
+ Returns:
1083
+ PIL Image or Tensor: Rotated image.
1084
+
1085
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
1086
+
1087
+ """
1088
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1089
+ _log_api_usage_once(rotate)
1090
+
1091
+ if isinstance(interpolation, int):
1092
+ interpolation = _interpolation_modes_from_int(interpolation)
1093
+ elif not isinstance(interpolation, InterpolationMode):
1094
+ raise TypeError(
1095
+ "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
1096
+ )
1097
+
1098
+ if not isinstance(angle, (int, float)):
1099
+ raise TypeError("Argument angle should be int or float")
1100
+
1101
+ if center is not None and not isinstance(center, (list, tuple)):
1102
+ raise TypeError("Argument center should be a sequence")
1103
+
1104
+ if not isinstance(img, torch.Tensor):
1105
+ pil_interpolation = pil_modes_mapping[interpolation]
1106
+ return F_pil.rotate(img, angle=angle, interpolation=pil_interpolation, expand=expand, center=center, fill=fill)
1107
+
1108
+ center_f = [0.0, 0.0]
1109
+ if center is not None:
1110
+ _, height, width = get_dimensions(img)
1111
+ # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center.
1112
+ center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])]
1113
+
1114
+ # due to current incoherence of rotation angle direction between affine and rotate implementations
1115
+ # we need to set -angle.
1116
+ matrix = _get_inverse_affine_matrix(center_f, -angle, [0.0, 0.0], 1.0, [0.0, 0.0])
1117
+ return F_t.rotate(img, matrix=matrix, interpolation=interpolation.value, expand=expand, fill=fill)
1118
+
1119
+
1120
+ def affine(
1121
+ img: Tensor,
1122
+ angle: float,
1123
+ translate: List[int],
1124
+ scale: float,
1125
+ shear: List[float],
1126
+ interpolation: InterpolationMode = InterpolationMode.NEAREST,
1127
+ fill: Optional[List[float]] = None,
1128
+ center: Optional[List[int]] = None,
1129
+ ) -> Tensor:
1130
+ """Apply affine transformation on the image keeping image center invariant.
1131
+ If the image is torch Tensor, it is expected
1132
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
1133
+
1134
+ Args:
1135
+ img (PIL Image or Tensor): image to transform.
1136
+ angle (number): rotation angle in degrees between -180 and 180, clockwise direction.
1137
+ translate (sequence of integers): horizontal and vertical translations (post-rotation translation)
1138
+ scale (float): overall scale
1139
+ shear (float or sequence): shear angle value in degrees between -180 to 180, clockwise direction.
1140
+ If a sequence is specified, the first value corresponds to a shear parallel to the x-axis, while
1141
+ the second value corresponds to a shear parallel to the y-axis.
1142
+ interpolation (InterpolationMode): Desired interpolation enum defined by
1143
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
1144
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
1145
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1146
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
1147
+ image. If given a number, the value is used for all bands respectively.
1148
+
1149
+ .. note::
1150
+ In torchscript mode single int/float value is not supported, please use a sequence
1151
+ of length 1: ``[value, ]``.
1152
+ center (sequence, optional): Optional center of rotation. Origin is the upper left corner.
1153
+ Default is the center of the image.
1154
+
1155
+ Returns:
1156
+ PIL Image or Tensor: Transformed image.
1157
+ """
1158
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1159
+ _log_api_usage_once(affine)
1160
+
1161
+ if isinstance(interpolation, int):
1162
+ interpolation = _interpolation_modes_from_int(interpolation)
1163
+ elif not isinstance(interpolation, InterpolationMode):
1164
+ raise TypeError(
1165
+ "Argument interpolation should be a InterpolationMode or a corresponding Pillow integer constant"
1166
+ )
1167
+
1168
+ if not isinstance(angle, (int, float)):
1169
+ raise TypeError("Argument angle should be int or float")
1170
+
1171
+ if not isinstance(translate, (list, tuple)):
1172
+ raise TypeError("Argument translate should be a sequence")
1173
+
1174
+ if len(translate) != 2:
1175
+ raise ValueError("Argument translate should be a sequence of length 2")
1176
+
1177
+ if scale <= 0.0:
1178
+ raise ValueError("Argument scale should be positive")
1179
+
1180
+ if not isinstance(shear, (numbers.Number, (list, tuple))):
1181
+ raise TypeError("Shear should be either a single value or a sequence of two values")
1182
+
1183
+ if isinstance(angle, int):
1184
+ angle = float(angle)
1185
+
1186
+ if isinstance(translate, tuple):
1187
+ translate = list(translate)
1188
+
1189
+ if isinstance(shear, numbers.Number):
1190
+ shear = [shear, 0.0]
1191
+
1192
+ if isinstance(shear, tuple):
1193
+ shear = list(shear)
1194
+
1195
+ if len(shear) == 1:
1196
+ shear = [shear[0], shear[0]]
1197
+
1198
+ if len(shear) != 2:
1199
+ raise ValueError(f"Shear should be a sequence containing two values. Got {shear}")
1200
+
1201
+ if center is not None and not isinstance(center, (list, tuple)):
1202
+ raise TypeError("Argument center should be a sequence")
1203
+
1204
+ _, height, width = get_dimensions(img)
1205
+ if not isinstance(img, torch.Tensor):
1206
+ # center = (width * 0.5 + 0.5, height * 0.5 + 0.5)
1207
+ # it is visually better to estimate the center without 0.5 offset
1208
+ # otherwise image rotated by 90 degrees is shifted vs output image of torch.rot90 or F_t.affine
1209
+ if center is None:
1210
+ center = [width * 0.5, height * 0.5]
1211
+ matrix = _get_inverse_affine_matrix(center, angle, translate, scale, shear)
1212
+ pil_interpolation = pil_modes_mapping[interpolation]
1213
+ return F_pil.affine(img, matrix=matrix, interpolation=pil_interpolation, fill=fill)
1214
+
1215
+ center_f = [0.0, 0.0]
1216
+ if center is not None:
1217
+ _, height, width = get_dimensions(img)
1218
+ # Center values should be in pixel coordinates but translated such that (0, 0) corresponds to image center.
1219
+ center_f = [1.0 * (c - s * 0.5) for c, s in zip(center, [width, height])]
1220
+
1221
+ translate_f = [1.0 * t for t in translate]
1222
+ matrix = _get_inverse_affine_matrix(center_f, angle, translate_f, scale, shear)
1223
+ return F_t.affine(img, matrix=matrix, interpolation=interpolation.value, fill=fill)
1224
+
1225
+
1226
+ # Looks like to_grayscale() is a stand-alone functional that is never called
1227
+ # from the transform classes. Perhaps it's still here for BC? I can't be
1228
+ # bothered to dig.
1229
+ @torch.jit.unused
1230
+ def to_grayscale(img, num_output_channels=1):
1231
+ """Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image.
1232
+ This transform does not support torch Tensor.
1233
+
1234
+ Args:
1235
+ img (PIL Image): PIL Image to be converted to grayscale.
1236
+ num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default is 1.
1237
+
1238
+ Returns:
1239
+ PIL Image: Grayscale version of the image.
1240
+
1241
+ - if num_output_channels = 1 : returned image is single channel
1242
+ - if num_output_channels = 3 : returned image is 3 channel with r = g = b
1243
+ """
1244
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1245
+ _log_api_usage_once(to_grayscale)
1246
+ if isinstance(img, Image.Image):
1247
+ return F_pil.to_grayscale(img, num_output_channels)
1248
+
1249
+ raise TypeError("Input should be PIL Image")
1250
+
1251
+
1252
+ def rgb_to_grayscale(img: Tensor, num_output_channels: int = 1) -> Tensor:
1253
+ """Convert RGB image to grayscale version of image.
1254
+ If the image is torch Tensor, it is expected
1255
+ to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions
1256
+
1257
+ Note:
1258
+ Please, note that this method supports only RGB images as input. For inputs in other color spaces,
1259
+ please, consider using :meth:`~torchvision.transforms.functional.to_grayscale` with PIL Image.
1260
+
1261
+ Args:
1262
+ img (PIL Image or Tensor): RGB Image to be converted to grayscale.
1263
+ num_output_channels (int): number of channels of the output image. Value can be 1 or 3. Default, 1.
1264
+
1265
+ Returns:
1266
+ PIL Image or Tensor: Grayscale version of the image.
1267
+
1268
+ - if num_output_channels = 1 : returned image is single channel
1269
+ - if num_output_channels = 3 : returned image is 3 channel with r = g = b
1270
+ """
1271
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1272
+ _log_api_usage_once(rgb_to_grayscale)
1273
+ if not isinstance(img, torch.Tensor):
1274
+ return F_pil.to_grayscale(img, num_output_channels)
1275
+
1276
+ return F_t.rgb_to_grayscale(img, num_output_channels)
1277
+
1278
+
1279
+ def erase(img: Tensor, i: int, j: int, h: int, w: int, v: Tensor, inplace: bool = False) -> Tensor:
1280
+ """Erase the input Tensor Image with given value.
1281
+ This transform does not support PIL Image.
1282
+
1283
+ Args:
1284
+ img (Tensor Image): Tensor image of size (C, H, W) to be erased
1285
+ i (int): i in (i,j) i.e coordinates of the upper left corner.
1286
+ j (int): j in (i,j) i.e coordinates of the upper left corner.
1287
+ h (int): Height of the erased region.
1288
+ w (int): Width of the erased region.
1289
+ v: Erasing value.
1290
+ inplace(bool, optional): For in-place operations. By default, is set False.
1291
+
1292
+ Returns:
1293
+ Tensor Image: Erased image.
1294
+ """
1295
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1296
+ _log_api_usage_once(erase)
1297
+ if not isinstance(img, torch.Tensor):
1298
+ raise TypeError(f"img should be Tensor Image. Got {type(img)}")
1299
+
1300
+ return F_t.erase(img, i, j, h, w, v, inplace=inplace)
1301
+
1302
+
1303
+ def gaussian_blur(img: Tensor, kernel_size: List[int], sigma: Optional[List[float]] = None) -> Tensor:
1304
+ """Performs Gaussian blurring on the image by given kernel.
1305
+ If the image is torch Tensor, it is expected
1306
+ to have [..., H, W] shape, where ... means at most one leading dimension.
1307
+
1308
+ Args:
1309
+ img (PIL Image or Tensor): Image to be blurred
1310
+ kernel_size (sequence of ints or int): Gaussian kernel size. Can be a sequence of integers
1311
+ like ``(kx, ky)`` or a single integer for square kernels.
1312
+
1313
+ .. note::
1314
+ In torchscript mode kernel_size as single int is not supported, use a sequence of
1315
+ length 1: ``[ksize, ]``.
1316
+ sigma (sequence of floats or float, optional): Gaussian kernel standard deviation. Can be a
1317
+ sequence of floats like ``(sigma_x, sigma_y)`` or a single float to define the
1318
+ same sigma in both X/Y directions. If None, then it is computed using
1319
+ ``kernel_size`` as ``sigma = 0.3 * ((kernel_size - 1) * 0.5 - 1) + 0.8``.
1320
+ Default, None.
1321
+
1322
+ .. note::
1323
+ In torchscript mode sigma as single float is
1324
+ not supported, use a sequence of length 1: ``[sigma, ]``.
1325
+
1326
+ Returns:
1327
+ PIL Image or Tensor: Gaussian Blurred version of the image.
1328
+ """
1329
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1330
+ _log_api_usage_once(gaussian_blur)
1331
+ if not isinstance(kernel_size, (int, list, tuple)):
1332
+ raise TypeError(f"kernel_size should be int or a sequence of integers. Got {type(kernel_size)}")
1333
+ if isinstance(kernel_size, int):
1334
+ kernel_size = [kernel_size, kernel_size]
1335
+ if len(kernel_size) != 2:
1336
+ raise ValueError(f"If kernel_size is a sequence its length should be 2. Got {len(kernel_size)}")
1337
+ for ksize in kernel_size:
1338
+ if ksize % 2 == 0 or ksize < 0:
1339
+ raise ValueError(f"kernel_size should have odd and positive integers. Got {kernel_size}")
1340
+
1341
+ if sigma is None:
1342
+ sigma = [ksize * 0.15 + 0.35 for ksize in kernel_size]
1343
+
1344
+ if sigma is not None and not isinstance(sigma, (int, float, list, tuple)):
1345
+ raise TypeError(f"sigma should be either float or sequence of floats. Got {type(sigma)}")
1346
+ if isinstance(sigma, (int, float)):
1347
+ sigma = [float(sigma), float(sigma)]
1348
+ if isinstance(sigma, (list, tuple)) and len(sigma) == 1:
1349
+ sigma = [sigma[0], sigma[0]]
1350
+ if len(sigma) != 2:
1351
+ raise ValueError(f"If sigma is a sequence, its length should be 2. Got {len(sigma)}")
1352
+ for s in sigma:
1353
+ if s <= 0.0:
1354
+ raise ValueError(f"sigma should have positive values. Got {sigma}")
1355
+
1356
+ t_img = img
1357
+ if not isinstance(img, torch.Tensor):
1358
+ if not F_pil._is_pil_image(img):
1359
+ raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}")
1360
+
1361
+ t_img = pil_to_tensor(img)
1362
+
1363
+ output = F_t.gaussian_blur(t_img, kernel_size, sigma)
1364
+
1365
+ if not isinstance(img, torch.Tensor):
1366
+ output = to_pil_image(output, mode=img.mode)
1367
+ return output
1368
+
1369
+
1370
+ def invert(img: Tensor) -> Tensor:
1371
+ """Invert the colors of an RGB/grayscale image.
1372
+
1373
+ Args:
1374
+ img (PIL Image or Tensor): Image to have its colors inverted.
1375
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1376
+ where ... means it can have an arbitrary number of leading dimensions.
1377
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1378
+
1379
+ Returns:
1380
+ PIL Image or Tensor: Color inverted image.
1381
+ """
1382
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1383
+ _log_api_usage_once(invert)
1384
+ if not isinstance(img, torch.Tensor):
1385
+ return F_pil.invert(img)
1386
+
1387
+ return F_t.invert(img)
1388
+
1389
+
1390
+ def posterize(img: Tensor, bits: int) -> Tensor:
1391
+ """Posterize an image by reducing the number of bits for each color channel.
1392
+
1393
+ Args:
1394
+ img (PIL Image or Tensor): Image to have its colors posterized.
1395
+ If img is torch Tensor, it should be of type torch.uint8, and
1396
+ it is expected to be in [..., 1 or 3, H, W] format, where ... means
1397
+ it can have an arbitrary number of leading dimensions.
1398
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1399
+ bits (int): The number of bits to keep for each channel (0-8).
1400
+ Returns:
1401
+ PIL Image or Tensor: Posterized image.
1402
+ """
1403
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1404
+ _log_api_usage_once(posterize)
1405
+ if not (0 <= bits <= 8):
1406
+ raise ValueError(f"The number if bits should be between 0 and 8. Got {bits}")
1407
+
1408
+ if not isinstance(img, torch.Tensor):
1409
+ return F_pil.posterize(img, bits)
1410
+
1411
+ return F_t.posterize(img, bits)
1412
+
1413
+
1414
+ def solarize(img: Tensor, threshold: float) -> Tensor:
1415
+ """Solarize an RGB/grayscale image by inverting all pixel values above a threshold.
1416
+
1417
+ Args:
1418
+ img (PIL Image or Tensor): Image to have its colors inverted.
1419
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1420
+ where ... means it can have an arbitrary number of leading dimensions.
1421
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1422
+ threshold (float): All pixels equal or above this value are inverted.
1423
+ Returns:
1424
+ PIL Image or Tensor: Solarized image.
1425
+ """
1426
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1427
+ _log_api_usage_once(solarize)
1428
+ if not isinstance(img, torch.Tensor):
1429
+ return F_pil.solarize(img, threshold)
1430
+
1431
+ return F_t.solarize(img, threshold)
1432
+
1433
+
1434
+ def adjust_sharpness(img: Tensor, sharpness_factor: float) -> Tensor:
1435
+ """Adjust the sharpness of an image.
1436
+
1437
+ Args:
1438
+ img (PIL Image or Tensor): Image to be adjusted.
1439
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1440
+ where ... means it can have an arbitrary number of leading dimensions.
1441
+ sharpness_factor (float): How much to adjust the sharpness. Can be
1442
+ any non-negative number. 0 gives a blurred image, 1 gives the
1443
+ original image while 2 increases the sharpness by a factor of 2.
1444
+
1445
+ Returns:
1446
+ PIL Image or Tensor: Sharpness adjusted image.
1447
+ """
1448
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1449
+ _log_api_usage_once(adjust_sharpness)
1450
+ if not isinstance(img, torch.Tensor):
1451
+ return F_pil.adjust_sharpness(img, sharpness_factor)
1452
+
1453
+ return F_t.adjust_sharpness(img, sharpness_factor)
1454
+
1455
+
1456
+ def autocontrast(img: Tensor) -> Tensor:
1457
+ """Maximize contrast of an image by remapping its
1458
+ pixels per channel so that the lowest becomes black and the lightest
1459
+ becomes white.
1460
+
1461
+ Args:
1462
+ img (PIL Image or Tensor): Image on which autocontrast is applied.
1463
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1464
+ where ... means it can have an arbitrary number of leading dimensions.
1465
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1466
+
1467
+ Returns:
1468
+ PIL Image or Tensor: An image that was autocontrasted.
1469
+ """
1470
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1471
+ _log_api_usage_once(autocontrast)
1472
+ if not isinstance(img, torch.Tensor):
1473
+ return F_pil.autocontrast(img)
1474
+
1475
+ return F_t.autocontrast(img)
1476
+
1477
+
1478
+ def equalize(img: Tensor) -> Tensor:
1479
+ """Equalize the histogram of an image by applying
1480
+ a non-linear mapping to the input in order to create a uniform
1481
+ distribution of grayscale values in the output.
1482
+
1483
+ Args:
1484
+ img (PIL Image or Tensor): Image on which equalize is applied.
1485
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1486
+ where ... means it can have an arbitrary number of leading dimensions.
1487
+ The tensor dtype must be ``torch.uint8`` and values are expected to be in ``[0, 255]``.
1488
+ If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
1489
+
1490
+ Returns:
1491
+ PIL Image or Tensor: An image that was equalized.
1492
+ """
1493
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1494
+ _log_api_usage_once(equalize)
1495
+ if not isinstance(img, torch.Tensor):
1496
+ return F_pil.equalize(img)
1497
+
1498
+ return F_t.equalize(img)
1499
+
1500
+
1501
+ def elastic_transform(
1502
+ img: Tensor,
1503
+ displacement: Tensor,
1504
+ interpolation: InterpolationMode = InterpolationMode.BILINEAR,
1505
+ fill: Optional[List[float]] = None,
1506
+ ) -> Tensor:
1507
+ """Transform a tensor image with elastic transformations.
1508
+ Given alpha and sigma, it will generate displacement
1509
+ vectors for all pixels based on random offsets. Alpha controls the strength
1510
+ and sigma controls the smoothness of the displacements.
1511
+ The displacements are added to an identity grid and the resulting grid is
1512
+ used to grid_sample from the image.
1513
+
1514
+ Applications:
1515
+ Randomly transforms the morphology of objects in images and produces a
1516
+ see-through-water-like effect.
1517
+
1518
+ Args:
1519
+ img (PIL Image or Tensor): Image on which elastic_transform is applied.
1520
+ If img is torch Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1521
+ where ... means it can have an arbitrary number of leading dimensions.
1522
+ If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
1523
+ displacement (Tensor): The displacement field. Expected shape is [1, H, W, 2].
1524
+ interpolation (InterpolationMode): Desired interpolation enum defined by
1525
+ :class:`torchvision.transforms.InterpolationMode`.
1526
+ Default is ``InterpolationMode.BILINEAR``.
1527
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1528
+ fill (number or str or tuple): Pixel fill value for constant fill. Default is 0.
1529
+ If a tuple of length 3, it is used to fill R, G, B channels respectively.
1530
+ This value is only used when the padding_mode is constant.
1531
+ """
1532
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
1533
+ _log_api_usage_once(elastic_transform)
1534
+ # Backward compatibility with integer value
1535
+ if isinstance(interpolation, int):
1536
+ warnings.warn(
1537
+ "Argument interpolation should be of type InterpolationMode instead of int. "
1538
+ "Please, use InterpolationMode enum."
1539
+ )
1540
+ interpolation = _interpolation_modes_from_int(interpolation)
1541
+
1542
+ if not isinstance(displacement, torch.Tensor):
1543
+ raise TypeError("Argument displacement should be a Tensor")
1544
+
1545
+ t_img = img
1546
+ if not isinstance(img, torch.Tensor):
1547
+ if not F_pil._is_pil_image(img):
1548
+ raise TypeError(f"img should be PIL Image or Tensor. Got {type(img)}")
1549
+ t_img = pil_to_tensor(img)
1550
+
1551
+ shape = t_img.shape
1552
+ shape = (1,) + shape[-2:] + (2,)
1553
+ if shape != displacement.shape:
1554
+ raise ValueError(f"Argument displacement shape should be {shape}, but given {displacement.shape}")
1555
+
1556
+ # TODO: if image shape is [N1, N2, ..., C, H, W] and
1557
+ # displacement is [1, H, W, 2] we need to reshape input image
1558
+ # such grid_sampler takes internal code for 4D input
1559
+
1560
+ output = F_t.elastic_transform(
1561
+ t_img,
1562
+ displacement,
1563
+ interpolation=interpolation.value,
1564
+ fill=fill,
1565
+ )
1566
+
1567
+ if not isinstance(img, torch.Tensor):
1568
+ output = to_pil_image(output, mode=img.mode)
1569
+ return output
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/transforms.py ADDED
@@ -0,0 +1,2153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ import random
4
+ import warnings
5
+ from collections.abc import Sequence
6
+ from typing import List, Optional, Tuple, Union
7
+
8
+ import torch
9
+ from torch import Tensor
10
+
11
+ try:
12
+ import accimage
13
+ except ImportError:
14
+ accimage = None
15
+
16
+ from ..utils import _log_api_usage_once
17
+ from . import functional as F
18
+ from .functional import _interpolation_modes_from_int, InterpolationMode
19
+
20
+ __all__ = [
21
+ "Compose",
22
+ "ToTensor",
23
+ "PILToTensor",
24
+ "ConvertImageDtype",
25
+ "ToPILImage",
26
+ "Normalize",
27
+ "Resize",
28
+ "CenterCrop",
29
+ "Pad",
30
+ "Lambda",
31
+ "RandomApply",
32
+ "RandomChoice",
33
+ "RandomOrder",
34
+ "RandomCrop",
35
+ "RandomHorizontalFlip",
36
+ "RandomVerticalFlip",
37
+ "RandomResizedCrop",
38
+ "FiveCrop",
39
+ "TenCrop",
40
+ "LinearTransformation",
41
+ "ColorJitter",
42
+ "RandomRotation",
43
+ "RandomAffine",
44
+ "Grayscale",
45
+ "RandomGrayscale",
46
+ "RandomPerspective",
47
+ "RandomErasing",
48
+ "GaussianBlur",
49
+ "InterpolationMode",
50
+ "RandomInvert",
51
+ "RandomPosterize",
52
+ "RandomSolarize",
53
+ "RandomAdjustSharpness",
54
+ "RandomAutocontrast",
55
+ "RandomEqualize",
56
+ "ElasticTransform",
57
+ ]
58
+
59
+
60
+ class Compose:
61
+ """Composes several transforms together. This transform does not support torchscript.
62
+ Please, see the note below.
63
+
64
+ Args:
65
+ transforms (list of ``Transform`` objects): list of transforms to compose.
66
+
67
+ Example:
68
+ >>> transforms.Compose([
69
+ >>> transforms.CenterCrop(10),
70
+ >>> transforms.PILToTensor(),
71
+ >>> transforms.ConvertImageDtype(torch.float),
72
+ >>> ])
73
+
74
+ .. note::
75
+ In order to script the transformations, please use ``torch.nn.Sequential`` as below.
76
+
77
+ >>> transforms = torch.nn.Sequential(
78
+ >>> transforms.CenterCrop(10),
79
+ >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
80
+ >>> )
81
+ >>> scripted_transforms = torch.jit.script(transforms)
82
+
83
+ Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
84
+ `lambda` functions or ``PIL.Image``.
85
+
86
+ """
87
+
88
+ def __init__(self, transforms):
89
+ if not torch.jit.is_scripting() and not torch.jit.is_tracing():
90
+ _log_api_usage_once(self)
91
+ self.transforms = transforms
92
+
93
+ def __call__(self, img):
94
+ for t in self.transforms:
95
+ img = t(img)
96
+ return img
97
+
98
+ def __repr__(self) -> str:
99
+ format_string = self.__class__.__name__ + "("
100
+ for t in self.transforms:
101
+ format_string += "\n"
102
+ format_string += f" {t}"
103
+ format_string += "\n)"
104
+ return format_string
105
+
106
+
107
+ class ToTensor:
108
+ """Convert a PIL Image or ndarray to tensor and scale the values accordingly.
109
+
110
+ This transform does not support torchscript.
111
+
112
+ Converts a PIL Image or numpy.ndarray (H x W x C) in the range
113
+ [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
114
+ if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)
115
+ or if the numpy.ndarray has dtype = np.uint8
116
+
117
+ In the other cases, tensors are returned without scaling.
118
+
119
+ .. note::
120
+ Because the input image is scaled to [0.0, 1.0], this transformation should not be used when
121
+ transforming target image masks. See the `references`_ for implementing the transforms for image masks.
122
+
123
+ .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation
124
+ """
125
+
126
+ def __init__(self) -> None:
127
+ _log_api_usage_once(self)
128
+
129
+ def __call__(self, pic):
130
+ """
131
+ Args:
132
+ pic (PIL Image or numpy.ndarray): Image to be converted to tensor.
133
+
134
+ Returns:
135
+ Tensor: Converted image.
136
+ """
137
+ return F.to_tensor(pic)
138
+
139
+ def __repr__(self) -> str:
140
+ return f"{self.__class__.__name__}()"
141
+
142
+
143
+ class PILToTensor:
144
+ """Convert a PIL Image to a tensor of the same type - this does not scale values.
145
+
146
+ This transform does not support torchscript.
147
+
148
+ Converts a PIL Image (H x W x C) to a Tensor of shape (C x H x W).
149
+ """
150
+
151
+ def __init__(self) -> None:
152
+ _log_api_usage_once(self)
153
+
154
+ def __call__(self, pic):
155
+ """
156
+ .. note::
157
+
158
+ A deep copy of the underlying array is performed.
159
+
160
+ Args:
161
+ pic (PIL Image): Image to be converted to tensor.
162
+
163
+ Returns:
164
+ Tensor: Converted image.
165
+ """
166
+ return F.pil_to_tensor(pic)
167
+
168
+ def __repr__(self) -> str:
169
+ return f"{self.__class__.__name__}()"
170
+
171
+
172
+ class ConvertImageDtype(torch.nn.Module):
173
+ """Convert a tensor image to the given ``dtype`` and scale the values accordingly.
174
+
175
+ This function does not support PIL Image.
176
+
177
+ Args:
178
+ dtype (torch.dtype): Desired data type of the output
179
+
180
+ .. note::
181
+
182
+ When converting from a smaller to a larger integer ``dtype`` the maximum values are **not** mapped exactly.
183
+ If converted back and forth, this mismatch has no effect.
184
+
185
+ Raises:
186
+ RuntimeError: When trying to cast :class:`torch.float32` to :class:`torch.int32` or :class:`torch.int64` as
187
+ well as for trying to cast :class:`torch.float64` to :class:`torch.int64`. These conversions might lead to
188
+ overflow errors since the floating point ``dtype`` cannot store consecutive integers over the whole range
189
+ of the integer ``dtype``.
190
+ """
191
+
192
+ def __init__(self, dtype: torch.dtype) -> None:
193
+ super().__init__()
194
+ _log_api_usage_once(self)
195
+ self.dtype = dtype
196
+
197
+ def forward(self, image):
198
+ return F.convert_image_dtype(image, self.dtype)
199
+
200
+
201
+ class ToPILImage:
202
+ """Convert a tensor or an ndarray to PIL Image
203
+
204
+ This transform does not support torchscript.
205
+
206
+ Converts a torch.*Tensor of shape C x H x W or a numpy ndarray of shape
207
+ H x W x C to a PIL Image while adjusting the value range depending on the ``mode``.
208
+
209
+ Args:
210
+ mode (`PIL.Image mode`_): color space and pixel depth of input data (optional).
211
+ If ``mode`` is ``None`` (default) there are some assumptions made about the input data:
212
+
213
+ - If the input has 4 channels, the ``mode`` is assumed to be ``RGBA``.
214
+ - If the input has 3 channels, the ``mode`` is assumed to be ``RGB``.
215
+ - If the input has 2 channels, the ``mode`` is assumed to be ``LA``.
216
+ - If the input has 1 channel, the ``mode`` is determined by the data type (i.e ``int``, ``float``, ``short``).
217
+
218
+ .. _PIL.Image mode: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#concept-modes
219
+ """
220
+
221
+ def __init__(self, mode=None):
222
+ _log_api_usage_once(self)
223
+ self.mode = mode
224
+
225
+ def __call__(self, pic):
226
+ """
227
+ Args:
228
+ pic (Tensor or numpy.ndarray): Image to be converted to PIL Image.
229
+
230
+ Returns:
231
+ PIL Image: Image converted to PIL Image.
232
+
233
+ """
234
+ return F.to_pil_image(pic, self.mode)
235
+
236
+ def __repr__(self) -> str:
237
+ format_string = self.__class__.__name__ + "("
238
+ if self.mode is not None:
239
+ format_string += f"mode={self.mode}"
240
+ format_string += ")"
241
+ return format_string
242
+
243
+
244
+ class Normalize(torch.nn.Module):
245
+ """Normalize a tensor image with mean and standard deviation.
246
+ This transform does not support PIL Image.
247
+ Given mean: ``(mean[1],...,mean[n])`` and std: ``(std[1],..,std[n])`` for ``n``
248
+ channels, this transform will normalize each channel of the input
249
+ ``torch.*Tensor`` i.e.,
250
+ ``output[channel] = (input[channel] - mean[channel]) / std[channel]``
251
+
252
+ .. note::
253
+ This transform acts out of place, i.e., it does not mutate the input tensor.
254
+
255
+ Args:
256
+ mean (sequence): Sequence of means for each channel.
257
+ std (sequence): Sequence of standard deviations for each channel.
258
+ inplace(bool,optional): Bool to make this operation in-place.
259
+
260
+ """
261
+
262
+ def __init__(self, mean, std, inplace=False):
263
+ super().__init__()
264
+ _log_api_usage_once(self)
265
+ self.mean = mean
266
+ self.std = std
267
+ self.inplace = inplace
268
+
269
+ def forward(self, tensor: Tensor) -> Tensor:
270
+ """
271
+ Args:
272
+ tensor (Tensor): Tensor image to be normalized.
273
+
274
+ Returns:
275
+ Tensor: Normalized Tensor image.
276
+ """
277
+ return F.normalize(tensor, self.mean, self.std, self.inplace)
278
+
279
+ def __repr__(self) -> str:
280
+ return f"{self.__class__.__name__}(mean={self.mean}, std={self.std})"
281
+
282
+
283
+ class Resize(torch.nn.Module):
284
+ """Resize the input image to the given size.
285
+ If the image is torch Tensor, it is expected
286
+ to have [..., H, W] shape, where ... means a maximum of two leading dimensions
287
+
288
+ Args:
289
+ size (sequence or int): Desired output size. If size is a sequence like
290
+ (h, w), output size will be matched to this. If size is an int,
291
+ smaller edge of the image will be matched to this number.
292
+ i.e, if height > width, then image will be rescaled to
293
+ (size * height / width, size).
294
+
295
+ .. note::
296
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
297
+ interpolation (InterpolationMode): Desired interpolation enum defined by
298
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
299
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
300
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
301
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
302
+ max_size (int, optional): The maximum allowed for the longer edge of
303
+ the resized image. If the longer edge of the image is greater
304
+ than ``max_size`` after being resized according to ``size``,
305
+ ``size`` will be overruled so that the longer edge is equal to
306
+ ``max_size``.
307
+ As a result, the smaller edge may be shorter than ``size``. This
308
+ is only supported if ``size`` is an int (or a sequence of length
309
+ 1 in torchscript mode).
310
+ antialias (bool, optional): Whether to apply antialiasing.
311
+ It only affects **tensors** with bilinear or bicubic modes and it is
312
+ ignored otherwise: on PIL images, antialiasing is always applied on
313
+ bilinear or bicubic modes; on other modes (for PIL images and
314
+ tensors), antialiasing makes no sense and this parameter is ignored.
315
+ Possible values are:
316
+
317
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
318
+ Other mode aren't affected. This is probably what you want to use.
319
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
320
+ images are still antialiased on bilinear or bicubic modes, because
321
+ PIL doesn't support no antialias.
322
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
323
+ PIL images. This value exists for legacy reasons and you probably
324
+ don't want to use it unless you really know what you are doing.
325
+
326
+ The default value changed from ``None`` to ``True`` in
327
+ v0.17, for the PIL and Tensor backends to be consistent.
328
+ """
329
+
330
+ def __init__(self, size, interpolation=InterpolationMode.BILINEAR, max_size=None, antialias=True):
331
+ super().__init__()
332
+ _log_api_usage_once(self)
333
+ if not isinstance(size, (int, Sequence)):
334
+ raise TypeError(f"Size should be int or sequence. Got {type(size)}")
335
+ if isinstance(size, Sequence) and len(size) not in (1, 2):
336
+ raise ValueError("If size is a sequence, it should have 1 or 2 values")
337
+ self.size = size
338
+ self.max_size = max_size
339
+
340
+ if isinstance(interpolation, int):
341
+ interpolation = _interpolation_modes_from_int(interpolation)
342
+
343
+ self.interpolation = interpolation
344
+ self.antialias = antialias
345
+
346
+ def forward(self, img):
347
+ """
348
+ Args:
349
+ img (PIL Image or Tensor): Image to be scaled.
350
+
351
+ Returns:
352
+ PIL Image or Tensor: Rescaled image.
353
+ """
354
+ return F.resize(img, self.size, self.interpolation, self.max_size, self.antialias)
355
+
356
+ def __repr__(self) -> str:
357
+ detail = f"(size={self.size}, interpolation={self.interpolation.value}, max_size={self.max_size}, antialias={self.antialias})"
358
+ return f"{self.__class__.__name__}{detail}"
359
+
360
+
361
+ class CenterCrop(torch.nn.Module):
362
+ """Crops the given image at the center.
363
+ If the image is torch Tensor, it is expected
364
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
365
+ If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
366
+
367
+ Args:
368
+ size (sequence or int): Desired output size of the crop. If size is an
369
+ int instead of sequence like (h, w), a square crop (size, size) is
370
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
371
+ """
372
+
373
+ def __init__(self, size):
374
+ super().__init__()
375
+ _log_api_usage_once(self)
376
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
377
+
378
+ def forward(self, img):
379
+ """
380
+ Args:
381
+ img (PIL Image or Tensor): Image to be cropped.
382
+
383
+ Returns:
384
+ PIL Image or Tensor: Cropped image.
385
+ """
386
+ return F.center_crop(img, self.size)
387
+
388
+ def __repr__(self) -> str:
389
+ return f"{self.__class__.__name__}(size={self.size})"
390
+
391
+
392
+ class Pad(torch.nn.Module):
393
+ """Pad the given image on all sides with the given "pad" value.
394
+ If the image is torch Tensor, it is expected
395
+ to have [..., H, W] shape, where ... means at most 2 leading dimensions for mode reflect and symmetric,
396
+ at most 3 leading dimensions for mode edge,
397
+ and an arbitrary number of leading dimensions for mode constant
398
+
399
+ Args:
400
+ padding (int or sequence): Padding on each border. If a single int is provided this
401
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
402
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
403
+ this is the padding for the left, top, right and bottom borders respectively.
404
+
405
+ .. note::
406
+ In torchscript mode padding as single int is not supported, use a sequence of
407
+ length 1: ``[padding, ]``.
408
+ fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
409
+ length 3, it is used to fill R, G, B channels respectively.
410
+ This value is only used when the padding_mode is constant.
411
+ Only number is supported for torch Tensor.
412
+ Only int or tuple value is supported for PIL Image.
413
+ padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
414
+ Default is constant.
415
+
416
+ - constant: pads with a constant value, this value is specified with fill
417
+
418
+ - edge: pads with the last value at the edge of the image.
419
+ If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2
420
+
421
+ - reflect: pads with reflection of image without repeating the last value on the edge.
422
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
423
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
424
+
425
+ - symmetric: pads with reflection of image repeating the last value on the edge.
426
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
427
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
428
+ """
429
+
430
+ def __init__(self, padding, fill=0, padding_mode="constant"):
431
+ super().__init__()
432
+ _log_api_usage_once(self)
433
+ if not isinstance(padding, (numbers.Number, tuple, list)):
434
+ raise TypeError("Got inappropriate padding arg")
435
+
436
+ if not isinstance(fill, (numbers.Number, tuple, list)):
437
+ raise TypeError("Got inappropriate fill arg")
438
+
439
+ if padding_mode not in ["constant", "edge", "reflect", "symmetric"]:
440
+ raise ValueError("Padding mode should be either constant, edge, reflect or symmetric")
441
+
442
+ if isinstance(padding, Sequence) and len(padding) not in [1, 2, 4]:
443
+ raise ValueError(
444
+ f"Padding must be an int or a 1, 2, or 4 element tuple, not a {len(padding)} element tuple"
445
+ )
446
+
447
+ self.padding = padding
448
+ self.fill = fill
449
+ self.padding_mode = padding_mode
450
+
451
+ def forward(self, img):
452
+ """
453
+ Args:
454
+ img (PIL Image or Tensor): Image to be padded.
455
+
456
+ Returns:
457
+ PIL Image or Tensor: Padded image.
458
+ """
459
+ return F.pad(img, self.padding, self.fill, self.padding_mode)
460
+
461
+ def __repr__(self) -> str:
462
+ return f"{self.__class__.__name__}(padding={self.padding}, fill={self.fill}, padding_mode={self.padding_mode})"
463
+
464
+
465
+ class Lambda:
466
+ """Apply a user-defined lambda as a transform. This transform does not support torchscript.
467
+
468
+ Args:
469
+ lambd (function): Lambda/function to be used for transform.
470
+ """
471
+
472
+ def __init__(self, lambd):
473
+ _log_api_usage_once(self)
474
+ if not callable(lambd):
475
+ raise TypeError(f"Argument lambd should be callable, got {repr(type(lambd).__name__)}")
476
+ self.lambd = lambd
477
+
478
+ def __call__(self, img):
479
+ return self.lambd(img)
480
+
481
+ def __repr__(self) -> str:
482
+ return f"{self.__class__.__name__}()"
483
+
484
+
485
+ class RandomTransforms:
486
+ """Base class for a list of transformations with randomness
487
+
488
+ Args:
489
+ transforms (sequence): list of transformations
490
+ """
491
+
492
+ def __init__(self, transforms):
493
+ _log_api_usage_once(self)
494
+ if not isinstance(transforms, Sequence):
495
+ raise TypeError("Argument transforms should be a sequence")
496
+ self.transforms = transforms
497
+
498
+ def __call__(self, *args, **kwargs):
499
+ raise NotImplementedError()
500
+
501
+ def __repr__(self) -> str:
502
+ format_string = self.__class__.__name__ + "("
503
+ for t in self.transforms:
504
+ format_string += "\n"
505
+ format_string += f" {t}"
506
+ format_string += "\n)"
507
+ return format_string
508
+
509
+
510
+ class RandomApply(torch.nn.Module):
511
+ """Apply randomly a list of transformations with a given probability.
512
+
513
+ .. note::
514
+ In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of
515
+ transforms as shown below:
516
+
517
+ >>> transforms = transforms.RandomApply(torch.nn.ModuleList([
518
+ >>> transforms.ColorJitter(),
519
+ >>> ]), p=0.3)
520
+ >>> scripted_transforms = torch.jit.script(transforms)
521
+
522
+ Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
523
+ `lambda` functions or ``PIL.Image``.
524
+
525
+ Args:
526
+ transforms (sequence or torch.nn.Module): list of transformations
527
+ p (float): probability
528
+ """
529
+
530
+ def __init__(self, transforms, p=0.5):
531
+ super().__init__()
532
+ _log_api_usage_once(self)
533
+ self.transforms = transforms
534
+ self.p = p
535
+
536
+ def forward(self, img):
537
+ if self.p < torch.rand(1):
538
+ return img
539
+ for t in self.transforms:
540
+ img = t(img)
541
+ return img
542
+
543
+ def __repr__(self) -> str:
544
+ format_string = self.__class__.__name__ + "("
545
+ format_string += f"\n p={self.p}"
546
+ for t in self.transforms:
547
+ format_string += "\n"
548
+ format_string += f" {t}"
549
+ format_string += "\n)"
550
+ return format_string
551
+
552
+
553
+ class RandomOrder(RandomTransforms):
554
+ """Apply a list of transformations in a random order. This transform does not support torchscript."""
555
+
556
+ def __call__(self, img):
557
+ order = list(range(len(self.transforms)))
558
+ random.shuffle(order)
559
+ for i in order:
560
+ img = self.transforms[i](img)
561
+ return img
562
+
563
+
564
+ class RandomChoice(RandomTransforms):
565
+ """Apply single transformation randomly picked from a list. This transform does not support torchscript."""
566
+
567
+ def __init__(self, transforms, p=None):
568
+ super().__init__(transforms)
569
+ if p is not None and not isinstance(p, Sequence):
570
+ raise TypeError("Argument p should be a sequence")
571
+ self.p = p
572
+
573
+ def __call__(self, *args):
574
+ t = random.choices(self.transforms, weights=self.p)[0]
575
+ return t(*args)
576
+
577
+ def __repr__(self) -> str:
578
+ return f"{super().__repr__()}(p={self.p})"
579
+
580
+
581
+ class RandomCrop(torch.nn.Module):
582
+ """Crop the given image at a random location.
583
+ If the image is torch Tensor, it is expected
584
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions,
585
+ but if non-constant padding is used, the input is expected to have at most 2 leading dimensions
586
+
587
+ Args:
588
+ size (sequence or int): Desired output size of the crop. If size is an
589
+ int instead of sequence like (h, w), a square crop (size, size) is
590
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
591
+ padding (int or sequence, optional): Optional padding on each border
592
+ of the image. Default is None. If a single int is provided this
593
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
594
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
595
+ this is the padding for the left, top, right and bottom borders respectively.
596
+
597
+ .. note::
598
+ In torchscript mode padding as single int is not supported, use a sequence of
599
+ length 1: ``[padding, ]``.
600
+ pad_if_needed (boolean): It will pad the image if smaller than the
601
+ desired size to avoid raising an exception. Since cropping is done
602
+ after padding, the padding seems to be done at a random offset.
603
+ fill (number or tuple): Pixel fill value for constant fill. Default is 0. If a tuple of
604
+ length 3, it is used to fill R, G, B channels respectively.
605
+ This value is only used when the padding_mode is constant.
606
+ Only number is supported for torch Tensor.
607
+ Only int or tuple value is supported for PIL Image.
608
+ padding_mode (str): Type of padding. Should be: constant, edge, reflect or symmetric.
609
+ Default is constant.
610
+
611
+ - constant: pads with a constant value, this value is specified with fill
612
+
613
+ - edge: pads with the last value at the edge of the image.
614
+ If input a 5D torch Tensor, the last 3 dimensions will be padded instead of the last 2
615
+
616
+ - reflect: pads with reflection of image without repeating the last value on the edge.
617
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
618
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
619
+
620
+ - symmetric: pads with reflection of image repeating the last value on the edge.
621
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
622
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
623
+ """
624
+
625
+ @staticmethod
626
+ def get_params(img: Tensor, output_size: Tuple[int, int]) -> Tuple[int, int, int, int]:
627
+ """Get parameters for ``crop`` for a random crop.
628
+
629
+ Args:
630
+ img (PIL Image or Tensor): Image to be cropped.
631
+ output_size (tuple): Expected output size of the crop.
632
+
633
+ Returns:
634
+ tuple: params (i, j, h, w) to be passed to ``crop`` for random crop.
635
+ """
636
+ _, h, w = F.get_dimensions(img)
637
+ th, tw = output_size
638
+
639
+ if h < th or w < tw:
640
+ raise ValueError(f"Required crop size {(th, tw)} is larger than input image size {(h, w)}")
641
+
642
+ if w == tw and h == th:
643
+ return 0, 0, h, w
644
+
645
+ i = torch.randint(0, h - th + 1, size=(1,)).item()
646
+ j = torch.randint(0, w - tw + 1, size=(1,)).item()
647
+ return i, j, th, tw
648
+
649
+ def __init__(self, size, padding=None, pad_if_needed=False, fill=0, padding_mode="constant"):
650
+ super().__init__()
651
+ _log_api_usage_once(self)
652
+
653
+ self.size = tuple(_setup_size(size, error_msg="Please provide only two dimensions (h, w) for size."))
654
+
655
+ self.padding = padding
656
+ self.pad_if_needed = pad_if_needed
657
+ self.fill = fill
658
+ self.padding_mode = padding_mode
659
+
660
+ def forward(self, img):
661
+ """
662
+ Args:
663
+ img (PIL Image or Tensor): Image to be cropped.
664
+
665
+ Returns:
666
+ PIL Image or Tensor: Cropped image.
667
+ """
668
+ if self.padding is not None:
669
+ img = F.pad(img, self.padding, self.fill, self.padding_mode)
670
+
671
+ _, height, width = F.get_dimensions(img)
672
+ # pad the width if needed
673
+ if self.pad_if_needed and width < self.size[1]:
674
+ padding = [self.size[1] - width, 0]
675
+ img = F.pad(img, padding, self.fill, self.padding_mode)
676
+ # pad the height if needed
677
+ if self.pad_if_needed and height < self.size[0]:
678
+ padding = [0, self.size[0] - height]
679
+ img = F.pad(img, padding, self.fill, self.padding_mode)
680
+
681
+ i, j, h, w = self.get_params(img, self.size)
682
+
683
+ return F.crop(img, i, j, h, w)
684
+
685
+ def __repr__(self) -> str:
686
+ return f"{self.__class__.__name__}(size={self.size}, padding={self.padding})"
687
+
688
+
689
+ class RandomHorizontalFlip(torch.nn.Module):
690
+ """Horizontally flip the given image randomly with a given probability.
691
+ If the image is torch Tensor, it is expected
692
+ to have [..., H, W] shape, where ... means an arbitrary number of leading
693
+ dimensions
694
+
695
+ Args:
696
+ p (float): probability of the image being flipped. Default value is 0.5
697
+ """
698
+
699
+ def __init__(self, p=0.5):
700
+ super().__init__()
701
+ _log_api_usage_once(self)
702
+ self.p = p
703
+
704
+ def forward(self, img):
705
+ """
706
+ Args:
707
+ img (PIL Image or Tensor): Image to be flipped.
708
+
709
+ Returns:
710
+ PIL Image or Tensor: Randomly flipped image.
711
+ """
712
+ if torch.rand(1) < self.p:
713
+ return F.hflip(img)
714
+ return img
715
+
716
+ def __repr__(self) -> str:
717
+ return f"{self.__class__.__name__}(p={self.p})"
718
+
719
+
720
+ class RandomVerticalFlip(torch.nn.Module):
721
+ """Vertically flip the given image randomly with a given probability.
722
+ If the image is torch Tensor, it is expected
723
+ to have [..., H, W] shape, where ... means an arbitrary number of leading
724
+ dimensions
725
+
726
+ Args:
727
+ p (float): probability of the image being flipped. Default value is 0.5
728
+ """
729
+
730
+ def __init__(self, p=0.5):
731
+ super().__init__()
732
+ _log_api_usage_once(self)
733
+ self.p = p
734
+
735
+ def forward(self, img):
736
+ """
737
+ Args:
738
+ img (PIL Image or Tensor): Image to be flipped.
739
+
740
+ Returns:
741
+ PIL Image or Tensor: Randomly flipped image.
742
+ """
743
+ if torch.rand(1) < self.p:
744
+ return F.vflip(img)
745
+ return img
746
+
747
+ def __repr__(self) -> str:
748
+ return f"{self.__class__.__name__}(p={self.p})"
749
+
750
+
751
+ class RandomPerspective(torch.nn.Module):
752
+ """Performs a random perspective transformation of the given image with a given probability.
753
+ If the image is torch Tensor, it is expected
754
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
755
+
756
+ Args:
757
+ distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1.
758
+ Default is 0.5.
759
+ p (float): probability of the image being transformed. Default is 0.5.
760
+ interpolation (InterpolationMode): Desired interpolation enum defined by
761
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
762
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
763
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
764
+ fill (sequence or number): Pixel fill value for the area outside the transformed
765
+ image. Default is ``0``. If given a number, the value is used for all bands respectively.
766
+ """
767
+
768
+ def __init__(self, distortion_scale=0.5, p=0.5, interpolation=InterpolationMode.BILINEAR, fill=0):
769
+ super().__init__()
770
+ _log_api_usage_once(self)
771
+ self.p = p
772
+
773
+ if isinstance(interpolation, int):
774
+ interpolation = _interpolation_modes_from_int(interpolation)
775
+
776
+ self.interpolation = interpolation
777
+ self.distortion_scale = distortion_scale
778
+
779
+ if fill is None:
780
+ fill = 0
781
+ elif not isinstance(fill, (Sequence, numbers.Number)):
782
+ raise TypeError("Fill should be either a sequence or a number.")
783
+
784
+ self.fill = fill
785
+
786
+ def forward(self, img):
787
+ """
788
+ Args:
789
+ img (PIL Image or Tensor): Image to be Perspectively transformed.
790
+
791
+ Returns:
792
+ PIL Image or Tensor: Randomly transformed image.
793
+ """
794
+
795
+ fill = self.fill
796
+ channels, height, width = F.get_dimensions(img)
797
+ if isinstance(img, Tensor):
798
+ if isinstance(fill, (int, float)):
799
+ fill = [float(fill)] * channels
800
+ else:
801
+ fill = [float(f) for f in fill]
802
+
803
+ if torch.rand(1) < self.p:
804
+ startpoints, endpoints = self.get_params(width, height, self.distortion_scale)
805
+ return F.perspective(img, startpoints, endpoints, self.interpolation, fill)
806
+ return img
807
+
808
+ @staticmethod
809
+ def get_params(width: int, height: int, distortion_scale: float) -> Tuple[List[List[int]], List[List[int]]]:
810
+ """Get parameters for ``perspective`` for a random perspective transform.
811
+
812
+ Args:
813
+ width (int): width of the image.
814
+ height (int): height of the image.
815
+ distortion_scale (float): argument to control the degree of distortion and ranges from 0 to 1.
816
+
817
+ Returns:
818
+ List containing [top-left, top-right, bottom-right, bottom-left] of the original image,
819
+ List containing [top-left, top-right, bottom-right, bottom-left] of the transformed image.
820
+ """
821
+ half_height = height // 2
822
+ half_width = width // 2
823
+ topleft = [
824
+ int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()),
825
+ int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()),
826
+ ]
827
+ topright = [
828
+ int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()),
829
+ int(torch.randint(0, int(distortion_scale * half_height) + 1, size=(1,)).item()),
830
+ ]
831
+ botright = [
832
+ int(torch.randint(width - int(distortion_scale * half_width) - 1, width, size=(1,)).item()),
833
+ int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()),
834
+ ]
835
+ botleft = [
836
+ int(torch.randint(0, int(distortion_scale * half_width) + 1, size=(1,)).item()),
837
+ int(torch.randint(height - int(distortion_scale * half_height) - 1, height, size=(1,)).item()),
838
+ ]
839
+ startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]
840
+ endpoints = [topleft, topright, botright, botleft]
841
+ return startpoints, endpoints
842
+
843
+ def __repr__(self) -> str:
844
+ return f"{self.__class__.__name__}(p={self.p})"
845
+
846
+
847
+ class RandomResizedCrop(torch.nn.Module):
848
+ """Crop a random portion of image and resize it to a given size.
849
+
850
+ If the image is torch Tensor, it is expected
851
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions
852
+
853
+ A crop of the original image is made: the crop has a random area (H * W)
854
+ and a random aspect ratio. This crop is finally resized to the given
855
+ size. This is popularly used to train the Inception networks.
856
+
857
+ Args:
858
+ size (int or sequence): expected output size of the crop, for each edge. If size is an
859
+ int instead of sequence like (h, w), a square output size ``(size, size)`` is
860
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
861
+
862
+ .. note::
863
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
864
+ scale (tuple of float): Specifies the lower and upper bounds for the random area of the crop,
865
+ before resizing. The scale is defined with respect to the area of the original image.
866
+ ratio (tuple of float): lower and upper bounds for the random aspect ratio of the crop, before
867
+ resizing.
868
+ interpolation (InterpolationMode): Desired interpolation enum defined by
869
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
870
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
871
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
872
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
873
+ antialias (bool, optional): Whether to apply antialiasing.
874
+ It only affects **tensors** with bilinear or bicubic modes and it is
875
+ ignored otherwise: on PIL images, antialiasing is always applied on
876
+ bilinear or bicubic modes; on other modes (for PIL images and
877
+ tensors), antialiasing makes no sense and this parameter is ignored.
878
+ Possible values are:
879
+
880
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
881
+ Other mode aren't affected. This is probably what you want to use.
882
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
883
+ images are still antialiased on bilinear or bicubic modes, because
884
+ PIL doesn't support no antialias.
885
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
886
+ PIL images. This value exists for legacy reasons and you probably
887
+ don't want to use it unless you really know what you are doing.
888
+
889
+ The default value changed from ``None`` to ``True`` in
890
+ v0.17, for the PIL and Tensor backends to be consistent.
891
+ """
892
+
893
+ def __init__(
894
+ self,
895
+ size,
896
+ scale=(0.08, 1.0),
897
+ ratio=(3.0 / 4.0, 4.0 / 3.0),
898
+ interpolation=InterpolationMode.BILINEAR,
899
+ antialias: Optional[bool] = True,
900
+ ):
901
+ super().__init__()
902
+ _log_api_usage_once(self)
903
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
904
+
905
+ if not isinstance(scale, Sequence):
906
+ raise TypeError("Scale should be a sequence")
907
+ if not isinstance(ratio, Sequence):
908
+ raise TypeError("Ratio should be a sequence")
909
+ if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
910
+ warnings.warn("Scale and ratio should be of kind (min, max)")
911
+
912
+ if isinstance(interpolation, int):
913
+ interpolation = _interpolation_modes_from_int(interpolation)
914
+
915
+ self.interpolation = interpolation
916
+ self.antialias = antialias
917
+ self.scale = scale
918
+ self.ratio = ratio
919
+
920
+ @staticmethod
921
+ def get_params(img: Tensor, scale: List[float], ratio: List[float]) -> Tuple[int, int, int, int]:
922
+ """Get parameters for ``crop`` for a random sized crop.
923
+
924
+ Args:
925
+ img (PIL Image or Tensor): Input image.
926
+ scale (list): range of scale of the origin size cropped
927
+ ratio (list): range of aspect ratio of the origin aspect ratio cropped
928
+
929
+ Returns:
930
+ tuple: params (i, j, h, w) to be passed to ``crop`` for a random
931
+ sized crop.
932
+ """
933
+ _, height, width = F.get_dimensions(img)
934
+ area = height * width
935
+
936
+ log_ratio = torch.log(torch.tensor(ratio))
937
+ for _ in range(10):
938
+ target_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item()
939
+ aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item()
940
+
941
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
942
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
943
+
944
+ if 0 < w <= width and 0 < h <= height:
945
+ i = torch.randint(0, height - h + 1, size=(1,)).item()
946
+ j = torch.randint(0, width - w + 1, size=(1,)).item()
947
+ return i, j, h, w
948
+
949
+ # Fallback to central crop
950
+ in_ratio = float(width) / float(height)
951
+ if in_ratio < min(ratio):
952
+ w = width
953
+ h = int(round(w / min(ratio)))
954
+ elif in_ratio > max(ratio):
955
+ h = height
956
+ w = int(round(h * max(ratio)))
957
+ else: # whole image
958
+ w = width
959
+ h = height
960
+ i = (height - h) // 2
961
+ j = (width - w) // 2
962
+ return i, j, h, w
963
+
964
+ def forward(self, img):
965
+ """
966
+ Args:
967
+ img (PIL Image or Tensor): Image to be cropped and resized.
968
+
969
+ Returns:
970
+ PIL Image or Tensor: Randomly cropped and resized image.
971
+ """
972
+ i, j, h, w = self.get_params(img, self.scale, self.ratio)
973
+ return F.resized_crop(img, i, j, h, w, self.size, self.interpolation, antialias=self.antialias)
974
+
975
+ def __repr__(self) -> str:
976
+ interpolate_str = self.interpolation.value
977
+ format_string = self.__class__.__name__ + f"(size={self.size}"
978
+ format_string += f", scale={tuple(round(s, 4) for s in self.scale)}"
979
+ format_string += f", ratio={tuple(round(r, 4) for r in self.ratio)}"
980
+ format_string += f", interpolation={interpolate_str}"
981
+ format_string += f", antialias={self.antialias})"
982
+ return format_string
983
+
984
+
985
+ class FiveCrop(torch.nn.Module):
986
+ """Crop the given image into four corners and the central crop.
987
+ If the image is torch Tensor, it is expected
988
+ to have [..., H, W] shape, where ... means an arbitrary number of leading
989
+ dimensions
990
+
991
+ .. Note::
992
+ This transform returns a tuple of images and there may be a mismatch in the number of
993
+ inputs and targets your Dataset returns. See below for an example of how to deal with
994
+ this.
995
+
996
+ Args:
997
+ size (sequence or int): Desired output size of the crop. If size is an ``int``
998
+ instead of sequence like (h, w), a square crop of size (size, size) is made.
999
+ If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
1000
+
1001
+ Example:
1002
+ >>> transform = Compose([
1003
+ >>> FiveCrop(size), # this is a list of PIL Images
1004
+ >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor
1005
+ >>> ])
1006
+ >>> #In your test loop you can do the following:
1007
+ >>> input, target = batch # input is a 5d tensor, target is 2d
1008
+ >>> bs, ncrops, c, h, w = input.size()
1009
+ >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
1010
+ >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
1011
+ """
1012
+
1013
+ def __init__(self, size):
1014
+ super().__init__()
1015
+ _log_api_usage_once(self)
1016
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
1017
+
1018
+ def forward(self, img):
1019
+ """
1020
+ Args:
1021
+ img (PIL Image or Tensor): Image to be cropped.
1022
+
1023
+ Returns:
1024
+ tuple of 5 images. Image can be PIL Image or Tensor
1025
+ """
1026
+ return F.five_crop(img, self.size)
1027
+
1028
+ def __repr__(self) -> str:
1029
+ return f"{self.__class__.__name__}(size={self.size})"
1030
+
1031
+
1032
+ class TenCrop(torch.nn.Module):
1033
+ """Crop the given image into four corners and the central crop plus the flipped version of
1034
+ these (horizontal flipping is used by default).
1035
+ If the image is torch Tensor, it is expected
1036
+ to have [..., H, W] shape, where ... means an arbitrary number of leading
1037
+ dimensions
1038
+
1039
+ .. Note::
1040
+ This transform returns a tuple of images and there may be a mismatch in the number of
1041
+ inputs and targets your Dataset returns. See below for an example of how to deal with
1042
+ this.
1043
+
1044
+ Args:
1045
+ size (sequence or int): Desired output size of the crop. If size is an
1046
+ int instead of sequence like (h, w), a square crop (size, size) is
1047
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
1048
+ vertical_flip (bool): Use vertical flipping instead of horizontal
1049
+
1050
+ Example:
1051
+ >>> transform = Compose([
1052
+ >>> TenCrop(size), # this is a tuple of PIL Images
1053
+ >>> Lambda(lambda crops: torch.stack([PILToTensor()(crop) for crop in crops])) # returns a 4D tensor
1054
+ >>> ])
1055
+ >>> #In your test loop you can do the following:
1056
+ >>> input, target = batch # input is a 5d tensor, target is 2d
1057
+ >>> bs, ncrops, c, h, w = input.size()
1058
+ >>> result = model(input.view(-1, c, h, w)) # fuse batch size and ncrops
1059
+ >>> result_avg = result.view(bs, ncrops, -1).mean(1) # avg over crops
1060
+ """
1061
+
1062
+ def __init__(self, size, vertical_flip=False):
1063
+ super().__init__()
1064
+ _log_api_usage_once(self)
1065
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
1066
+ self.vertical_flip = vertical_flip
1067
+
1068
+ def forward(self, img):
1069
+ """
1070
+ Args:
1071
+ img (PIL Image or Tensor): Image to be cropped.
1072
+
1073
+ Returns:
1074
+ tuple of 10 images. Image can be PIL Image or Tensor
1075
+ """
1076
+ return F.ten_crop(img, self.size, self.vertical_flip)
1077
+
1078
+ def __repr__(self) -> str:
1079
+ return f"{self.__class__.__name__}(size={self.size}, vertical_flip={self.vertical_flip})"
1080
+
1081
+
1082
+ class LinearTransformation(torch.nn.Module):
1083
+ """Transform a tensor image with a square transformation matrix and a mean_vector computed
1084
+ offline.
1085
+ This transform does not support PIL Image.
1086
+ Given transformation_matrix and mean_vector, will flatten the torch.*Tensor and
1087
+ subtract mean_vector from it which is then followed by computing the dot
1088
+ product with the transformation matrix and then reshaping the tensor to its
1089
+ original shape.
1090
+
1091
+ Applications:
1092
+ whitening transformation: Suppose X is a column vector zero-centered data.
1093
+ Then compute the data covariance matrix [D x D] with torch.mm(X.t(), X),
1094
+ perform SVD on this matrix and pass it as transformation_matrix.
1095
+
1096
+ Args:
1097
+ transformation_matrix (Tensor): tensor [D x D], D = C x H x W
1098
+ mean_vector (Tensor): tensor [D], D = C x H x W
1099
+ """
1100
+
1101
+ def __init__(self, transformation_matrix, mean_vector):
1102
+ super().__init__()
1103
+ _log_api_usage_once(self)
1104
+ if transformation_matrix.size(0) != transformation_matrix.size(1):
1105
+ raise ValueError(
1106
+ "transformation_matrix should be square. Got "
1107
+ f"{tuple(transformation_matrix.size())} rectangular matrix."
1108
+ )
1109
+
1110
+ if mean_vector.size(0) != transformation_matrix.size(0):
1111
+ raise ValueError(
1112
+ f"mean_vector should have the same length {mean_vector.size(0)}"
1113
+ f" as any one of the dimensions of the transformation_matrix [{tuple(transformation_matrix.size())}]"
1114
+ )
1115
+
1116
+ if transformation_matrix.device != mean_vector.device:
1117
+ raise ValueError(
1118
+ f"Input tensors should be on the same device. Got {transformation_matrix.device} and {mean_vector.device}"
1119
+ )
1120
+
1121
+ if transformation_matrix.dtype != mean_vector.dtype:
1122
+ raise ValueError(
1123
+ f"Input tensors should have the same dtype. Got {transformation_matrix.dtype} and {mean_vector.dtype}"
1124
+ )
1125
+
1126
+ self.transformation_matrix = transformation_matrix
1127
+ self.mean_vector = mean_vector
1128
+
1129
+ def forward(self, tensor: Tensor) -> Tensor:
1130
+ """
1131
+ Args:
1132
+ tensor (Tensor): Tensor image to be whitened.
1133
+
1134
+ Returns:
1135
+ Tensor: Transformed image.
1136
+ """
1137
+ shape = tensor.shape
1138
+ n = shape[-3] * shape[-2] * shape[-1]
1139
+ if n != self.transformation_matrix.shape[0]:
1140
+ raise ValueError(
1141
+ "Input tensor and transformation matrix have incompatible shape."
1142
+ + f"[{shape[-3]} x {shape[-2]} x {shape[-1]}] != "
1143
+ + f"{self.transformation_matrix.shape[0]}"
1144
+ )
1145
+
1146
+ if tensor.device.type != self.mean_vector.device.type:
1147
+ raise ValueError(
1148
+ "Input tensor should be on the same device as transformation matrix and mean vector. "
1149
+ f"Got {tensor.device} vs {self.mean_vector.device}"
1150
+ )
1151
+
1152
+ flat_tensor = tensor.view(-1, n) - self.mean_vector
1153
+ transformation_matrix = self.transformation_matrix.to(flat_tensor.dtype)
1154
+ transformed_tensor = torch.mm(flat_tensor, transformation_matrix)
1155
+ tensor = transformed_tensor.view(shape)
1156
+ return tensor
1157
+
1158
+ def __repr__(self) -> str:
1159
+ s = (
1160
+ f"{self.__class__.__name__}(transformation_matrix="
1161
+ f"{self.transformation_matrix.tolist()}"
1162
+ f", mean_vector={self.mean_vector.tolist()})"
1163
+ )
1164
+ return s
1165
+
1166
+
1167
+ class ColorJitter(torch.nn.Module):
1168
+ """Randomly change the brightness, contrast, saturation and hue of an image.
1169
+ If the image is torch Tensor, it is expected
1170
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
1171
+ If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported.
1172
+
1173
+ Args:
1174
+ brightness (float or tuple of float (min, max)): How much to jitter brightness.
1175
+ brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
1176
+ or the given [min, max]. Should be non negative numbers.
1177
+ contrast (float or tuple of float (min, max)): How much to jitter contrast.
1178
+ contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
1179
+ or the given [min, max]. Should be non-negative numbers.
1180
+ saturation (float or tuple of float (min, max)): How much to jitter saturation.
1181
+ saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
1182
+ or the given [min, max]. Should be non negative numbers.
1183
+ hue (float or tuple of float (min, max)): How much to jitter hue.
1184
+ hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
1185
+ Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
1186
+ To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space;
1187
+ thus it does not work if you normalize your image to an interval with negative values,
1188
+ or use an interpolation that generates negative values before using this function.
1189
+ """
1190
+
1191
+ def __init__(
1192
+ self,
1193
+ brightness: Union[float, Tuple[float, float]] = 0,
1194
+ contrast: Union[float, Tuple[float, float]] = 0,
1195
+ saturation: Union[float, Tuple[float, float]] = 0,
1196
+ hue: Union[float, Tuple[float, float]] = 0,
1197
+ ) -> None:
1198
+ super().__init__()
1199
+ _log_api_usage_once(self)
1200
+ self.brightness = self._check_input(brightness, "brightness")
1201
+ self.contrast = self._check_input(contrast, "contrast")
1202
+ self.saturation = self._check_input(saturation, "saturation")
1203
+ self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False)
1204
+
1205
+ @torch.jit.unused
1206
+ def _check_input(self, value, name, center=1, bound=(0, float("inf")), clip_first_on_zero=True):
1207
+ if isinstance(value, numbers.Number):
1208
+ if value < 0:
1209
+ raise ValueError(f"If {name} is a single number, it must be non negative.")
1210
+ value = [center - float(value), center + float(value)]
1211
+ if clip_first_on_zero:
1212
+ value[0] = max(value[0], 0.0)
1213
+ elif isinstance(value, (tuple, list)) and len(value) == 2:
1214
+ value = [float(value[0]), float(value[1])]
1215
+ else:
1216
+ raise TypeError(f"{name} should be a single number or a list/tuple with length 2.")
1217
+
1218
+ if not bound[0] <= value[0] <= value[1] <= bound[1]:
1219
+ raise ValueError(f"{name} values should be between {bound}, but got {value}.")
1220
+
1221
+ # if value is 0 or (1., 1.) for brightness/contrast/saturation
1222
+ # or (0., 0.) for hue, do nothing
1223
+ if value[0] == value[1] == center:
1224
+ return None
1225
+ else:
1226
+ return tuple(value)
1227
+
1228
+ @staticmethod
1229
+ def get_params(
1230
+ brightness: Optional[List[float]],
1231
+ contrast: Optional[List[float]],
1232
+ saturation: Optional[List[float]],
1233
+ hue: Optional[List[float]],
1234
+ ) -> Tuple[Tensor, Optional[float], Optional[float], Optional[float], Optional[float]]:
1235
+ """Get the parameters for the randomized transform to be applied on image.
1236
+
1237
+ Args:
1238
+ brightness (tuple of float (min, max), optional): The range from which the brightness_factor is chosen
1239
+ uniformly. Pass None to turn off the transformation.
1240
+ contrast (tuple of float (min, max), optional): The range from which the contrast_factor is chosen
1241
+ uniformly. Pass None to turn off the transformation.
1242
+ saturation (tuple of float (min, max), optional): The range from which the saturation_factor is chosen
1243
+ uniformly. Pass None to turn off the transformation.
1244
+ hue (tuple of float (min, max), optional): The range from which the hue_factor is chosen uniformly.
1245
+ Pass None to turn off the transformation.
1246
+
1247
+ Returns:
1248
+ tuple: The parameters used to apply the randomized transform
1249
+ along with their random order.
1250
+ """
1251
+ fn_idx = torch.randperm(4)
1252
+
1253
+ b = None if brightness is None else float(torch.empty(1).uniform_(brightness[0], brightness[1]))
1254
+ c = None if contrast is None else float(torch.empty(1).uniform_(contrast[0], contrast[1]))
1255
+ s = None if saturation is None else float(torch.empty(1).uniform_(saturation[0], saturation[1]))
1256
+ h = None if hue is None else float(torch.empty(1).uniform_(hue[0], hue[1]))
1257
+
1258
+ return fn_idx, b, c, s, h
1259
+
1260
+ def forward(self, img):
1261
+ """
1262
+ Args:
1263
+ img (PIL Image or Tensor): Input image.
1264
+
1265
+ Returns:
1266
+ PIL Image or Tensor: Color jittered image.
1267
+ """
1268
+ fn_idx, brightness_factor, contrast_factor, saturation_factor, hue_factor = self.get_params(
1269
+ self.brightness, self.contrast, self.saturation, self.hue
1270
+ )
1271
+
1272
+ for fn_id in fn_idx:
1273
+ if fn_id == 0 and brightness_factor is not None:
1274
+ img = F.adjust_brightness(img, brightness_factor)
1275
+ elif fn_id == 1 and contrast_factor is not None:
1276
+ img = F.adjust_contrast(img, contrast_factor)
1277
+ elif fn_id == 2 and saturation_factor is not None:
1278
+ img = F.adjust_saturation(img, saturation_factor)
1279
+ elif fn_id == 3 and hue_factor is not None:
1280
+ img = F.adjust_hue(img, hue_factor)
1281
+
1282
+ return img
1283
+
1284
+ def __repr__(self) -> str:
1285
+ s = (
1286
+ f"{self.__class__.__name__}("
1287
+ f"brightness={self.brightness}"
1288
+ f", contrast={self.contrast}"
1289
+ f", saturation={self.saturation}"
1290
+ f", hue={self.hue})"
1291
+ )
1292
+ return s
1293
+
1294
+
1295
+ class RandomRotation(torch.nn.Module):
1296
+ """Rotate the image by angle.
1297
+ If the image is torch Tensor, it is expected
1298
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
1299
+
1300
+ Args:
1301
+ degrees (sequence or number): Range of degrees to select from.
1302
+ If degrees is a number instead of sequence like (min, max), the range of degrees
1303
+ will be (-degrees, +degrees).
1304
+ interpolation (InterpolationMode): Desired interpolation enum defined by
1305
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
1306
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
1307
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1308
+ expand (bool, optional): Optional expansion flag.
1309
+ If true, expands the output to make it large enough to hold the entire rotated image.
1310
+ If false or omitted, make the output image the same size as the input image.
1311
+ Note that the expand flag assumes rotation around the center and no translation.
1312
+ center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
1313
+ Default is the center of the image.
1314
+ fill (sequence or number): Pixel fill value for the area outside the rotated
1315
+ image. Default is ``0``. If given a number, the value is used for all bands respectively.
1316
+
1317
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
1318
+
1319
+ """
1320
+
1321
+ def __init__(self, degrees, interpolation=InterpolationMode.NEAREST, expand=False, center=None, fill=0):
1322
+ super().__init__()
1323
+ _log_api_usage_once(self)
1324
+
1325
+ if isinstance(interpolation, int):
1326
+ interpolation = _interpolation_modes_from_int(interpolation)
1327
+
1328
+ self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
1329
+
1330
+ if center is not None:
1331
+ _check_sequence_input(center, "center", req_sizes=(2,))
1332
+
1333
+ self.center = center
1334
+
1335
+ self.interpolation = interpolation
1336
+ self.expand = expand
1337
+
1338
+ if fill is None:
1339
+ fill = 0
1340
+ elif not isinstance(fill, (Sequence, numbers.Number)):
1341
+ raise TypeError("Fill should be either a sequence or a number.")
1342
+
1343
+ self.fill = fill
1344
+
1345
+ @staticmethod
1346
+ def get_params(degrees: List[float]) -> float:
1347
+ """Get parameters for ``rotate`` for a random rotation.
1348
+
1349
+ Returns:
1350
+ float: angle parameter to be passed to ``rotate`` for random rotation.
1351
+ """
1352
+ angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item())
1353
+ return angle
1354
+
1355
+ def forward(self, img):
1356
+ """
1357
+ Args:
1358
+ img (PIL Image or Tensor): Image to be rotated.
1359
+
1360
+ Returns:
1361
+ PIL Image or Tensor: Rotated image.
1362
+ """
1363
+ fill = self.fill
1364
+ channels, _, _ = F.get_dimensions(img)
1365
+ if isinstance(img, Tensor):
1366
+ if isinstance(fill, (int, float)):
1367
+ fill = [float(fill)] * channels
1368
+ else:
1369
+ fill = [float(f) for f in fill]
1370
+ angle = self.get_params(self.degrees)
1371
+
1372
+ return F.rotate(img, angle, self.interpolation, self.expand, self.center, fill)
1373
+
1374
+ def __repr__(self) -> str:
1375
+ interpolate_str = self.interpolation.value
1376
+ format_string = self.__class__.__name__ + f"(degrees={self.degrees}"
1377
+ format_string += f", interpolation={interpolate_str}"
1378
+ format_string += f", expand={self.expand}"
1379
+ if self.center is not None:
1380
+ format_string += f", center={self.center}"
1381
+ if self.fill is not None:
1382
+ format_string += f", fill={self.fill}"
1383
+ format_string += ")"
1384
+ return format_string
1385
+
1386
+
1387
+ class RandomAffine(torch.nn.Module):
1388
+ """Random affine transformation of the image keeping center invariant.
1389
+ If the image is torch Tensor, it is expected
1390
+ to have [..., H, W] shape, where ... means an arbitrary number of leading dimensions.
1391
+
1392
+ Args:
1393
+ degrees (sequence or number): Range of degrees to select from.
1394
+ If degrees is a number instead of sequence like (min, max), the range of degrees
1395
+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.
1396
+ translate (tuple, optional): tuple of maximum absolute fraction for horizontal
1397
+ and vertical translations. For example translate=(a, b), then horizontal shift
1398
+ is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
1399
+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
1400
+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
1401
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
1402
+ shear (sequence or number, optional): Range of degrees to select from.
1403
+ If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear)
1404
+ will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the
1405
+ range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values,
1406
+ an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
1407
+ Will not apply shear by default.
1408
+ interpolation (InterpolationMode): Desired interpolation enum defined by
1409
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
1410
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
1411
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1412
+ fill (sequence or number): Pixel fill value for the area outside the transformed
1413
+ image. Default is ``0``. If given a number, the value is used for all bands respectively.
1414
+ center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
1415
+ Default is the center of the image.
1416
+
1417
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
1418
+
1419
+ """
1420
+
1421
+ def __init__(
1422
+ self,
1423
+ degrees,
1424
+ translate=None,
1425
+ scale=None,
1426
+ shear=None,
1427
+ interpolation=InterpolationMode.NEAREST,
1428
+ fill=0,
1429
+ center=None,
1430
+ ):
1431
+ super().__init__()
1432
+ _log_api_usage_once(self)
1433
+
1434
+ if isinstance(interpolation, int):
1435
+ interpolation = _interpolation_modes_from_int(interpolation)
1436
+
1437
+ self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
1438
+
1439
+ if translate is not None:
1440
+ _check_sequence_input(translate, "translate", req_sizes=(2,))
1441
+ for t in translate:
1442
+ if not (0.0 <= t <= 1.0):
1443
+ raise ValueError("translation values should be between 0 and 1")
1444
+ self.translate = translate
1445
+
1446
+ if scale is not None:
1447
+ _check_sequence_input(scale, "scale", req_sizes=(2,))
1448
+ for s in scale:
1449
+ if s <= 0:
1450
+ raise ValueError("scale values should be positive")
1451
+ self.scale = scale
1452
+
1453
+ if shear is not None:
1454
+ self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4))
1455
+ else:
1456
+ self.shear = shear
1457
+
1458
+ self.interpolation = interpolation
1459
+
1460
+ if fill is None:
1461
+ fill = 0
1462
+ elif not isinstance(fill, (Sequence, numbers.Number)):
1463
+ raise TypeError("Fill should be either a sequence or a number.")
1464
+
1465
+ self.fill = fill
1466
+
1467
+ if center is not None:
1468
+ _check_sequence_input(center, "center", req_sizes=(2,))
1469
+
1470
+ self.center = center
1471
+
1472
+ @staticmethod
1473
+ def get_params(
1474
+ degrees: List[float],
1475
+ translate: Optional[List[float]],
1476
+ scale_ranges: Optional[List[float]],
1477
+ shears: Optional[List[float]],
1478
+ img_size: List[int],
1479
+ ) -> Tuple[float, Tuple[int, int], float, Tuple[float, float]]:
1480
+ """Get parameters for affine transformation
1481
+
1482
+ Returns:
1483
+ params to be passed to the affine transformation
1484
+ """
1485
+ angle = float(torch.empty(1).uniform_(float(degrees[0]), float(degrees[1])).item())
1486
+ if translate is not None:
1487
+ max_dx = float(translate[0] * img_size[0])
1488
+ max_dy = float(translate[1] * img_size[1])
1489
+ tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item()))
1490
+ ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item()))
1491
+ translations = (tx, ty)
1492
+ else:
1493
+ translations = (0, 0)
1494
+
1495
+ if scale_ranges is not None:
1496
+ scale = float(torch.empty(1).uniform_(scale_ranges[0], scale_ranges[1]).item())
1497
+ else:
1498
+ scale = 1.0
1499
+
1500
+ shear_x = shear_y = 0.0
1501
+ if shears is not None:
1502
+ shear_x = float(torch.empty(1).uniform_(shears[0], shears[1]).item())
1503
+ if len(shears) == 4:
1504
+ shear_y = float(torch.empty(1).uniform_(shears[2], shears[3]).item())
1505
+
1506
+ shear = (shear_x, shear_y)
1507
+
1508
+ return angle, translations, scale, shear
1509
+
1510
+ def forward(self, img):
1511
+ """
1512
+ img (PIL Image or Tensor): Image to be transformed.
1513
+
1514
+ Returns:
1515
+ PIL Image or Tensor: Affine transformed image.
1516
+ """
1517
+ fill = self.fill
1518
+ channels, height, width = F.get_dimensions(img)
1519
+ if isinstance(img, Tensor):
1520
+ if isinstance(fill, (int, float)):
1521
+ fill = [float(fill)] * channels
1522
+ else:
1523
+ fill = [float(f) for f in fill]
1524
+
1525
+ img_size = [width, height] # flip for keeping BC on get_params call
1526
+
1527
+ ret = self.get_params(self.degrees, self.translate, self.scale, self.shear, img_size)
1528
+
1529
+ return F.affine(img, *ret, interpolation=self.interpolation, fill=fill, center=self.center)
1530
+
1531
+ def __repr__(self) -> str:
1532
+ s = f"{self.__class__.__name__}(degrees={self.degrees}"
1533
+ s += f", translate={self.translate}" if self.translate is not None else ""
1534
+ s += f", scale={self.scale}" if self.scale is not None else ""
1535
+ s += f", shear={self.shear}" if self.shear is not None else ""
1536
+ s += f", interpolation={self.interpolation.value}" if self.interpolation != InterpolationMode.NEAREST else ""
1537
+ s += f", fill={self.fill}" if self.fill != 0 else ""
1538
+ s += f", center={self.center}" if self.center is not None else ""
1539
+ s += ")"
1540
+
1541
+ return s
1542
+
1543
+
1544
+ class Grayscale(torch.nn.Module):
1545
+ """Convert image to grayscale.
1546
+ If the image is torch Tensor, it is expected
1547
+ to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions
1548
+
1549
+ Args:
1550
+ num_output_channels (int): (1 or 3) number of channels desired for output image
1551
+
1552
+ Returns:
1553
+ PIL Image: Grayscale version of the input.
1554
+
1555
+ - If ``num_output_channels == 1`` : returned image is single channel
1556
+ - If ``num_output_channels == 3`` : returned image is 3 channel with r == g == b
1557
+
1558
+ """
1559
+
1560
+ def __init__(self, num_output_channels=1):
1561
+ super().__init__()
1562
+ _log_api_usage_once(self)
1563
+ self.num_output_channels = num_output_channels
1564
+
1565
+ def forward(self, img):
1566
+ """
1567
+ Args:
1568
+ img (PIL Image or Tensor): Image to be converted to grayscale.
1569
+
1570
+ Returns:
1571
+ PIL Image or Tensor: Grayscaled image.
1572
+ """
1573
+ return F.rgb_to_grayscale(img, num_output_channels=self.num_output_channels)
1574
+
1575
+ def __repr__(self) -> str:
1576
+ return f"{self.__class__.__name__}(num_output_channels={self.num_output_channels})"
1577
+
1578
+
1579
+ class RandomGrayscale(torch.nn.Module):
1580
+ """Randomly convert image to grayscale with a probability of p (default 0.1).
1581
+ If the image is torch Tensor, it is expected
1582
+ to have [..., 3, H, W] shape, where ... means an arbitrary number of leading dimensions
1583
+
1584
+ Args:
1585
+ p (float): probability that image should be converted to grayscale.
1586
+
1587
+ Returns:
1588
+ PIL Image or Tensor: Grayscale version of the input image with probability p and unchanged
1589
+ with probability (1-p).
1590
+ - If input image is 1 channel: grayscale version is 1 channel
1591
+ - If input image is 3 channel: grayscale version is 3 channel with r == g == b
1592
+
1593
+ """
1594
+
1595
+ def __init__(self, p=0.1):
1596
+ super().__init__()
1597
+ _log_api_usage_once(self)
1598
+ self.p = p
1599
+
1600
+ def forward(self, img):
1601
+ """
1602
+ Args:
1603
+ img (PIL Image or Tensor): Image to be converted to grayscale.
1604
+
1605
+ Returns:
1606
+ PIL Image or Tensor: Randomly grayscaled image.
1607
+ """
1608
+ num_output_channels, _, _ = F.get_dimensions(img)
1609
+ if torch.rand(1) < self.p:
1610
+ return F.rgb_to_grayscale(img, num_output_channels=num_output_channels)
1611
+ return img
1612
+
1613
+ def __repr__(self) -> str:
1614
+ return f"{self.__class__.__name__}(p={self.p})"
1615
+
1616
+
1617
+ class RandomErasing(torch.nn.Module):
1618
+ """Randomly selects a rectangle region in a torch.Tensor image and erases its pixels.
1619
+ This transform does not support PIL Image.
1620
+ 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896
1621
+
1622
+ Args:
1623
+ p: probability that the random erasing operation will be performed.
1624
+ scale: range of proportion of erased area against input image.
1625
+ ratio: range of aspect ratio of erased area.
1626
+ value: erasing value. Default is 0. If a single int, it is used to
1627
+ erase all pixels. If a tuple of length 3, it is used to erase
1628
+ R, G, B channels respectively.
1629
+ If a str of 'random', erasing each pixel with random values.
1630
+ inplace: boolean to make this transform inplace. Default set to False.
1631
+
1632
+ Returns:
1633
+ Erased Image.
1634
+
1635
+ Example:
1636
+ >>> transform = transforms.Compose([
1637
+ >>> transforms.RandomHorizontalFlip(),
1638
+ >>> transforms.PILToTensor(),
1639
+ >>> transforms.ConvertImageDtype(torch.float),
1640
+ >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
1641
+ >>> transforms.RandomErasing(),
1642
+ >>> ])
1643
+ """
1644
+
1645
+ def __init__(self, p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), value=0, inplace=False):
1646
+ super().__init__()
1647
+ _log_api_usage_once(self)
1648
+ if not isinstance(value, (numbers.Number, str, tuple, list)):
1649
+ raise TypeError("Argument value should be either a number or str or a sequence")
1650
+ if isinstance(value, str) and value != "random":
1651
+ raise ValueError("If value is str, it should be 'random'")
1652
+ if not isinstance(scale, (tuple, list)):
1653
+ raise TypeError("Scale should be a sequence")
1654
+ if not isinstance(ratio, (tuple, list)):
1655
+ raise TypeError("Ratio should be a sequence")
1656
+ if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
1657
+ warnings.warn("Scale and ratio should be of kind (min, max)")
1658
+ if scale[0] < 0 or scale[1] > 1:
1659
+ raise ValueError("Scale should be between 0 and 1")
1660
+ if p < 0 or p > 1:
1661
+ raise ValueError("Random erasing probability should be between 0 and 1")
1662
+
1663
+ self.p = p
1664
+ self.scale = scale
1665
+ self.ratio = ratio
1666
+ self.value = value
1667
+ self.inplace = inplace
1668
+
1669
+ @staticmethod
1670
+ def get_params(
1671
+ img: Tensor, scale: Tuple[float, float], ratio: Tuple[float, float], value: Optional[List[float]] = None
1672
+ ) -> Tuple[int, int, int, int, Tensor]:
1673
+ """Get parameters for ``erase`` for a random erasing.
1674
+
1675
+ Args:
1676
+ img (Tensor): Tensor image to be erased.
1677
+ scale (sequence): range of proportion of erased area against input image.
1678
+ ratio (sequence): range of aspect ratio of erased area.
1679
+ value (list, optional): erasing value. If None, it is interpreted as "random"
1680
+ (erasing each pixel with random values). If ``len(value)`` is 1, it is interpreted as a number,
1681
+ i.e. ``value[0]``.
1682
+
1683
+ Returns:
1684
+ tuple: params (i, j, h, w, v) to be passed to ``erase`` for random erasing.
1685
+ """
1686
+ img_c, img_h, img_w = img.shape[-3], img.shape[-2], img.shape[-1]
1687
+ area = img_h * img_w
1688
+
1689
+ log_ratio = torch.log(torch.tensor(ratio))
1690
+ for _ in range(10):
1691
+ erase_area = area * torch.empty(1).uniform_(scale[0], scale[1]).item()
1692
+ aspect_ratio = torch.exp(torch.empty(1).uniform_(log_ratio[0], log_ratio[1])).item()
1693
+
1694
+ h = int(round(math.sqrt(erase_area * aspect_ratio)))
1695
+ w = int(round(math.sqrt(erase_area / aspect_ratio)))
1696
+ if not (h < img_h and w < img_w):
1697
+ continue
1698
+
1699
+ if value is None:
1700
+ v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()
1701
+ else:
1702
+ v = torch.tensor(value)[:, None, None]
1703
+
1704
+ i = torch.randint(0, img_h - h + 1, size=(1,)).item()
1705
+ j = torch.randint(0, img_w - w + 1, size=(1,)).item()
1706
+ return i, j, h, w, v
1707
+
1708
+ # Return original image
1709
+ return 0, 0, img_h, img_w, img
1710
+
1711
+ def forward(self, img):
1712
+ """
1713
+ Args:
1714
+ img (Tensor): Tensor image to be erased.
1715
+
1716
+ Returns:
1717
+ img (Tensor): Erased Tensor image.
1718
+ """
1719
+ if torch.rand(1) < self.p:
1720
+
1721
+ # cast self.value to script acceptable type
1722
+ if isinstance(self.value, (int, float)):
1723
+ value = [float(self.value)]
1724
+ elif isinstance(self.value, str):
1725
+ value = None
1726
+ elif isinstance(self.value, (list, tuple)):
1727
+ value = [float(v) for v in self.value]
1728
+ else:
1729
+ value = self.value
1730
+
1731
+ if value is not None and not (len(value) in (1, img.shape[-3])):
1732
+ raise ValueError(
1733
+ "If value is a sequence, it should have either a single value or "
1734
+ f"{img.shape[-3]} (number of input channels)"
1735
+ )
1736
+
1737
+ x, y, h, w, v = self.get_params(img, scale=self.scale, ratio=self.ratio, value=value)
1738
+ return F.erase(img, x, y, h, w, v, self.inplace)
1739
+ return img
1740
+
1741
+ def __repr__(self) -> str:
1742
+ s = (
1743
+ f"{self.__class__.__name__}"
1744
+ f"(p={self.p}, "
1745
+ f"scale={self.scale}, "
1746
+ f"ratio={self.ratio}, "
1747
+ f"value={self.value}, "
1748
+ f"inplace={self.inplace})"
1749
+ )
1750
+ return s
1751
+
1752
+
1753
+ class GaussianBlur(torch.nn.Module):
1754
+ """Blurs image with randomly chosen Gaussian blur.
1755
+ If the image is torch Tensor, it is expected
1756
+ to have [..., C, H, W] shape, where ... means at most one leading dimension.
1757
+
1758
+ Args:
1759
+ kernel_size (int or sequence): Size of the Gaussian kernel.
1760
+ sigma (float or tuple of float (min, max)): Standard deviation to be used for
1761
+ creating kernel to perform blurring. If float, sigma is fixed. If it is tuple
1762
+ of float (min, max), sigma is chosen uniformly at random to lie in the
1763
+ given range.
1764
+
1765
+ Returns:
1766
+ PIL Image or Tensor: Gaussian blurred version of the input image.
1767
+
1768
+ """
1769
+
1770
+ def __init__(self, kernel_size, sigma=(0.1, 2.0)):
1771
+ super().__init__()
1772
+ _log_api_usage_once(self)
1773
+ self.kernel_size = _setup_size(kernel_size, "Kernel size should be a tuple/list of two integers")
1774
+ for ks in self.kernel_size:
1775
+ if ks <= 0 or ks % 2 == 0:
1776
+ raise ValueError("Kernel size value should be an odd and positive number.")
1777
+
1778
+ if isinstance(sigma, numbers.Number):
1779
+ if sigma <= 0:
1780
+ raise ValueError("If sigma is a single number, it must be positive.")
1781
+ sigma = (sigma, sigma)
1782
+ elif isinstance(sigma, Sequence) and len(sigma) == 2:
1783
+ if not 0.0 < sigma[0] <= sigma[1]:
1784
+ raise ValueError("sigma values should be positive and of the form (min, max).")
1785
+ else:
1786
+ raise ValueError("sigma should be a single number or a list/tuple with length 2.")
1787
+
1788
+ self.sigma = sigma
1789
+
1790
+ @staticmethod
1791
+ def get_params(sigma_min: float, sigma_max: float) -> float:
1792
+ """Choose sigma for random gaussian blurring.
1793
+
1794
+ Args:
1795
+ sigma_min (float): Minimum standard deviation that can be chosen for blurring kernel.
1796
+ sigma_max (float): Maximum standard deviation that can be chosen for blurring kernel.
1797
+
1798
+ Returns:
1799
+ float: Standard deviation to be passed to calculate kernel for gaussian blurring.
1800
+ """
1801
+ return torch.empty(1).uniform_(sigma_min, sigma_max).item()
1802
+
1803
+ def forward(self, img: Tensor) -> Tensor:
1804
+ """
1805
+ Args:
1806
+ img (PIL Image or Tensor): image to be blurred.
1807
+
1808
+ Returns:
1809
+ PIL Image or Tensor: Gaussian blurred image
1810
+ """
1811
+ sigma = self.get_params(self.sigma[0], self.sigma[1])
1812
+ return F.gaussian_blur(img, self.kernel_size, [sigma, sigma])
1813
+
1814
+ def __repr__(self) -> str:
1815
+ s = f"{self.__class__.__name__}(kernel_size={self.kernel_size}, sigma={self.sigma})"
1816
+ return s
1817
+
1818
+
1819
+ def _setup_size(size, error_msg):
1820
+ if isinstance(size, numbers.Number):
1821
+ return int(size), int(size)
1822
+
1823
+ if isinstance(size, Sequence) and len(size) == 1:
1824
+ return size[0], size[0]
1825
+
1826
+ if len(size) != 2:
1827
+ raise ValueError(error_msg)
1828
+
1829
+ return size
1830
+
1831
+
1832
+ def _check_sequence_input(x, name, req_sizes):
1833
+ msg = req_sizes[0] if len(req_sizes) < 2 else " or ".join([str(s) for s in req_sizes])
1834
+ if not isinstance(x, Sequence):
1835
+ raise TypeError(f"{name} should be a sequence of length {msg}.")
1836
+ if len(x) not in req_sizes:
1837
+ raise ValueError(f"{name} should be a sequence of length {msg}.")
1838
+
1839
+
1840
+ def _setup_angle(x, name, req_sizes=(2,)):
1841
+ if isinstance(x, numbers.Number):
1842
+ if x < 0:
1843
+ raise ValueError(f"If {name} is a single number, it must be positive.")
1844
+ x = [-x, x]
1845
+ else:
1846
+ _check_sequence_input(x, name, req_sizes)
1847
+
1848
+ return [float(d) for d in x]
1849
+
1850
+
1851
+ class RandomInvert(torch.nn.Module):
1852
+ """Inverts the colors of the given image randomly with a given probability.
1853
+ If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1854
+ where ... means it can have an arbitrary number of leading dimensions.
1855
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1856
+
1857
+ Args:
1858
+ p (float): probability of the image being color inverted. Default value is 0.5
1859
+ """
1860
+
1861
+ def __init__(self, p=0.5):
1862
+ super().__init__()
1863
+ _log_api_usage_once(self)
1864
+ self.p = p
1865
+
1866
+ def forward(self, img):
1867
+ """
1868
+ Args:
1869
+ img (PIL Image or Tensor): Image to be inverted.
1870
+
1871
+ Returns:
1872
+ PIL Image or Tensor: Randomly color inverted image.
1873
+ """
1874
+ if torch.rand(1).item() < self.p:
1875
+ return F.invert(img)
1876
+ return img
1877
+
1878
+ def __repr__(self) -> str:
1879
+ return f"{self.__class__.__name__}(p={self.p})"
1880
+
1881
+
1882
+ class RandomPosterize(torch.nn.Module):
1883
+ """Posterize the image randomly with a given probability by reducing the
1884
+ number of bits for each color channel. If the image is torch Tensor, it should be of type torch.uint8,
1885
+ and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
1886
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1887
+
1888
+ Args:
1889
+ bits (int): number of bits to keep for each channel (0-8)
1890
+ p (float): probability of the image being posterized. Default value is 0.5
1891
+ """
1892
+
1893
+ def __init__(self, bits, p=0.5):
1894
+ super().__init__()
1895
+ _log_api_usage_once(self)
1896
+ self.bits = bits
1897
+ self.p = p
1898
+
1899
+ def forward(self, img):
1900
+ """
1901
+ Args:
1902
+ img (PIL Image or Tensor): Image to be posterized.
1903
+
1904
+ Returns:
1905
+ PIL Image or Tensor: Randomly posterized image.
1906
+ """
1907
+ if torch.rand(1).item() < self.p:
1908
+ return F.posterize(img, self.bits)
1909
+ return img
1910
+
1911
+ def __repr__(self) -> str:
1912
+ return f"{self.__class__.__name__}(bits={self.bits},p={self.p})"
1913
+
1914
+
1915
+ class RandomSolarize(torch.nn.Module):
1916
+ """Solarize the image randomly with a given probability by inverting all pixel
1917
+ values above a threshold. If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
1918
+ where ... means it can have an arbitrary number of leading dimensions.
1919
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1920
+
1921
+ Args:
1922
+ threshold (float): all pixels equal or above this value are inverted.
1923
+ p (float): probability of the image being solarized. Default value is 0.5
1924
+ """
1925
+
1926
+ def __init__(self, threshold, p=0.5):
1927
+ super().__init__()
1928
+ _log_api_usage_once(self)
1929
+ self.threshold = threshold
1930
+ self.p = p
1931
+
1932
+ def forward(self, img):
1933
+ """
1934
+ Args:
1935
+ img (PIL Image or Tensor): Image to be solarized.
1936
+
1937
+ Returns:
1938
+ PIL Image or Tensor: Randomly solarized image.
1939
+ """
1940
+ if torch.rand(1).item() < self.p:
1941
+ return F.solarize(img, self.threshold)
1942
+ return img
1943
+
1944
+ def __repr__(self) -> str:
1945
+ return f"{self.__class__.__name__}(threshold={self.threshold},p={self.p})"
1946
+
1947
+
1948
+ class RandomAdjustSharpness(torch.nn.Module):
1949
+ """Adjust the sharpness of the image randomly with a given probability. If the image is torch Tensor,
1950
+ it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
1951
+
1952
+ Args:
1953
+ sharpness_factor (float): How much to adjust the sharpness. Can be
1954
+ any non-negative number. 0 gives a blurred image, 1 gives the
1955
+ original image while 2 increases the sharpness by a factor of 2.
1956
+ p (float): probability of the image being sharpened. Default value is 0.5
1957
+ """
1958
+
1959
+ def __init__(self, sharpness_factor, p=0.5):
1960
+ super().__init__()
1961
+ _log_api_usage_once(self)
1962
+ self.sharpness_factor = sharpness_factor
1963
+ self.p = p
1964
+
1965
+ def forward(self, img):
1966
+ """
1967
+ Args:
1968
+ img (PIL Image or Tensor): Image to be sharpened.
1969
+
1970
+ Returns:
1971
+ PIL Image or Tensor: Randomly sharpened image.
1972
+ """
1973
+ if torch.rand(1).item() < self.p:
1974
+ return F.adjust_sharpness(img, self.sharpness_factor)
1975
+ return img
1976
+
1977
+ def __repr__(self) -> str:
1978
+ return f"{self.__class__.__name__}(sharpness_factor={self.sharpness_factor},p={self.p})"
1979
+
1980
+
1981
+ class RandomAutocontrast(torch.nn.Module):
1982
+ """Autocontrast the pixels of the given image randomly with a given probability.
1983
+ If the image is torch Tensor, it is expected
1984
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
1985
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
1986
+
1987
+ Args:
1988
+ p (float): probability of the image being autocontrasted. Default value is 0.5
1989
+ """
1990
+
1991
+ def __init__(self, p=0.5):
1992
+ super().__init__()
1993
+ _log_api_usage_once(self)
1994
+ self.p = p
1995
+
1996
+ def forward(self, img):
1997
+ """
1998
+ Args:
1999
+ img (PIL Image or Tensor): Image to be autocontrasted.
2000
+
2001
+ Returns:
2002
+ PIL Image or Tensor: Randomly autocontrasted image.
2003
+ """
2004
+ if torch.rand(1).item() < self.p:
2005
+ return F.autocontrast(img)
2006
+ return img
2007
+
2008
+ def __repr__(self) -> str:
2009
+ return f"{self.__class__.__name__}(p={self.p})"
2010
+
2011
+
2012
+ class RandomEqualize(torch.nn.Module):
2013
+ """Equalize the histogram of the given image randomly with a given probability.
2014
+ If the image is torch Tensor, it is expected
2015
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
2016
+ If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
2017
+
2018
+ Args:
2019
+ p (float): probability of the image being equalized. Default value is 0.5
2020
+ """
2021
+
2022
+ def __init__(self, p=0.5):
2023
+ super().__init__()
2024
+ _log_api_usage_once(self)
2025
+ self.p = p
2026
+
2027
+ def forward(self, img):
2028
+ """
2029
+ Args:
2030
+ img (PIL Image or Tensor): Image to be equalized.
2031
+
2032
+ Returns:
2033
+ PIL Image or Tensor: Randomly equalized image.
2034
+ """
2035
+ if torch.rand(1).item() < self.p:
2036
+ return F.equalize(img)
2037
+ return img
2038
+
2039
+ def __repr__(self) -> str:
2040
+ return f"{self.__class__.__name__}(p={self.p})"
2041
+
2042
+
2043
+ class ElasticTransform(torch.nn.Module):
2044
+ """Transform a tensor image with elastic transformations.
2045
+ Given alpha and sigma, it will generate displacement
2046
+ vectors for all pixels based on random offsets. Alpha controls the strength
2047
+ and sigma controls the smoothness of the displacements.
2048
+ The displacements are added to an identity grid and the resulting grid is
2049
+ used to grid_sample from the image.
2050
+
2051
+ Applications:
2052
+ Randomly transforms the morphology of objects in images and produces a
2053
+ see-through-water-like effect.
2054
+
2055
+ Args:
2056
+ alpha (float or sequence of floats): Magnitude of displacements. Default is 50.0.
2057
+ sigma (float or sequence of floats): Smoothness of displacements. Default is 5.0.
2058
+ interpolation (InterpolationMode): Desired interpolation enum defined by
2059
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
2060
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
2061
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
2062
+ fill (sequence or number): Pixel fill value for the area outside the transformed
2063
+ image. Default is ``0``. If given a number, the value is used for all bands respectively.
2064
+
2065
+ """
2066
+
2067
+ def __init__(self, alpha=50.0, sigma=5.0, interpolation=InterpolationMode.BILINEAR, fill=0):
2068
+ super().__init__()
2069
+ _log_api_usage_once(self)
2070
+ if not isinstance(alpha, (float, Sequence)):
2071
+ raise TypeError(f"alpha should be float or a sequence of floats. Got {type(alpha)}")
2072
+ if isinstance(alpha, Sequence) and len(alpha) != 2:
2073
+ raise ValueError(f"If alpha is a sequence its length should be 2. Got {len(alpha)}")
2074
+ if isinstance(alpha, Sequence):
2075
+ for element in alpha:
2076
+ if not isinstance(element, float):
2077
+ raise TypeError(f"alpha should be a sequence of floats. Got {type(element)}")
2078
+
2079
+ if isinstance(alpha, float):
2080
+ alpha = [float(alpha), float(alpha)]
2081
+ if isinstance(alpha, (list, tuple)) and len(alpha) == 1:
2082
+ alpha = [alpha[0], alpha[0]]
2083
+
2084
+ self.alpha = alpha
2085
+
2086
+ if not isinstance(sigma, (float, Sequence)):
2087
+ raise TypeError(f"sigma should be float or a sequence of floats. Got {type(sigma)}")
2088
+ if isinstance(sigma, Sequence) and len(sigma) != 2:
2089
+ raise ValueError(f"If sigma is a sequence its length should be 2. Got {len(sigma)}")
2090
+ if isinstance(sigma, Sequence):
2091
+ for element in sigma:
2092
+ if not isinstance(element, float):
2093
+ raise TypeError(f"sigma should be a sequence of floats. Got {type(element)}")
2094
+
2095
+ if isinstance(sigma, float):
2096
+ sigma = [float(sigma), float(sigma)]
2097
+ if isinstance(sigma, (list, tuple)) and len(sigma) == 1:
2098
+ sigma = [sigma[0], sigma[0]]
2099
+
2100
+ self.sigma = sigma
2101
+
2102
+ if isinstance(interpolation, int):
2103
+ interpolation = _interpolation_modes_from_int(interpolation)
2104
+ self.interpolation = interpolation
2105
+
2106
+ if isinstance(fill, (int, float)):
2107
+ fill = [float(fill)]
2108
+ elif isinstance(fill, (list, tuple)):
2109
+ fill = [float(f) for f in fill]
2110
+ else:
2111
+ raise TypeError(f"fill should be int or float or a list or tuple of them. Got {type(fill)}")
2112
+ self.fill = fill
2113
+
2114
+ @staticmethod
2115
+ def get_params(alpha: List[float], sigma: List[float], size: List[int]) -> Tensor:
2116
+ dx = torch.rand([1, 1] + size) * 2 - 1
2117
+ if sigma[0] > 0.0:
2118
+ kx = int(8 * sigma[0] + 1)
2119
+ # if kernel size is even we have to make it odd
2120
+ if kx % 2 == 0:
2121
+ kx += 1
2122
+ dx = F.gaussian_blur(dx, [kx, kx], sigma)
2123
+ dx = dx * alpha[0] / size[0]
2124
+
2125
+ dy = torch.rand([1, 1] + size) * 2 - 1
2126
+ if sigma[1] > 0.0:
2127
+ ky = int(8 * sigma[1] + 1)
2128
+ # if kernel size is even we have to make it odd
2129
+ if ky % 2 == 0:
2130
+ ky += 1
2131
+ dy = F.gaussian_blur(dy, [ky, ky], sigma)
2132
+ dy = dy * alpha[1] / size[1]
2133
+ return torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2
2134
+
2135
+ def forward(self, tensor: Tensor) -> Tensor:
2136
+ """
2137
+ Args:
2138
+ tensor (PIL Image or Tensor): Image to be transformed.
2139
+
2140
+ Returns:
2141
+ PIL Image or Tensor: Transformed image.
2142
+ """
2143
+ _, height, width = F.get_dimensions(tensor)
2144
+ displacement = self.get_params(self.alpha, self.sigma, [height, width])
2145
+ return F.elastic_transform(tensor, displacement, self.interpolation, self.fill)
2146
+
2147
+ def __repr__(self):
2148
+ format_string = self.__class__.__name__
2149
+ format_string += f"(alpha={self.alpha}"
2150
+ format_string += f", sigma={self.sigma}"
2151
+ format_string += f", interpolation={self.interpolation}"
2152
+ format_string += f", fill={self.fill})"
2153
+ return format_string
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__init__.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torchvision.transforms import AutoAugmentPolicy, InterpolationMode # usort: skip
2
+
3
+ from . import functional # usort: skip
4
+
5
+ from ._transform import Transform # usort: skip
6
+
7
+ from ._augment import CutMix, MixUp, RandomErasing
8
+ from ._auto_augment import AugMix, AutoAugment, RandAugment, TrivialAugmentWide
9
+ from ._color import (
10
+ ColorJitter,
11
+ Grayscale,
12
+ RandomAdjustSharpness,
13
+ RandomAutocontrast,
14
+ RandomChannelPermutation,
15
+ RandomEqualize,
16
+ RandomGrayscale,
17
+ RandomInvert,
18
+ RandomPhotometricDistort,
19
+ RandomPosterize,
20
+ RandomSolarize,
21
+ )
22
+ from ._container import Compose, RandomApply, RandomChoice, RandomOrder
23
+ from ._geometry import (
24
+ CenterCrop,
25
+ ElasticTransform,
26
+ FiveCrop,
27
+ Pad,
28
+ RandomAffine,
29
+ RandomCrop,
30
+ RandomHorizontalFlip,
31
+ RandomIoUCrop,
32
+ RandomPerspective,
33
+ RandomResize,
34
+ RandomResizedCrop,
35
+ RandomRotation,
36
+ RandomShortestSize,
37
+ RandomVerticalFlip,
38
+ RandomZoomOut,
39
+ Resize,
40
+ ScaleJitter,
41
+ TenCrop,
42
+ )
43
+ from ._meta import ClampBoundingBoxes, ConvertBoundingBoxFormat
44
+ from ._misc import (
45
+ ConvertImageDtype,
46
+ GaussianBlur,
47
+ Identity,
48
+ Lambda,
49
+ LinearTransformation,
50
+ Normalize,
51
+ SanitizeBoundingBoxes,
52
+ ToDtype,
53
+ )
54
+ from ._temporal import UniformTemporalSubsample
55
+ from ._type_conversion import PILToTensor, ToImage, ToPILImage, ToPureTensor
56
+
57
+ from ._deprecated import ToTensor # usort: skip
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_auto_augment.cpython-310.pyc ADDED
Binary file (24.1 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_color.cpython-310.pyc ADDED
Binary file (17.8 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_deprecated.cpython-310.pyc ADDED
Binary file (2.42 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/__pycache__/_misc.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_augment.py ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ import warnings
4
+ from typing import Any, Callable, Dict, List, Tuple
5
+
6
+ import PIL.Image
7
+ import torch
8
+ from torch.nn.functional import one_hot
9
+ from torch.utils._pytree import tree_flatten, tree_unflatten
10
+ from torchvision import transforms as _transforms, tv_tensors
11
+ from torchvision.transforms.v2 import functional as F
12
+
13
+ from ._transform import _RandomApplyTransform, Transform
14
+ from ._utils import _parse_labels_getter, has_any, is_pure_tensor, query_chw, query_size
15
+
16
+
17
+ class RandomErasing(_RandomApplyTransform):
18
+ """Randomly select a rectangle region in the input image or video and erase its pixels.
19
+
20
+ This transform does not support PIL Image.
21
+ 'Random Erasing Data Augmentation' by Zhong et al. See https://arxiv.org/abs/1708.04896
22
+
23
+ Args:
24
+ p (float, optional): probability that the random erasing operation will be performed.
25
+ scale (tuple of float, optional): range of proportion of erased area against input image.
26
+ ratio (tuple of float, optional): range of aspect ratio of erased area.
27
+ value (number or tuple of numbers): erasing value. Default is 0. If a single int, it is used to
28
+ erase all pixels. If a tuple of length 3, it is used to erase
29
+ R, G, B channels respectively.
30
+ If a str of 'random', erasing each pixel with random values.
31
+ inplace (bool, optional): boolean to make this transform inplace. Default set to False.
32
+
33
+ Returns:
34
+ Erased input.
35
+
36
+ Example:
37
+ >>> from torchvision.transforms import v2 as transforms
38
+ >>>
39
+ >>> transform = transforms.Compose([
40
+ >>> transforms.RandomHorizontalFlip(),
41
+ >>> transforms.PILToTensor(),
42
+ >>> transforms.ConvertImageDtype(torch.float),
43
+ >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
44
+ >>> transforms.RandomErasing(),
45
+ >>> ])
46
+ """
47
+
48
+ _v1_transform_cls = _transforms.RandomErasing
49
+
50
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
51
+ return dict(
52
+ super()._extract_params_for_v1_transform(),
53
+ value="random" if self.value is None else self.value,
54
+ )
55
+
56
+ def __init__(
57
+ self,
58
+ p: float = 0.5,
59
+ scale: Tuple[float, float] = (0.02, 0.33),
60
+ ratio: Tuple[float, float] = (0.3, 3.3),
61
+ value: float = 0.0,
62
+ inplace: bool = False,
63
+ ):
64
+ super().__init__(p=p)
65
+ if not isinstance(value, (numbers.Number, str, tuple, list)):
66
+ raise TypeError("Argument value should be either a number or str or a sequence")
67
+ if isinstance(value, str) and value != "random":
68
+ raise ValueError("If value is str, it should be 'random'")
69
+ if not isinstance(scale, (tuple, list)):
70
+ raise TypeError("Scale should be a sequence")
71
+ if not isinstance(ratio, (tuple, list)):
72
+ raise TypeError("Ratio should be a sequence")
73
+ if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
74
+ warnings.warn("Scale and ratio should be of kind (min, max)")
75
+ if scale[0] < 0 or scale[1] > 1:
76
+ raise ValueError("Scale should be between 0 and 1")
77
+ self.scale = scale
78
+ self.ratio = ratio
79
+ if isinstance(value, (int, float)):
80
+ self.value = [float(value)]
81
+ elif isinstance(value, str):
82
+ self.value = None
83
+ elif isinstance(value, (list, tuple)):
84
+ self.value = [float(v) for v in value]
85
+ else:
86
+ self.value = value
87
+ self.inplace = inplace
88
+
89
+ self._log_ratio = torch.log(torch.tensor(self.ratio))
90
+
91
+ def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any:
92
+ if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask)):
93
+ warnings.warn(
94
+ f"{type(self).__name__}() is currently passing through inputs of type "
95
+ f"tv_tensors.{type(inpt).__name__}. This will likely change in the future."
96
+ )
97
+ return super()._call_kernel(functional, inpt, *args, **kwargs)
98
+
99
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
100
+ img_c, img_h, img_w = query_chw(flat_inputs)
101
+
102
+ if self.value is not None and not (len(self.value) in (1, img_c)):
103
+ raise ValueError(
104
+ f"If value is a sequence, it should have either a single value or {img_c} (number of inpt channels)"
105
+ )
106
+
107
+ area = img_h * img_w
108
+
109
+ log_ratio = self._log_ratio
110
+ for _ in range(10):
111
+ erase_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
112
+ aspect_ratio = torch.exp(
113
+ torch.empty(1).uniform_(
114
+ log_ratio[0], # type: ignore[arg-type]
115
+ log_ratio[1], # type: ignore[arg-type]
116
+ )
117
+ ).item()
118
+
119
+ h = int(round(math.sqrt(erase_area * aspect_ratio)))
120
+ w = int(round(math.sqrt(erase_area / aspect_ratio)))
121
+ if not (h < img_h and w < img_w):
122
+ continue
123
+
124
+ if self.value is None:
125
+ v = torch.empty([img_c, h, w], dtype=torch.float32).normal_()
126
+ else:
127
+ v = torch.tensor(self.value)[:, None, None]
128
+
129
+ i = torch.randint(0, img_h - h + 1, size=(1,)).item()
130
+ j = torch.randint(0, img_w - w + 1, size=(1,)).item()
131
+ break
132
+ else:
133
+ i, j, h, w, v = 0, 0, img_h, img_w, None
134
+
135
+ return dict(i=i, j=j, h=h, w=w, v=v)
136
+
137
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
138
+ if params["v"] is not None:
139
+ inpt = self._call_kernel(F.erase, inpt, **params, inplace=self.inplace)
140
+
141
+ return inpt
142
+
143
+
144
+ class _BaseMixUpCutMix(Transform):
145
+ def __init__(self, *, alpha: float = 1.0, num_classes: int, labels_getter="default") -> None:
146
+ super().__init__()
147
+ self.alpha = float(alpha)
148
+ self._dist = torch.distributions.Beta(torch.tensor([alpha]), torch.tensor([alpha]))
149
+
150
+ self.num_classes = num_classes
151
+
152
+ self._labels_getter = _parse_labels_getter(labels_getter)
153
+
154
+ def forward(self, *inputs):
155
+ inputs = inputs if len(inputs) > 1 else inputs[0]
156
+ flat_inputs, spec = tree_flatten(inputs)
157
+ needs_transform_list = self._needs_transform_list(flat_inputs)
158
+
159
+ if has_any(flat_inputs, PIL.Image.Image, tv_tensors.BoundingBoxes, tv_tensors.Mask):
160
+ raise ValueError(f"{type(self).__name__}() does not support PIL images, bounding boxes and masks.")
161
+
162
+ labels = self._labels_getter(inputs)
163
+ if not isinstance(labels, torch.Tensor):
164
+ raise ValueError(f"The labels must be a tensor, but got {type(labels)} instead.")
165
+ elif labels.ndim != 1:
166
+ raise ValueError(
167
+ f"labels tensor should be of shape (batch_size,) " f"but got shape {labels.shape} instead."
168
+ )
169
+
170
+ params = {
171
+ "labels": labels,
172
+ "batch_size": labels.shape[0],
173
+ **self._get_params(
174
+ [inpt for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list) if needs_transform]
175
+ ),
176
+ }
177
+
178
+ # By default, the labels will be False inside needs_transform_list, since they are a torch.Tensor coming
179
+ # after an image or video. However, we need to handle them in _transform, so we make sure to set them to True
180
+ needs_transform_list[next(idx for idx, inpt in enumerate(flat_inputs) if inpt is labels)] = True
181
+ flat_outputs = [
182
+ self._transform(inpt, params) if needs_transform else inpt
183
+ for (inpt, needs_transform) in zip(flat_inputs, needs_transform_list)
184
+ ]
185
+
186
+ return tree_unflatten(flat_outputs, spec)
187
+
188
+ def _check_image_or_video(self, inpt: torch.Tensor, *, batch_size: int):
189
+ expected_num_dims = 5 if isinstance(inpt, tv_tensors.Video) else 4
190
+ if inpt.ndim != expected_num_dims:
191
+ raise ValueError(
192
+ f"Expected a batched input with {expected_num_dims} dims, but got {inpt.ndim} dimensions instead."
193
+ )
194
+ if inpt.shape[0] != batch_size:
195
+ raise ValueError(
196
+ f"The batch size of the image or video does not match the batch size of the labels: "
197
+ f"{inpt.shape[0]} != {batch_size}."
198
+ )
199
+
200
+ def _mixup_label(self, label: torch.Tensor, *, lam: float) -> torch.Tensor:
201
+ label = one_hot(label, num_classes=self.num_classes)
202
+ if not label.dtype.is_floating_point:
203
+ label = label.float()
204
+ return label.roll(1, 0).mul_(1.0 - lam).add_(label.mul(lam))
205
+
206
+
207
+ class MixUp(_BaseMixUpCutMix):
208
+ """Apply MixUp to the provided batch of images and labels.
209
+
210
+ Paper: `mixup: Beyond Empirical Risk Minimization <https://arxiv.org/abs/1710.09412>`_.
211
+
212
+ .. note::
213
+ This transform is meant to be used on **batches** of samples, not
214
+ individual images. See
215
+ :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage
216
+ examples.
217
+ The sample pairing is deterministic and done by matching consecutive
218
+ samples in the batch, so the batch needs to be shuffled (this is an
219
+ implementation detail, not a guaranteed convention.)
220
+
221
+ In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed
222
+ into a tensor of shape ``(batch_size, num_classes)``.
223
+
224
+ Args:
225
+ alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1.
226
+ num_classes (int): number of classes in the batch. Used for one-hot-encoding.
227
+ labels_getter (callable or "default", optional): indicates how to identify the labels in the input.
228
+ By default, this will pick the second parameter as the labels if it's a tensor. This covers the most
229
+ common scenario where this transform is called as ``MixUp()(imgs_batch, labels_batch)``.
230
+ It can also be a callable that takes the same input as the transform, and returns the labels.
231
+ """
232
+
233
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
234
+ return dict(lam=float(self._dist.sample(()))) # type: ignore[arg-type]
235
+
236
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
237
+ lam = params["lam"]
238
+
239
+ if inpt is params["labels"]:
240
+ return self._mixup_label(inpt, lam=lam)
241
+ elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt):
242
+ self._check_image_or_video(inpt, batch_size=params["batch_size"])
243
+
244
+ output = inpt.roll(1, 0).mul_(1.0 - lam).add_(inpt.mul(lam))
245
+
246
+ if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)):
247
+ output = tv_tensors.wrap(output, like=inpt)
248
+
249
+ return output
250
+ else:
251
+ return inpt
252
+
253
+
254
+ class CutMix(_BaseMixUpCutMix):
255
+ """Apply CutMix to the provided batch of images and labels.
256
+
257
+ Paper: `CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features
258
+ <https://arxiv.org/abs/1905.04899>`_.
259
+
260
+ .. note::
261
+ This transform is meant to be used on **batches** of samples, not
262
+ individual images. See
263
+ :ref:`sphx_glr_auto_examples_transforms_plot_cutmix_mixup.py` for detailed usage
264
+ examples.
265
+ The sample pairing is deterministic and done by matching consecutive
266
+ samples in the batch, so the batch needs to be shuffled (this is an
267
+ implementation detail, not a guaranteed convention.)
268
+
269
+ In the input, the labels are expected to be a tensor of shape ``(batch_size,)``. They will be transformed
270
+ into a tensor of shape ``(batch_size, num_classes)``.
271
+
272
+ Args:
273
+ alpha (float, optional): hyperparameter of the Beta distribution used for mixup. Default is 1.
274
+ num_classes (int): number of classes in the batch. Used for one-hot-encoding.
275
+ labels_getter (callable or "default", optional): indicates how to identify the labels in the input.
276
+ By default, this will pick the second parameter as the labels if it's a tensor. This covers the most
277
+ common scenario where this transform is called as ``CutMix()(imgs_batch, labels_batch)``.
278
+ It can also be a callable that takes the same input as the transform, and returns the labels.
279
+ """
280
+
281
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
282
+ lam = float(self._dist.sample(())) # type: ignore[arg-type]
283
+
284
+ H, W = query_size(flat_inputs)
285
+
286
+ r_x = torch.randint(W, size=(1,))
287
+ r_y = torch.randint(H, size=(1,))
288
+
289
+ r = 0.5 * math.sqrt(1.0 - lam)
290
+ r_w_half = int(r * W)
291
+ r_h_half = int(r * H)
292
+
293
+ x1 = int(torch.clamp(r_x - r_w_half, min=0))
294
+ y1 = int(torch.clamp(r_y - r_h_half, min=0))
295
+ x2 = int(torch.clamp(r_x + r_w_half, max=W))
296
+ y2 = int(torch.clamp(r_y + r_h_half, max=H))
297
+ box = (x1, y1, x2, y2)
298
+
299
+ lam_adjusted = float(1.0 - (x2 - x1) * (y2 - y1) / (W * H))
300
+
301
+ return dict(box=box, lam_adjusted=lam_adjusted)
302
+
303
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
304
+ if inpt is params["labels"]:
305
+ return self._mixup_label(inpt, lam=params["lam_adjusted"])
306
+ elif isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)) or is_pure_tensor(inpt):
307
+ self._check_image_or_video(inpt, batch_size=params["batch_size"])
308
+
309
+ x1, y1, x2, y2 = params["box"]
310
+ rolled = inpt.roll(1, 0)
311
+ output = inpt.clone()
312
+ output[..., y1:y2, x1:x2] = rolled[..., y1:y2, x1:x2]
313
+
314
+ if isinstance(inpt, (tv_tensors.Image, tv_tensors.Video)):
315
+ output = tv_tensors.wrap(output, like=inpt)
316
+
317
+ return output
318
+ else:
319
+ return inpt
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_auto_augment.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
3
+
4
+ import PIL.Image
5
+ import torch
6
+
7
+ from torch.utils._pytree import tree_flatten, tree_unflatten, TreeSpec
8
+ from torchvision import transforms as _transforms, tv_tensors
9
+ from torchvision.transforms import _functional_tensor as _FT
10
+ from torchvision.transforms.v2 import AutoAugmentPolicy, functional as F, InterpolationMode, Transform
11
+ from torchvision.transforms.v2.functional._geometry import _check_interpolation
12
+ from torchvision.transforms.v2.functional._meta import get_size
13
+ from torchvision.transforms.v2.functional._utils import _FillType, _FillTypeJIT
14
+
15
+ from ._utils import _get_fill, _setup_fill_arg, check_type, is_pure_tensor
16
+
17
+
18
+ ImageOrVideo = Union[torch.Tensor, PIL.Image.Image, tv_tensors.Image, tv_tensors.Video]
19
+
20
+
21
+ class _AutoAugmentBase(Transform):
22
+ def __init__(
23
+ self,
24
+ *,
25
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
26
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = None,
27
+ ) -> None:
28
+ super().__init__()
29
+ self.interpolation = _check_interpolation(interpolation)
30
+ self.fill = fill
31
+ self._fill = _setup_fill_arg(fill)
32
+
33
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
34
+ params = super()._extract_params_for_v1_transform()
35
+
36
+ if isinstance(params["fill"], dict):
37
+ raise ValueError(f"{type(self).__name__}() can not be scripted for when `fill` is a dictionary.")
38
+
39
+ return params
40
+
41
+ def _get_random_item(self, dct: Dict[str, Tuple[Callable, bool]]) -> Tuple[str, Tuple[Callable, bool]]:
42
+ keys = tuple(dct.keys())
43
+ key = keys[int(torch.randint(len(keys), ()))]
44
+ return key, dct[key]
45
+
46
+ def _flatten_and_extract_image_or_video(
47
+ self,
48
+ inputs: Any,
49
+ unsupported_types: Tuple[Type, ...] = (tv_tensors.BoundingBoxes, tv_tensors.Mask),
50
+ ) -> Tuple[Tuple[List[Any], TreeSpec, int], ImageOrVideo]:
51
+ flat_inputs, spec = tree_flatten(inputs if len(inputs) > 1 else inputs[0])
52
+ needs_transform_list = self._needs_transform_list(flat_inputs)
53
+
54
+ image_or_videos = []
55
+ for idx, (inpt, needs_transform) in enumerate(zip(flat_inputs, needs_transform_list)):
56
+ if needs_transform and check_type(
57
+ inpt,
58
+ (
59
+ tv_tensors.Image,
60
+ PIL.Image.Image,
61
+ is_pure_tensor,
62
+ tv_tensors.Video,
63
+ ),
64
+ ):
65
+ image_or_videos.append((idx, inpt))
66
+ elif isinstance(inpt, unsupported_types):
67
+ raise TypeError(f"Inputs of type {type(inpt).__name__} are not supported by {type(self).__name__}()")
68
+
69
+ if not image_or_videos:
70
+ raise TypeError("Found no image in the sample.")
71
+ if len(image_or_videos) > 1:
72
+ raise TypeError(
73
+ f"Auto augment transformations are only properly defined for a single image or video, "
74
+ f"but found {len(image_or_videos)}."
75
+ )
76
+
77
+ idx, image_or_video = image_or_videos[0]
78
+ return (flat_inputs, spec, idx), image_or_video
79
+
80
+ def _unflatten_and_insert_image_or_video(
81
+ self,
82
+ flat_inputs_with_spec: Tuple[List[Any], TreeSpec, int],
83
+ image_or_video: ImageOrVideo,
84
+ ) -> Any:
85
+ flat_inputs, spec, idx = flat_inputs_with_spec
86
+ flat_inputs[idx] = image_or_video
87
+ return tree_unflatten(flat_inputs, spec)
88
+
89
+ def _apply_image_or_video_transform(
90
+ self,
91
+ image: ImageOrVideo,
92
+ transform_id: str,
93
+ magnitude: float,
94
+ interpolation: Union[InterpolationMode, int],
95
+ fill: Dict[Union[Type, str], _FillTypeJIT],
96
+ ) -> ImageOrVideo:
97
+ fill_ = _get_fill(fill, type(image))
98
+
99
+ if transform_id == "Identity":
100
+ return image
101
+ elif transform_id == "ShearX":
102
+ # magnitude should be arctan(magnitude)
103
+ # official autoaug: (1, level, 0, 0, 1, 0)
104
+ # https://github.com/tensorflow/models/blob/dd02069717128186b88afa8d857ce57d17957f03/research/autoaugment/augmentation_transforms.py#L290
105
+ # compared to
106
+ # torchvision: (1, tan(level), 0, 0, 1, 0)
107
+ # https://github.com/pytorch/vision/blob/0c2373d0bba3499e95776e7936e207d8a1676e65/torchvision/transforms/functional.py#L976
108
+ return F.affine(
109
+ image,
110
+ angle=0.0,
111
+ translate=[0, 0],
112
+ scale=1.0,
113
+ shear=[math.degrees(math.atan(magnitude)), 0.0],
114
+ interpolation=interpolation,
115
+ fill=fill_,
116
+ center=[0, 0],
117
+ )
118
+ elif transform_id == "ShearY":
119
+ # magnitude should be arctan(magnitude)
120
+ # See above
121
+ return F.affine(
122
+ image,
123
+ angle=0.0,
124
+ translate=[0, 0],
125
+ scale=1.0,
126
+ shear=[0.0, math.degrees(math.atan(magnitude))],
127
+ interpolation=interpolation,
128
+ fill=fill_,
129
+ center=[0, 0],
130
+ )
131
+ elif transform_id == "TranslateX":
132
+ return F.affine(
133
+ image,
134
+ angle=0.0,
135
+ translate=[int(magnitude), 0],
136
+ scale=1.0,
137
+ interpolation=interpolation,
138
+ shear=[0.0, 0.0],
139
+ fill=fill_,
140
+ )
141
+ elif transform_id == "TranslateY":
142
+ return F.affine(
143
+ image,
144
+ angle=0.0,
145
+ translate=[0, int(magnitude)],
146
+ scale=1.0,
147
+ interpolation=interpolation,
148
+ shear=[0.0, 0.0],
149
+ fill=fill_,
150
+ )
151
+ elif transform_id == "Rotate":
152
+ return F.rotate(image, angle=magnitude, interpolation=interpolation, fill=fill_)
153
+ elif transform_id == "Brightness":
154
+ return F.adjust_brightness(image, brightness_factor=1.0 + magnitude)
155
+ elif transform_id == "Color":
156
+ return F.adjust_saturation(image, saturation_factor=1.0 + magnitude)
157
+ elif transform_id == "Contrast":
158
+ return F.adjust_contrast(image, contrast_factor=1.0 + magnitude)
159
+ elif transform_id == "Sharpness":
160
+ return F.adjust_sharpness(image, sharpness_factor=1.0 + magnitude)
161
+ elif transform_id == "Posterize":
162
+ return F.posterize(image, bits=int(magnitude))
163
+ elif transform_id == "Solarize":
164
+ bound = _FT._max_value(image.dtype) if isinstance(image, torch.Tensor) else 255.0
165
+ return F.solarize(image, threshold=bound * magnitude)
166
+ elif transform_id == "AutoContrast":
167
+ return F.autocontrast(image)
168
+ elif transform_id == "Equalize":
169
+ return F.equalize(image)
170
+ elif transform_id == "Invert":
171
+ return F.invert(image)
172
+ else:
173
+ raise ValueError(f"No transform available for {transform_id}")
174
+
175
+
176
+ class AutoAugment(_AutoAugmentBase):
177
+ r"""AutoAugment data augmentation method based on
178
+ `"AutoAugment: Learning Augmentation Strategies from Data" <https://arxiv.org/pdf/1805.09501.pdf>`_.
179
+
180
+ This transformation works on images and videos only.
181
+
182
+ If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected
183
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
184
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
185
+
186
+ Args:
187
+ policy (AutoAugmentPolicy, optional): Desired policy enum defined by
188
+ :class:`torchvision.transforms.autoaugment.AutoAugmentPolicy`. Default is ``AutoAugmentPolicy.IMAGENET``.
189
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
190
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
191
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
192
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
193
+ image. If given a number, the value is used for all bands respectively.
194
+ """
195
+ _v1_transform_cls = _transforms.AutoAugment
196
+
197
+ _AUGMENTATION_SPACE = {
198
+ "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True),
199
+ "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True),
200
+ "TranslateX": (
201
+ lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * width, num_bins),
202
+ True,
203
+ ),
204
+ "TranslateY": (
205
+ lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * height, num_bins),
206
+ True,
207
+ ),
208
+ "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True),
209
+ "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
210
+ "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
211
+ "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
212
+ "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
213
+ "Posterize": (
214
+ lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(),
215
+ False,
216
+ ),
217
+ "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False),
218
+ "AutoContrast": (lambda num_bins, height, width: None, False),
219
+ "Equalize": (lambda num_bins, height, width: None, False),
220
+ "Invert": (lambda num_bins, height, width: None, False),
221
+ }
222
+
223
+ def __init__(
224
+ self,
225
+ policy: AutoAugmentPolicy = AutoAugmentPolicy.IMAGENET,
226
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
227
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = None,
228
+ ) -> None:
229
+ super().__init__(interpolation=interpolation, fill=fill)
230
+ self.policy = policy
231
+ self._policies = self._get_policies(policy)
232
+
233
+ def _get_policies(
234
+ self, policy: AutoAugmentPolicy
235
+ ) -> List[Tuple[Tuple[str, float, Optional[int]], Tuple[str, float, Optional[int]]]]:
236
+ if policy == AutoAugmentPolicy.IMAGENET:
237
+ return [
238
+ (("Posterize", 0.4, 8), ("Rotate", 0.6, 9)),
239
+ (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)),
240
+ (("Equalize", 0.8, None), ("Equalize", 0.6, None)),
241
+ (("Posterize", 0.6, 7), ("Posterize", 0.6, 6)),
242
+ (("Equalize", 0.4, None), ("Solarize", 0.2, 4)),
243
+ (("Equalize", 0.4, None), ("Rotate", 0.8, 8)),
244
+ (("Solarize", 0.6, 3), ("Equalize", 0.6, None)),
245
+ (("Posterize", 0.8, 5), ("Equalize", 1.0, None)),
246
+ (("Rotate", 0.2, 3), ("Solarize", 0.6, 8)),
247
+ (("Equalize", 0.6, None), ("Posterize", 0.4, 6)),
248
+ (("Rotate", 0.8, 8), ("Color", 0.4, 0)),
249
+ (("Rotate", 0.4, 9), ("Equalize", 0.6, None)),
250
+ (("Equalize", 0.0, None), ("Equalize", 0.8, None)),
251
+ (("Invert", 0.6, None), ("Equalize", 1.0, None)),
252
+ (("Color", 0.6, 4), ("Contrast", 1.0, 8)),
253
+ (("Rotate", 0.8, 8), ("Color", 1.0, 2)),
254
+ (("Color", 0.8, 8), ("Solarize", 0.8, 7)),
255
+ (("Sharpness", 0.4, 7), ("Invert", 0.6, None)),
256
+ (("ShearX", 0.6, 5), ("Equalize", 1.0, None)),
257
+ (("Color", 0.4, 0), ("Equalize", 0.6, None)),
258
+ (("Equalize", 0.4, None), ("Solarize", 0.2, 4)),
259
+ (("Solarize", 0.6, 5), ("AutoContrast", 0.6, None)),
260
+ (("Invert", 0.6, None), ("Equalize", 1.0, None)),
261
+ (("Color", 0.6, 4), ("Contrast", 1.0, 8)),
262
+ (("Equalize", 0.8, None), ("Equalize", 0.6, None)),
263
+ ]
264
+ elif policy == AutoAugmentPolicy.CIFAR10:
265
+ return [
266
+ (("Invert", 0.1, None), ("Contrast", 0.2, 6)),
267
+ (("Rotate", 0.7, 2), ("TranslateX", 0.3, 9)),
268
+ (("Sharpness", 0.8, 1), ("Sharpness", 0.9, 3)),
269
+ (("ShearY", 0.5, 8), ("TranslateY", 0.7, 9)),
270
+ (("AutoContrast", 0.5, None), ("Equalize", 0.9, None)),
271
+ (("ShearY", 0.2, 7), ("Posterize", 0.3, 7)),
272
+ (("Color", 0.4, 3), ("Brightness", 0.6, 7)),
273
+ (("Sharpness", 0.3, 9), ("Brightness", 0.7, 9)),
274
+ (("Equalize", 0.6, None), ("Equalize", 0.5, None)),
275
+ (("Contrast", 0.6, 7), ("Sharpness", 0.6, 5)),
276
+ (("Color", 0.7, 7), ("TranslateX", 0.5, 8)),
277
+ (("Equalize", 0.3, None), ("AutoContrast", 0.4, None)),
278
+ (("TranslateY", 0.4, 3), ("Sharpness", 0.2, 6)),
279
+ (("Brightness", 0.9, 6), ("Color", 0.2, 8)),
280
+ (("Solarize", 0.5, 2), ("Invert", 0.0, None)),
281
+ (("Equalize", 0.2, None), ("AutoContrast", 0.6, None)),
282
+ (("Equalize", 0.2, None), ("Equalize", 0.6, None)),
283
+ (("Color", 0.9, 9), ("Equalize", 0.6, None)),
284
+ (("AutoContrast", 0.8, None), ("Solarize", 0.2, 8)),
285
+ (("Brightness", 0.1, 3), ("Color", 0.7, 0)),
286
+ (("Solarize", 0.4, 5), ("AutoContrast", 0.9, None)),
287
+ (("TranslateY", 0.9, 9), ("TranslateY", 0.7, 9)),
288
+ (("AutoContrast", 0.9, None), ("Solarize", 0.8, 3)),
289
+ (("Equalize", 0.8, None), ("Invert", 0.1, None)),
290
+ (("TranslateY", 0.7, 9), ("AutoContrast", 0.9, None)),
291
+ ]
292
+ elif policy == AutoAugmentPolicy.SVHN:
293
+ return [
294
+ (("ShearX", 0.9, 4), ("Invert", 0.2, None)),
295
+ (("ShearY", 0.9, 8), ("Invert", 0.7, None)),
296
+ (("Equalize", 0.6, None), ("Solarize", 0.6, 6)),
297
+ (("Invert", 0.9, None), ("Equalize", 0.6, None)),
298
+ (("Equalize", 0.6, None), ("Rotate", 0.9, 3)),
299
+ (("ShearX", 0.9, 4), ("AutoContrast", 0.8, None)),
300
+ (("ShearY", 0.9, 8), ("Invert", 0.4, None)),
301
+ (("ShearY", 0.9, 5), ("Solarize", 0.2, 6)),
302
+ (("Invert", 0.9, None), ("AutoContrast", 0.8, None)),
303
+ (("Equalize", 0.6, None), ("Rotate", 0.9, 3)),
304
+ (("ShearX", 0.9, 4), ("Solarize", 0.3, 3)),
305
+ (("ShearY", 0.8, 8), ("Invert", 0.7, None)),
306
+ (("Equalize", 0.9, None), ("TranslateY", 0.6, 6)),
307
+ (("Invert", 0.9, None), ("Equalize", 0.6, None)),
308
+ (("Contrast", 0.3, 3), ("Rotate", 0.8, 4)),
309
+ (("Invert", 0.8, None), ("TranslateY", 0.0, 2)),
310
+ (("ShearY", 0.7, 6), ("Solarize", 0.4, 8)),
311
+ (("Invert", 0.6, None), ("Rotate", 0.8, 4)),
312
+ (("ShearY", 0.3, 7), ("TranslateX", 0.9, 3)),
313
+ (("ShearX", 0.1, 6), ("Invert", 0.6, None)),
314
+ (("Solarize", 0.7, 2), ("TranslateY", 0.6, 7)),
315
+ (("ShearY", 0.8, 4), ("Invert", 0.8, None)),
316
+ (("ShearX", 0.7, 9), ("TranslateY", 0.8, 3)),
317
+ (("ShearY", 0.8, 5), ("AutoContrast", 0.7, None)),
318
+ (("ShearX", 0.7, 2), ("Invert", 0.1, None)),
319
+ ]
320
+ else:
321
+ raise ValueError(f"The provided policy {policy} is not recognized.")
322
+
323
+ def forward(self, *inputs: Any) -> Any:
324
+ flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs)
325
+ height, width = get_size(image_or_video)
326
+
327
+ policy = self._policies[int(torch.randint(len(self._policies), ()))]
328
+
329
+ for transform_id, probability, magnitude_idx in policy:
330
+ if not torch.rand(()) <= probability:
331
+ continue
332
+
333
+ magnitudes_fn, signed = self._AUGMENTATION_SPACE[transform_id]
334
+
335
+ magnitudes = magnitudes_fn(10, height, width)
336
+ if magnitudes is not None:
337
+ magnitude = float(magnitudes[magnitude_idx])
338
+ if signed and torch.rand(()) <= 0.5:
339
+ magnitude *= -1
340
+ else:
341
+ magnitude = 0.0
342
+
343
+ image_or_video = self._apply_image_or_video_transform(
344
+ image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill
345
+ )
346
+
347
+ return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video)
348
+
349
+
350
+ class RandAugment(_AutoAugmentBase):
351
+ r"""RandAugment data augmentation method based on
352
+ `"RandAugment: Practical automated data augmentation with a reduced search space"
353
+ <https://arxiv.org/abs/1909.13719>`_.
354
+
355
+ This transformation works on images and videos only.
356
+
357
+ If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected
358
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
359
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
360
+
361
+ Args:
362
+ num_ops (int, optional): Number of augmentation transformations to apply sequentially.
363
+ magnitude (int, optional): Magnitude for all the transformations.
364
+ num_magnitude_bins (int, optional): The number of different magnitude values.
365
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
366
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
367
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
368
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
369
+ image. If given a number, the value is used for all bands respectively.
370
+ """
371
+
372
+ _v1_transform_cls = _transforms.RandAugment
373
+ _AUGMENTATION_SPACE = {
374
+ "Identity": (lambda num_bins, height, width: None, False),
375
+ "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True),
376
+ "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True),
377
+ "TranslateX": (
378
+ lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * width, num_bins),
379
+ True,
380
+ ),
381
+ "TranslateY": (
382
+ lambda num_bins, height, width: torch.linspace(0.0, 150.0 / 331.0 * height, num_bins),
383
+ True,
384
+ ),
385
+ "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True),
386
+ "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
387
+ "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
388
+ "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
389
+ "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
390
+ "Posterize": (
391
+ lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(),
392
+ False,
393
+ ),
394
+ "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False),
395
+ "AutoContrast": (lambda num_bins, height, width: None, False),
396
+ "Equalize": (lambda num_bins, height, width: None, False),
397
+ }
398
+
399
+ def __init__(
400
+ self,
401
+ num_ops: int = 2,
402
+ magnitude: int = 9,
403
+ num_magnitude_bins: int = 31,
404
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
405
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = None,
406
+ ) -> None:
407
+ super().__init__(interpolation=interpolation, fill=fill)
408
+ self.num_ops = num_ops
409
+ self.magnitude = magnitude
410
+ self.num_magnitude_bins = num_magnitude_bins
411
+
412
+ def forward(self, *inputs: Any) -> Any:
413
+ flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs)
414
+ height, width = get_size(image_or_video)
415
+
416
+ for _ in range(self.num_ops):
417
+ transform_id, (magnitudes_fn, signed) = self._get_random_item(self._AUGMENTATION_SPACE)
418
+ magnitudes = magnitudes_fn(self.num_magnitude_bins, height, width)
419
+ if magnitudes is not None:
420
+ magnitude = float(magnitudes[self.magnitude])
421
+ if signed and torch.rand(()) <= 0.5:
422
+ magnitude *= -1
423
+ else:
424
+ magnitude = 0.0
425
+ image_or_video = self._apply_image_or_video_transform(
426
+ image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill
427
+ )
428
+
429
+ return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video)
430
+
431
+
432
+ class TrivialAugmentWide(_AutoAugmentBase):
433
+ r"""Dataset-independent data-augmentation with TrivialAugment Wide, as described in
434
+ `"TrivialAugment: Tuning-free Yet State-of-the-Art Data Augmentation" <https://arxiv.org/abs/2103.10158>`_.
435
+
436
+ This transformation works on images and videos only.
437
+
438
+ If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected
439
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
440
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
441
+
442
+ Args:
443
+ num_magnitude_bins (int, optional): The number of different magnitude values.
444
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
445
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
446
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
447
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
448
+ image. If given a number, the value is used for all bands respectively.
449
+ """
450
+
451
+ _v1_transform_cls = _transforms.TrivialAugmentWide
452
+ _AUGMENTATION_SPACE = {
453
+ "Identity": (lambda num_bins, height, width: None, False),
454
+ "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True),
455
+ "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True),
456
+ "TranslateX": (lambda num_bins, height, width: torch.linspace(0.0, 32.0, num_bins), True),
457
+ "TranslateY": (lambda num_bins, height, width: torch.linspace(0.0, 32.0, num_bins), True),
458
+ "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 135.0, num_bins), True),
459
+ "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True),
460
+ "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True),
461
+ "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True),
462
+ "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.99, num_bins), True),
463
+ "Posterize": (
464
+ lambda num_bins, height, width: (8 - (torch.arange(num_bins) / ((num_bins - 1) / 6))).round().int(),
465
+ False,
466
+ ),
467
+ "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False),
468
+ "AutoContrast": (lambda num_bins, height, width: None, False),
469
+ "Equalize": (lambda num_bins, height, width: None, False),
470
+ }
471
+
472
+ def __init__(
473
+ self,
474
+ num_magnitude_bins: int = 31,
475
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
476
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = None,
477
+ ):
478
+ super().__init__(interpolation=interpolation, fill=fill)
479
+ self.num_magnitude_bins = num_magnitude_bins
480
+
481
+ def forward(self, *inputs: Any) -> Any:
482
+ flat_inputs_with_spec, image_or_video = self._flatten_and_extract_image_or_video(inputs)
483
+ height, width = get_size(image_or_video)
484
+
485
+ transform_id, (magnitudes_fn, signed) = self._get_random_item(self._AUGMENTATION_SPACE)
486
+
487
+ magnitudes = magnitudes_fn(self.num_magnitude_bins, height, width)
488
+ if magnitudes is not None:
489
+ magnitude = float(magnitudes[int(torch.randint(self.num_magnitude_bins, ()))])
490
+ if signed and torch.rand(()) <= 0.5:
491
+ magnitude *= -1
492
+ else:
493
+ magnitude = 0.0
494
+
495
+ image_or_video = self._apply_image_or_video_transform(
496
+ image_or_video, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill
497
+ )
498
+ return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, image_or_video)
499
+
500
+
501
+ class AugMix(_AutoAugmentBase):
502
+ r"""AugMix data augmentation method based on
503
+ `"AugMix: A Simple Data Processing Method to Improve Robustness and Uncertainty" <https://arxiv.org/abs/1912.02781>`_.
504
+
505
+ This transformation works on images and videos only.
506
+
507
+ If the input is :class:`torch.Tensor`, it should be of type ``torch.uint8``, and it is expected
508
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
509
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
510
+
511
+ Args:
512
+ severity (int, optional): The severity of base augmentation operators. Default is ``3``.
513
+ mixture_width (int, optional): The number of augmentation chains. Default is ``3``.
514
+ chain_depth (int, optional): The depth of augmentation chains. A negative value denotes stochastic depth sampled from the interval [1, 3].
515
+ Default is ``-1``.
516
+ alpha (float, optional): The hyperparameter for the probability distributions. Default is ``1.0``.
517
+ all_ops (bool, optional): Use all operations (including brightness, contrast, color and sharpness). Default is ``True``.
518
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
519
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
520
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
521
+ fill (sequence or number, optional): Pixel fill value for the area outside the transformed
522
+ image. If given a number, the value is used for all bands respectively.
523
+ """
524
+
525
+ _v1_transform_cls = _transforms.AugMix
526
+
527
+ _PARTIAL_AUGMENTATION_SPACE = {
528
+ "ShearX": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True),
529
+ "ShearY": (lambda num_bins, height, width: torch.linspace(0.0, 0.3, num_bins), True),
530
+ "TranslateX": (lambda num_bins, height, width: torch.linspace(0.0, width / 3.0, num_bins), True),
531
+ "TranslateY": (lambda num_bins, height, width: torch.linspace(0.0, height / 3.0, num_bins), True),
532
+ "Rotate": (lambda num_bins, height, width: torch.linspace(0.0, 30.0, num_bins), True),
533
+ "Posterize": (
534
+ lambda num_bins, height, width: (4 - (torch.arange(num_bins) / ((num_bins - 1) / 4))).round().int(),
535
+ False,
536
+ ),
537
+ "Solarize": (lambda num_bins, height, width: torch.linspace(1.0, 0.0, num_bins), False),
538
+ "AutoContrast": (lambda num_bins, height, width: None, False),
539
+ "Equalize": (lambda num_bins, height, width: None, False),
540
+ }
541
+ _AUGMENTATION_SPACE: Dict[str, Tuple[Callable[[int, int, int], Optional[torch.Tensor]], bool]] = {
542
+ **_PARTIAL_AUGMENTATION_SPACE,
543
+ "Brightness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
544
+ "Color": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
545
+ "Contrast": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
546
+ "Sharpness": (lambda num_bins, height, width: torch.linspace(0.0, 0.9, num_bins), True),
547
+ }
548
+
549
+ def __init__(
550
+ self,
551
+ severity: int = 3,
552
+ mixture_width: int = 3,
553
+ chain_depth: int = -1,
554
+ alpha: float = 1.0,
555
+ all_ops: bool = True,
556
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
557
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = None,
558
+ ) -> None:
559
+ super().__init__(interpolation=interpolation, fill=fill)
560
+ self._PARAMETER_MAX = 10
561
+ if not (1 <= severity <= self._PARAMETER_MAX):
562
+ raise ValueError(f"The severity must be between [1, {self._PARAMETER_MAX}]. Got {severity} instead.")
563
+ self.severity = severity
564
+ self.mixture_width = mixture_width
565
+ self.chain_depth = chain_depth
566
+ self.alpha = alpha
567
+ self.all_ops = all_ops
568
+
569
+ def _sample_dirichlet(self, params: torch.Tensor) -> torch.Tensor:
570
+ # Must be on a separate method so that we can overwrite it in tests.
571
+ return torch._sample_dirichlet(params)
572
+
573
+ def forward(self, *inputs: Any) -> Any:
574
+ flat_inputs_with_spec, orig_image_or_video = self._flatten_and_extract_image_or_video(inputs)
575
+ height, width = get_size(orig_image_or_video)
576
+
577
+ if isinstance(orig_image_or_video, torch.Tensor):
578
+ image_or_video = orig_image_or_video
579
+ else: # isinstance(inpt, PIL.Image.Image):
580
+ image_or_video = F.pil_to_tensor(orig_image_or_video)
581
+
582
+ augmentation_space = self._AUGMENTATION_SPACE if self.all_ops else self._PARTIAL_AUGMENTATION_SPACE
583
+
584
+ orig_dims = list(image_or_video.shape)
585
+ expected_ndim = 5 if isinstance(orig_image_or_video, tv_tensors.Video) else 4
586
+ batch = image_or_video.reshape([1] * max(expected_ndim - image_or_video.ndim, 0) + orig_dims)
587
+ batch_dims = [batch.size(0)] + [1] * (batch.ndim - 1)
588
+
589
+ # Sample the beta weights for combining the original and augmented image or video. To get Beta, we use a
590
+ # Dirichlet with 2 parameters. The 1st column stores the weights of the original and the 2nd the ones of
591
+ # augmented image or video.
592
+ m = self._sample_dirichlet(
593
+ torch.tensor([self.alpha, self.alpha], device=batch.device).expand(batch_dims[0], -1)
594
+ )
595
+
596
+ # Sample the mixing weights and combine them with the ones sampled from Beta for the augmented images or videos.
597
+ combined_weights = self._sample_dirichlet(
598
+ torch.tensor([self.alpha] * self.mixture_width, device=batch.device).expand(batch_dims[0], -1)
599
+ ) * m[:, 1].reshape([batch_dims[0], -1])
600
+
601
+ mix = m[:, 0].reshape(batch_dims) * batch
602
+ for i in range(self.mixture_width):
603
+ aug = batch
604
+ depth = self.chain_depth if self.chain_depth > 0 else int(torch.randint(low=1, high=4, size=(1,)).item())
605
+ for _ in range(depth):
606
+ transform_id, (magnitudes_fn, signed) = self._get_random_item(augmentation_space)
607
+
608
+ magnitudes = magnitudes_fn(self._PARAMETER_MAX, height, width)
609
+ if magnitudes is not None:
610
+ magnitude = float(magnitudes[int(torch.randint(self.severity, ()))])
611
+ if signed and torch.rand(()) <= 0.5:
612
+ magnitude *= -1
613
+ else:
614
+ magnitude = 0.0
615
+
616
+ aug = self._apply_image_or_video_transform(
617
+ aug, transform_id, magnitude, interpolation=self.interpolation, fill=self._fill
618
+ )
619
+ mix.add_(combined_weights[:, i].reshape(batch_dims) * aug)
620
+ mix = mix.reshape(orig_dims).to(dtype=image_or_video.dtype)
621
+
622
+ if isinstance(orig_image_or_video, (tv_tensors.Image, tv_tensors.Video)):
623
+ mix = tv_tensors.wrap(mix, like=orig_image_or_video)
624
+ elif isinstance(orig_image_or_video, PIL.Image.Image):
625
+ mix = F.to_pil_image(mix)
626
+
627
+ return self._unflatten_and_insert_image_or_video(flat_inputs_with_spec, mix)
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_color.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
3
+
4
+ import torch
5
+ from torchvision import transforms as _transforms
6
+ from torchvision.transforms.v2 import functional as F, Transform
7
+
8
+ from ._transform import _RandomApplyTransform
9
+ from ._utils import query_chw
10
+
11
+
12
+ class Grayscale(Transform):
13
+ """Convert images or videos to grayscale.
14
+
15
+ If the input is a :class:`torch.Tensor`, it is expected
16
+ to have [..., 3 or 1, H, W] shape, where ... means an arbitrary number of leading dimensions
17
+
18
+ Args:
19
+ num_output_channels (int): (1 or 3) number of channels desired for output image
20
+ """
21
+
22
+ _v1_transform_cls = _transforms.Grayscale
23
+
24
+ def __init__(self, num_output_channels: int = 1):
25
+ super().__init__()
26
+ self.num_output_channels = num_output_channels
27
+
28
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
29
+ return self._call_kernel(F.rgb_to_grayscale, inpt, num_output_channels=self.num_output_channels)
30
+
31
+
32
+ class RandomGrayscale(_RandomApplyTransform):
33
+ """Randomly convert image or videos to grayscale with a probability of p (default 0.1).
34
+
35
+ If the input is a :class:`torch.Tensor`, it is expected to have [..., 3 or 1, H, W] shape,
36
+ where ... means an arbitrary number of leading dimensions
37
+
38
+ The output has the same number of channels as the input.
39
+
40
+ Args:
41
+ p (float): probability that image should be converted to grayscale.
42
+ """
43
+
44
+ _v1_transform_cls = _transforms.RandomGrayscale
45
+
46
+ def __init__(self, p: float = 0.1) -> None:
47
+ super().__init__(p=p)
48
+
49
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
50
+ num_input_channels, *_ = query_chw(flat_inputs)
51
+ return dict(num_input_channels=num_input_channels)
52
+
53
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
54
+ return self._call_kernel(F.rgb_to_grayscale, inpt, num_output_channels=params["num_input_channels"])
55
+
56
+
57
+ class ColorJitter(Transform):
58
+ """Randomly change the brightness, contrast, saturation and hue of an image or video.
59
+
60
+ If the input is a :class:`torch.Tensor`, it is expected
61
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
62
+ If img is PIL Image, mode "1", "I", "F" and modes with transparency (alpha channel) are not supported.
63
+
64
+ Args:
65
+ brightness (float or tuple of float (min, max)): How much to jitter brightness.
66
+ brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
67
+ or the given [min, max]. Should be non negative numbers.
68
+ contrast (float or tuple of float (min, max)): How much to jitter contrast.
69
+ contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
70
+ or the given [min, max]. Should be non-negative numbers.
71
+ saturation (float or tuple of float (min, max)): How much to jitter saturation.
72
+ saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
73
+ or the given [min, max]. Should be non negative numbers.
74
+ hue (float or tuple of float (min, max)): How much to jitter hue.
75
+ hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
76
+ Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
77
+ To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space;
78
+ thus it does not work if you normalize your image to an interval with negative values,
79
+ or use an interpolation that generates negative values before using this function.
80
+ """
81
+
82
+ _v1_transform_cls = _transforms.ColorJitter
83
+
84
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
85
+ return {attr: value or 0 for attr, value in super()._extract_params_for_v1_transform().items()}
86
+
87
+ def __init__(
88
+ self,
89
+ brightness: Optional[Union[float, Sequence[float]]] = None,
90
+ contrast: Optional[Union[float, Sequence[float]]] = None,
91
+ saturation: Optional[Union[float, Sequence[float]]] = None,
92
+ hue: Optional[Union[float, Sequence[float]]] = None,
93
+ ) -> None:
94
+ super().__init__()
95
+ self.brightness = self._check_input(brightness, "brightness")
96
+ self.contrast = self._check_input(contrast, "contrast")
97
+ self.saturation = self._check_input(saturation, "saturation")
98
+ self.hue = self._check_input(hue, "hue", center=0, bound=(-0.5, 0.5), clip_first_on_zero=False)
99
+
100
+ def _check_input(
101
+ self,
102
+ value: Optional[Union[float, Sequence[float]]],
103
+ name: str,
104
+ center: float = 1.0,
105
+ bound: Tuple[float, float] = (0, float("inf")),
106
+ clip_first_on_zero: bool = True,
107
+ ) -> Optional[Tuple[float, float]]:
108
+ if value is None:
109
+ return None
110
+
111
+ if isinstance(value, (int, float)):
112
+ if value < 0:
113
+ raise ValueError(f"If {name} is a single number, it must be non negative.")
114
+ value = [center - value, center + value]
115
+ if clip_first_on_zero:
116
+ value[0] = max(value[0], 0.0)
117
+ elif isinstance(value, collections.abc.Sequence) and len(value) == 2:
118
+ value = [float(v) for v in value]
119
+ else:
120
+ raise TypeError(f"{name}={value} should be a single number or a sequence with length 2.")
121
+
122
+ if not bound[0] <= value[0] <= value[1] <= bound[1]:
123
+ raise ValueError(f"{name} values should be between {bound}, but got {value}.")
124
+
125
+ return None if value[0] == value[1] == center else (float(value[0]), float(value[1]))
126
+
127
+ @staticmethod
128
+ def _generate_value(left: float, right: float) -> float:
129
+ return torch.empty(1).uniform_(left, right).item()
130
+
131
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
132
+ fn_idx = torch.randperm(4)
133
+
134
+ b = None if self.brightness is None else self._generate_value(self.brightness[0], self.brightness[1])
135
+ c = None if self.contrast is None else self._generate_value(self.contrast[0], self.contrast[1])
136
+ s = None if self.saturation is None else self._generate_value(self.saturation[0], self.saturation[1])
137
+ h = None if self.hue is None else self._generate_value(self.hue[0], self.hue[1])
138
+
139
+ return dict(fn_idx=fn_idx, brightness_factor=b, contrast_factor=c, saturation_factor=s, hue_factor=h)
140
+
141
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
142
+ output = inpt
143
+ brightness_factor = params["brightness_factor"]
144
+ contrast_factor = params["contrast_factor"]
145
+ saturation_factor = params["saturation_factor"]
146
+ hue_factor = params["hue_factor"]
147
+ for fn_id in params["fn_idx"]:
148
+ if fn_id == 0 and brightness_factor is not None:
149
+ output = self._call_kernel(F.adjust_brightness, output, brightness_factor=brightness_factor)
150
+ elif fn_id == 1 and contrast_factor is not None:
151
+ output = self._call_kernel(F.adjust_contrast, output, contrast_factor=contrast_factor)
152
+ elif fn_id == 2 and saturation_factor is not None:
153
+ output = self._call_kernel(F.adjust_saturation, output, saturation_factor=saturation_factor)
154
+ elif fn_id == 3 and hue_factor is not None:
155
+ output = self._call_kernel(F.adjust_hue, output, hue_factor=hue_factor)
156
+ return output
157
+
158
+
159
+ class RandomChannelPermutation(Transform):
160
+ """Randomly permute the channels of an image or video"""
161
+
162
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
163
+ num_channels, *_ = query_chw(flat_inputs)
164
+ return dict(permutation=torch.randperm(num_channels))
165
+
166
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
167
+ return self._call_kernel(F.permute_channels, inpt, params["permutation"])
168
+
169
+
170
+ class RandomPhotometricDistort(Transform):
171
+ """Randomly distorts the image or video as used in `SSD: Single Shot
172
+ MultiBox Detector <https://arxiv.org/abs/1512.02325>`_.
173
+
174
+ This transform relies on :class:`~torchvision.transforms.v2.ColorJitter`
175
+ under the hood to adjust the contrast, saturation, hue, brightness, and also
176
+ randomly permutes channels.
177
+
178
+ Args:
179
+ brightness (tuple of float (min, max), optional): How much to jitter brightness.
180
+ brightness_factor is chosen uniformly from [min, max]. Should be non negative numbers.
181
+ contrast (tuple of float (min, max), optional): How much to jitter contrast.
182
+ contrast_factor is chosen uniformly from [min, max]. Should be non-negative numbers.
183
+ saturation (tuple of float (min, max), optional): How much to jitter saturation.
184
+ saturation_factor is chosen uniformly from [min, max]. Should be non negative numbers.
185
+ hue (tuple of float (min, max), optional): How much to jitter hue.
186
+ hue_factor is chosen uniformly from [min, max]. Should have -0.5 <= min <= max <= 0.5.
187
+ To jitter hue, the pixel values of the input image has to be non-negative for conversion to HSV space;
188
+ thus it does not work if you normalize your image to an interval with negative values,
189
+ or use an interpolation that generates negative values before using this function.
190
+ p (float, optional) probability each distortion operation (contrast, saturation, ...) to be applied.
191
+ Default is 0.5.
192
+ """
193
+
194
+ def __init__(
195
+ self,
196
+ brightness: Tuple[float, float] = (0.875, 1.125),
197
+ contrast: Tuple[float, float] = (0.5, 1.5),
198
+ saturation: Tuple[float, float] = (0.5, 1.5),
199
+ hue: Tuple[float, float] = (-0.05, 0.05),
200
+ p: float = 0.5,
201
+ ):
202
+ super().__init__()
203
+ self.brightness = brightness
204
+ self.contrast = contrast
205
+ self.hue = hue
206
+ self.saturation = saturation
207
+ self.p = p
208
+
209
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
210
+ num_channels, *_ = query_chw(flat_inputs)
211
+ params: Dict[str, Any] = {
212
+ key: ColorJitter._generate_value(range[0], range[1]) if torch.rand(1) < self.p else None
213
+ for key, range in [
214
+ ("brightness_factor", self.brightness),
215
+ ("contrast_factor", self.contrast),
216
+ ("saturation_factor", self.saturation),
217
+ ("hue_factor", self.hue),
218
+ ]
219
+ }
220
+ params["contrast_before"] = bool(torch.rand(()) < 0.5)
221
+ params["channel_permutation"] = torch.randperm(num_channels) if torch.rand(1) < self.p else None
222
+ return params
223
+
224
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
225
+ if params["brightness_factor"] is not None:
226
+ inpt = self._call_kernel(F.adjust_brightness, inpt, brightness_factor=params["brightness_factor"])
227
+ if params["contrast_factor"] is not None and params["contrast_before"]:
228
+ inpt = self._call_kernel(F.adjust_contrast, inpt, contrast_factor=params["contrast_factor"])
229
+ if params["saturation_factor"] is not None:
230
+ inpt = self._call_kernel(F.adjust_saturation, inpt, saturation_factor=params["saturation_factor"])
231
+ if params["hue_factor"] is not None:
232
+ inpt = self._call_kernel(F.adjust_hue, inpt, hue_factor=params["hue_factor"])
233
+ if params["contrast_factor"] is not None and not params["contrast_before"]:
234
+ inpt = self._call_kernel(F.adjust_contrast, inpt, contrast_factor=params["contrast_factor"])
235
+ if params["channel_permutation"] is not None:
236
+ inpt = self._call_kernel(F.permute_channels, inpt, permutation=params["channel_permutation"])
237
+ return inpt
238
+
239
+
240
+ class RandomEqualize(_RandomApplyTransform):
241
+ """Equalize the histogram of the given image or video with a given probability.
242
+
243
+ If the input is a :class:`torch.Tensor`, it is expected
244
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
245
+ If img is PIL Image, it is expected to be in mode "P", "L" or "RGB".
246
+
247
+ Args:
248
+ p (float): probability of the image being equalized. Default value is 0.5
249
+ """
250
+
251
+ _v1_transform_cls = _transforms.RandomEqualize
252
+
253
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
254
+ return self._call_kernel(F.equalize, inpt)
255
+
256
+
257
+ class RandomInvert(_RandomApplyTransform):
258
+ """Inverts the colors of the given image or video with a given probability.
259
+
260
+ If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
261
+ where ... means it can have an arbitrary number of leading dimensions.
262
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
263
+
264
+ Args:
265
+ p (float): probability of the image being color inverted. Default value is 0.5
266
+ """
267
+
268
+ _v1_transform_cls = _transforms.RandomInvert
269
+
270
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
271
+ return self._call_kernel(F.invert, inpt)
272
+
273
+
274
+ class RandomPosterize(_RandomApplyTransform):
275
+ """Posterize the image or video with a given probability by reducing the
276
+ number of bits for each color channel.
277
+
278
+ If the input is a :class:`torch.Tensor`, it should be of type torch.uint8,
279
+ and it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
280
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
281
+
282
+ Args:
283
+ bits (int): number of bits to keep for each channel (0-8)
284
+ p (float): probability of the image being posterized. Default value is 0.5
285
+ """
286
+
287
+ _v1_transform_cls = _transforms.RandomPosterize
288
+
289
+ def __init__(self, bits: int, p: float = 0.5) -> None:
290
+ super().__init__(p=p)
291
+ self.bits = bits
292
+
293
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
294
+ return self._call_kernel(F.posterize, inpt, bits=self.bits)
295
+
296
+
297
+ class RandomSolarize(_RandomApplyTransform):
298
+ """Solarize the image or video with a given probability by inverting all pixel
299
+ values above a threshold.
300
+
301
+ If img is a Tensor, it is expected to be in [..., 1 or 3, H, W] format,
302
+ where ... means it can have an arbitrary number of leading dimensions.
303
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
304
+
305
+ Args:
306
+ threshold (float): all pixels equal or above this value are inverted.
307
+ p (float): probability of the image being solarized. Default value is 0.5
308
+ """
309
+
310
+ _v1_transform_cls = _transforms.RandomSolarize
311
+
312
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
313
+ params = super()._extract_params_for_v1_transform()
314
+ params["threshold"] = float(params["threshold"])
315
+ return params
316
+
317
+ def __init__(self, threshold: float, p: float = 0.5) -> None:
318
+ super().__init__(p=p)
319
+ self.threshold = threshold
320
+
321
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
322
+ return self._call_kernel(F.solarize, inpt, threshold=self.threshold)
323
+
324
+
325
+ class RandomAutocontrast(_RandomApplyTransform):
326
+ """Autocontrast the pixels of the given image or video with a given probability.
327
+
328
+ If the input is a :class:`torch.Tensor`, it is expected
329
+ to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
330
+ If img is PIL Image, it is expected to be in mode "L" or "RGB".
331
+
332
+ Args:
333
+ p (float): probability of the image being autocontrasted. Default value is 0.5
334
+ """
335
+
336
+ _v1_transform_cls = _transforms.RandomAutocontrast
337
+
338
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
339
+ return self._call_kernel(F.autocontrast, inpt)
340
+
341
+
342
+ class RandomAdjustSharpness(_RandomApplyTransform):
343
+ """Adjust the sharpness of the image or video with a given probability.
344
+
345
+ If the input is a :class:`torch.Tensor`,
346
+ it is expected to have [..., 1 or 3, H, W] shape, where ... means an arbitrary number of leading dimensions.
347
+
348
+ Args:
349
+ sharpness_factor (float): How much to adjust the sharpness. Can be
350
+ any non-negative number. 0 gives a blurred image, 1 gives the
351
+ original image while 2 increases the sharpness by a factor of 2.
352
+ p (float): probability of the image being sharpened. Default value is 0.5
353
+ """
354
+
355
+ _v1_transform_cls = _transforms.RandomAdjustSharpness
356
+
357
+ def __init__(self, sharpness_factor: float, p: float = 0.5) -> None:
358
+ super().__init__(p=p)
359
+ self.sharpness_factor = sharpness_factor
360
+
361
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
362
+ return self._call_kernel(F.adjust_sharpness, inpt, sharpness_factor=self.sharpness_factor)
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_container.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Callable, Dict, List, Optional, Sequence, Union
2
+
3
+ import torch
4
+
5
+ from torch import nn
6
+ from torchvision import transforms as _transforms
7
+ from torchvision.transforms.v2 import Transform
8
+
9
+
10
+ class Compose(Transform):
11
+ """Composes several transforms together.
12
+
13
+ This transform does not support torchscript.
14
+ Please, see the note below.
15
+
16
+ Args:
17
+ transforms (list of ``Transform`` objects): list of transforms to compose.
18
+
19
+ Example:
20
+ >>> transforms.Compose([
21
+ >>> transforms.CenterCrop(10),
22
+ >>> transforms.PILToTensor(),
23
+ >>> transforms.ConvertImageDtype(torch.float),
24
+ >>> ])
25
+
26
+ .. note::
27
+ In order to script the transformations, please use ``torch.nn.Sequential`` as below.
28
+
29
+ >>> transforms = torch.nn.Sequential(
30
+ >>> transforms.CenterCrop(10),
31
+ >>> transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225)),
32
+ >>> )
33
+ >>> scripted_transforms = torch.jit.script(transforms)
34
+
35
+ Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
36
+ `lambda` functions or ``PIL.Image``.
37
+
38
+ """
39
+
40
+ def __init__(self, transforms: Sequence[Callable]) -> None:
41
+ super().__init__()
42
+ if not isinstance(transforms, Sequence):
43
+ raise TypeError("Argument transforms should be a sequence of callables")
44
+ elif not transforms:
45
+ raise ValueError("Pass at least one transform")
46
+ self.transforms = transforms
47
+
48
+ def forward(self, *inputs: Any) -> Any:
49
+ needs_unpacking = len(inputs) > 1
50
+ for transform in self.transforms:
51
+ outputs = transform(*inputs)
52
+ inputs = outputs if needs_unpacking else (outputs,)
53
+ return outputs
54
+
55
+ def extra_repr(self) -> str:
56
+ format_string = []
57
+ for t in self.transforms:
58
+ format_string.append(f" {t}")
59
+ return "\n".join(format_string)
60
+
61
+
62
+ class RandomApply(Transform):
63
+ """Apply randomly a list of transformations with a given probability.
64
+
65
+ .. note::
66
+ In order to script the transformation, please use ``torch.nn.ModuleList`` as input instead of list/tuple of
67
+ transforms as shown below:
68
+
69
+ >>> transforms = transforms.RandomApply(torch.nn.ModuleList([
70
+ >>> transforms.ColorJitter(),
71
+ >>> ]), p=0.3)
72
+ >>> scripted_transforms = torch.jit.script(transforms)
73
+
74
+ Make sure to use only scriptable transformations, i.e. that work with ``torch.Tensor``, does not require
75
+ `lambda` functions or ``PIL.Image``.
76
+
77
+ Args:
78
+ transforms (sequence or torch.nn.Module): list of transformations
79
+ p (float): probability of applying the list of transforms
80
+ """
81
+
82
+ _v1_transform_cls = _transforms.RandomApply
83
+
84
+ def __init__(self, transforms: Union[Sequence[Callable], nn.ModuleList], p: float = 0.5) -> None:
85
+ super().__init__()
86
+
87
+ if not isinstance(transforms, (Sequence, nn.ModuleList)):
88
+ raise TypeError("Argument transforms should be a sequence of callables or a `nn.ModuleList`")
89
+ self.transforms = transforms
90
+
91
+ if not (0.0 <= p <= 1.0):
92
+ raise ValueError("`p` should be a floating point value in the interval [0.0, 1.0].")
93
+ self.p = p
94
+
95
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
96
+ return {"transforms": self.transforms, "p": self.p}
97
+
98
+ def forward(self, *inputs: Any) -> Any:
99
+ needs_unpacking = len(inputs) > 1
100
+
101
+ if torch.rand(1) >= self.p:
102
+ return inputs if needs_unpacking else inputs[0]
103
+
104
+ for transform in self.transforms:
105
+ outputs = transform(*inputs)
106
+ inputs = outputs if needs_unpacking else (outputs,)
107
+ return outputs
108
+
109
+ def extra_repr(self) -> str:
110
+ format_string = []
111
+ for t in self.transforms:
112
+ format_string.append(f" {t}")
113
+ return "\n".join(format_string)
114
+
115
+
116
+ class RandomChoice(Transform):
117
+ """Apply single transformation randomly picked from a list.
118
+
119
+ This transform does not support torchscript.
120
+
121
+ Args:
122
+ transforms (sequence or torch.nn.Module): list of transformations
123
+ p (list of floats or None, optional): probability of each transform being picked.
124
+ If ``p`` doesn't sum to 1, it is automatically normalized. If ``None``
125
+ (default), all transforms have the same probability.
126
+ """
127
+
128
+ def __init__(
129
+ self,
130
+ transforms: Sequence[Callable],
131
+ p: Optional[List[float]] = None,
132
+ ) -> None:
133
+ if not isinstance(transforms, Sequence):
134
+ raise TypeError("Argument transforms should be a sequence of callables")
135
+
136
+ if p is None:
137
+ p = [1] * len(transforms)
138
+ elif len(p) != len(transforms):
139
+ raise ValueError(f"Length of p doesn't match the number of transforms: {len(p)} != {len(transforms)}")
140
+
141
+ super().__init__()
142
+
143
+ self.transforms = transforms
144
+ total = sum(p)
145
+ self.p = [prob / total for prob in p]
146
+
147
+ def forward(self, *inputs: Any) -> Any:
148
+ idx = int(torch.multinomial(torch.tensor(self.p), 1))
149
+ transform = self.transforms[idx]
150
+ return transform(*inputs)
151
+
152
+
153
+ class RandomOrder(Transform):
154
+ """Apply a list of transformations in a random order.
155
+
156
+ This transform does not support torchscript.
157
+
158
+ Args:
159
+ transforms (sequence or torch.nn.Module): list of transformations
160
+ """
161
+
162
+ def __init__(self, transforms: Sequence[Callable]) -> None:
163
+ if not isinstance(transforms, Sequence):
164
+ raise TypeError("Argument transforms should be a sequence of callables")
165
+ super().__init__()
166
+ self.transforms = transforms
167
+
168
+ def forward(self, *inputs: Any) -> Any:
169
+ needs_unpacking = len(inputs) > 1
170
+ for idx in torch.randperm(len(self.transforms)):
171
+ transform = self.transforms[idx]
172
+ outputs = transform(*inputs)
173
+ inputs = outputs if needs_unpacking else (outputs,)
174
+ return outputs
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_deprecated.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import warnings
2
+ from typing import Any, Dict, Union
3
+
4
+ import numpy as np
5
+ import PIL.Image
6
+ import torch
7
+ from torchvision.transforms import functional as _F
8
+
9
+ from torchvision.transforms.v2 import Transform
10
+
11
+
12
+ class ToTensor(Transform):
13
+ """[DEPRECATED] Use ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`` instead.
14
+
15
+ Convert a PIL Image or ndarray to tensor and scale the values accordingly.
16
+
17
+ .. warning::
18
+ :class:`v2.ToTensor` is deprecated and will be removed in a future release.
19
+ Please use instead ``v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])``.
20
+
21
+ This transform does not support torchscript.
22
+
23
+
24
+ Converts a PIL Image or numpy.ndarray (H x W x C) in the range
25
+ [0, 255] to a torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0]
26
+ if the PIL Image belongs to one of the modes (L, LA, P, I, F, RGB, YCbCr, RGBA, CMYK, 1)
27
+ or if the numpy.ndarray has dtype = np.uint8
28
+
29
+ In the other cases, tensors are returned without scaling.
30
+
31
+ .. note::
32
+ Because the input image is scaled to [0.0, 1.0], this transformation should not be used when
33
+ transforming target image masks. See the `references`_ for implementing the transforms for image masks.
34
+
35
+ .. _references: https://github.com/pytorch/vision/tree/main/references/segmentation
36
+ """
37
+
38
+ _transformed_types = (PIL.Image.Image, np.ndarray)
39
+
40
+ def __init__(self) -> None:
41
+ warnings.warn(
42
+ "The transform `ToTensor()` is deprecated and will be removed in a future release. "
43
+ "Instead, please use `v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True)])`."
44
+ )
45
+ super().__init__()
46
+
47
+ def _transform(self, inpt: Union[PIL.Image.Image, np.ndarray], params: Dict[str, Any]) -> torch.Tensor:
48
+ return _F.to_tensor(inpt)
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_geometry.py ADDED
@@ -0,0 +1,1401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ import numbers
3
+ import warnings
4
+ from typing import Any, Callable, Dict, List, Literal, Optional, Sequence, Tuple, Type, Union
5
+
6
+ import PIL.Image
7
+ import torch
8
+
9
+ from torchvision import transforms as _transforms, tv_tensors
10
+ from torchvision.ops.boxes import box_iou
11
+ from torchvision.transforms.functional import _get_perspective_coeffs
12
+ from torchvision.transforms.v2 import functional as F, InterpolationMode, Transform
13
+ from torchvision.transforms.v2.functional._utils import _FillType
14
+
15
+ from ._transform import _RandomApplyTransform
16
+ from ._utils import (
17
+ _check_padding_arg,
18
+ _check_padding_mode_arg,
19
+ _check_sequence_input,
20
+ _get_fill,
21
+ _setup_angle,
22
+ _setup_fill_arg,
23
+ _setup_number_or_seq,
24
+ _setup_size,
25
+ get_bounding_boxes,
26
+ has_all,
27
+ has_any,
28
+ is_pure_tensor,
29
+ query_size,
30
+ )
31
+
32
+
33
+ class RandomHorizontalFlip(_RandomApplyTransform):
34
+ """Horizontally flip the input with a given probability.
35
+
36
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
37
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
38
+ it can have arbitrary number of leading batch dimensions. For example,
39
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
40
+
41
+ Args:
42
+ p (float, optional): probability of the input being flipped. Default value is 0.5
43
+ """
44
+
45
+ _v1_transform_cls = _transforms.RandomHorizontalFlip
46
+
47
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
48
+ return self._call_kernel(F.horizontal_flip, inpt)
49
+
50
+
51
+ class RandomVerticalFlip(_RandomApplyTransform):
52
+ """Vertically flip the input with a given probability.
53
+
54
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
55
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
56
+ it can have arbitrary number of leading batch dimensions. For example,
57
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
58
+
59
+ Args:
60
+ p (float, optional): probability of the input being flipped. Default value is 0.5
61
+ """
62
+
63
+ _v1_transform_cls = _transforms.RandomVerticalFlip
64
+
65
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
66
+ return self._call_kernel(F.vertical_flip, inpt)
67
+
68
+
69
+ class Resize(Transform):
70
+ """Resize the input to the given size.
71
+
72
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
73
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
74
+ it can have arbitrary number of leading batch dimensions. For example,
75
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
76
+
77
+ Args:
78
+ size (sequence or int): Desired output size. If size is a sequence like
79
+ (h, w), output size will be matched to this. If size is an int,
80
+ smaller edge of the image will be matched to this number.
81
+ i.e, if height > width, then image will be rescaled to
82
+ (size * height / width, size).
83
+
84
+ .. note::
85
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
86
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
87
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
88
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
89
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
90
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
91
+ max_size (int, optional): The maximum allowed for the longer edge of
92
+ the resized image. If the longer edge of the image is greater
93
+ than ``max_size`` after being resized according to ``size``,
94
+ ``size`` will be overruled so that the longer edge is equal to
95
+ ``max_size``.
96
+ As a result, the smaller edge may be shorter than ``size``. This
97
+ is only supported if ``size`` is an int (or a sequence of length
98
+ 1 in torchscript mode).
99
+ antialias (bool, optional): Whether to apply antialiasing.
100
+ It only affects **tensors** with bilinear or bicubic modes and it is
101
+ ignored otherwise: on PIL images, antialiasing is always applied on
102
+ bilinear or bicubic modes; on other modes (for PIL images and
103
+ tensors), antialiasing makes no sense and this parameter is ignored.
104
+ Possible values are:
105
+
106
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
107
+ Other mode aren't affected. This is probably what you want to use.
108
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
109
+ images are still antialiased on bilinear or bicubic modes, because
110
+ PIL doesn't support no antialias.
111
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
112
+ PIL images. This value exists for legacy reasons and you probably
113
+ don't want to use it unless you really know what you are doing.
114
+
115
+ The default value changed from ``None`` to ``True`` in
116
+ v0.17, for the PIL and Tensor backends to be consistent.
117
+ """
118
+
119
+ _v1_transform_cls = _transforms.Resize
120
+
121
+ def __init__(
122
+ self,
123
+ size: Union[int, Sequence[int]],
124
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
125
+ max_size: Optional[int] = None,
126
+ antialias: Optional[bool] = True,
127
+ ) -> None:
128
+ super().__init__()
129
+
130
+ if isinstance(size, int):
131
+ size = [size]
132
+ elif isinstance(size, Sequence) and len(size) in {1, 2}:
133
+ size = list(size)
134
+ else:
135
+ raise ValueError(
136
+ f"size can either be an integer or a sequence of one or two integers, but got {size} instead."
137
+ )
138
+ self.size = size
139
+
140
+ self.interpolation = interpolation
141
+ self.max_size = max_size
142
+ self.antialias = antialias
143
+
144
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
145
+ return self._call_kernel(
146
+ F.resize,
147
+ inpt,
148
+ self.size,
149
+ interpolation=self.interpolation,
150
+ max_size=self.max_size,
151
+ antialias=self.antialias,
152
+ )
153
+
154
+
155
+ class CenterCrop(Transform):
156
+ """Crop the input at the center.
157
+
158
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
159
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
160
+ it can have arbitrary number of leading batch dimensions. For example,
161
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
162
+
163
+ If image size is smaller than output size along any edge, image is padded with 0 and then center cropped.
164
+
165
+ Args:
166
+ size (sequence or int): Desired output size of the crop. If size is an
167
+ int instead of sequence like (h, w), a square crop (size, size) is
168
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
169
+ """
170
+
171
+ _v1_transform_cls = _transforms.CenterCrop
172
+
173
+ def __init__(self, size: Union[int, Sequence[int]]):
174
+ super().__init__()
175
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
176
+
177
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
178
+ return self._call_kernel(F.center_crop, inpt, output_size=self.size)
179
+
180
+
181
+ class RandomResizedCrop(Transform):
182
+ """Crop a random portion of the input and resize it to a given size.
183
+
184
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
185
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
186
+ it can have arbitrary number of leading batch dimensions. For example,
187
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
188
+
189
+ A crop of the original input is made: the crop has a random area (H * W)
190
+ and a random aspect ratio. This crop is finally resized to the given
191
+ size. This is popularly used to train the Inception networks.
192
+
193
+ Args:
194
+ size (int or sequence): expected output size of the crop, for each edge. If size is an
195
+ int instead of sequence like (h, w), a square output size ``(size, size)`` is
196
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
197
+
198
+ .. note::
199
+ In torchscript mode size as single int is not supported, use a sequence of length 1: ``[size, ]``.
200
+ scale (tuple of float, optional): Specifies the lower and upper bounds for the random area of the crop,
201
+ before resizing. The scale is defined with respect to the area of the original image.
202
+ ratio (tuple of float, optional): lower and upper bounds for the random aspect ratio of the crop, before
203
+ resizing.
204
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
205
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
206
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
207
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
208
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
209
+ antialias (bool, optional): Whether to apply antialiasing.
210
+ It only affects **tensors** with bilinear or bicubic modes and it is
211
+ ignored otherwise: on PIL images, antialiasing is always applied on
212
+ bilinear or bicubic modes; on other modes (for PIL images and
213
+ tensors), antialiasing makes no sense and this parameter is ignored.
214
+ Possible values are:
215
+
216
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
217
+ Other mode aren't affected. This is probably what you want to use.
218
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
219
+ images are still antialiased on bilinear or bicubic modes, because
220
+ PIL doesn't support no antialias.
221
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
222
+ PIL images. This value exists for legacy reasons and you probably
223
+ don't want to use it unless you really know what you are doing.
224
+
225
+ The default value changed from ``None`` to ``True`` in
226
+ v0.17, for the PIL and Tensor backends to be consistent.
227
+ """
228
+
229
+ _v1_transform_cls = _transforms.RandomResizedCrop
230
+
231
+ def __init__(
232
+ self,
233
+ size: Union[int, Sequence[int]],
234
+ scale: Tuple[float, float] = (0.08, 1.0),
235
+ ratio: Tuple[float, float] = (3.0 / 4.0, 4.0 / 3.0),
236
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
237
+ antialias: Optional[bool] = True,
238
+ ) -> None:
239
+ super().__init__()
240
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
241
+
242
+ if not isinstance(scale, Sequence):
243
+ raise TypeError("Scale should be a sequence")
244
+ if not isinstance(ratio, Sequence):
245
+ raise TypeError("Ratio should be a sequence")
246
+ if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
247
+ warnings.warn("Scale and ratio should be of kind (min, max)")
248
+
249
+ self.scale = scale
250
+ self.ratio = ratio
251
+ self.interpolation = interpolation
252
+ self.antialias = antialias
253
+
254
+ self._log_ratio = torch.log(torch.tensor(self.ratio))
255
+
256
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
257
+ height, width = query_size(flat_inputs)
258
+ area = height * width
259
+
260
+ log_ratio = self._log_ratio
261
+ for _ in range(10):
262
+ target_area = area * torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
263
+ aspect_ratio = torch.exp(
264
+ torch.empty(1).uniform_(
265
+ log_ratio[0], # type: ignore[arg-type]
266
+ log_ratio[1], # type: ignore[arg-type]
267
+ )
268
+ ).item()
269
+
270
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
271
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
272
+
273
+ if 0 < w <= width and 0 < h <= height:
274
+ i = torch.randint(0, height - h + 1, size=(1,)).item()
275
+ j = torch.randint(0, width - w + 1, size=(1,)).item()
276
+ break
277
+ else:
278
+ # Fallback to central crop
279
+ in_ratio = float(width) / float(height)
280
+ if in_ratio < min(self.ratio):
281
+ w = width
282
+ h = int(round(w / min(self.ratio)))
283
+ elif in_ratio > max(self.ratio):
284
+ h = height
285
+ w = int(round(h * max(self.ratio)))
286
+ else: # whole image
287
+ w = width
288
+ h = height
289
+ i = (height - h) // 2
290
+ j = (width - w) // 2
291
+
292
+ return dict(top=i, left=j, height=h, width=w)
293
+
294
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
295
+ return self._call_kernel(
296
+ F.resized_crop, inpt, **params, size=self.size, interpolation=self.interpolation, antialias=self.antialias
297
+ )
298
+
299
+
300
+ class FiveCrop(Transform):
301
+ """Crop the image or video into four corners and the central crop.
302
+
303
+ If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a
304
+ :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions.
305
+ For example, the image can have ``[..., C, H, W]`` shape.
306
+
307
+ .. Note::
308
+ This transform returns a tuple of images and there may be a mismatch in the number of
309
+ inputs and targets your Dataset returns. See below for an example of how to deal with
310
+ this.
311
+
312
+ Args:
313
+ size (sequence or int): Desired output size of the crop. If size is an ``int``
314
+ instead of sequence like (h, w), a square crop of size (size, size) is made.
315
+ If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
316
+
317
+ Example:
318
+ >>> class BatchMultiCrop(transforms.Transform):
319
+ ... def forward(self, sample: Tuple[Tuple[Union[tv_tensors.Image, tv_tensors.Video], ...], int]):
320
+ ... images_or_videos, labels = sample
321
+ ... batch_size = len(images_or_videos)
322
+ ... image_or_video = images_or_videos[0]
323
+ ... images_or_videos = tv_tensors.wrap(torch.stack(images_or_videos), like=image_or_video)
324
+ ... labels = torch.full((batch_size,), label, device=images_or_videos.device)
325
+ ... return images_or_videos, labels
326
+ ...
327
+ >>> image = tv_tensors.Image(torch.rand(3, 256, 256))
328
+ >>> label = 3
329
+ >>> transform = transforms.Compose([transforms.FiveCrop(224), BatchMultiCrop()])
330
+ >>> images, labels = transform(image, label)
331
+ >>> images.shape
332
+ torch.Size([5, 3, 224, 224])
333
+ >>> labels
334
+ tensor([3, 3, 3, 3, 3])
335
+ """
336
+
337
+ _v1_transform_cls = _transforms.FiveCrop
338
+
339
+ def __init__(self, size: Union[int, Sequence[int]]) -> None:
340
+ super().__init__()
341
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
342
+
343
+ def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any:
344
+ if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask)):
345
+ warnings.warn(
346
+ f"{type(self).__name__}() is currently passing through inputs of type "
347
+ f"tv_tensors.{type(inpt).__name__}. This will likely change in the future."
348
+ )
349
+ return super()._call_kernel(functional, inpt, *args, **kwargs)
350
+
351
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
352
+ return self._call_kernel(F.five_crop, inpt, self.size)
353
+
354
+ def _check_inputs(self, flat_inputs: List[Any]) -> None:
355
+ if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask):
356
+ raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()")
357
+
358
+
359
+ class TenCrop(Transform):
360
+ """Crop the image or video into four corners and the central crop plus the flipped version of
361
+ these (horizontal flipping is used by default).
362
+
363
+ If the input is a :class:`torch.Tensor` or a :class:`~torchvision.tv_tensors.Image` or a
364
+ :class:`~torchvision.tv_tensors.Video` it can have arbitrary number of leading batch dimensions.
365
+ For example, the image can have ``[..., C, H, W]`` shape.
366
+
367
+ See :class:`~torchvision.transforms.v2.FiveCrop` for an example.
368
+
369
+ .. Note::
370
+ This transform returns a tuple of images and there may be a mismatch in the number of
371
+ inputs and targets your Dataset returns. See below for an example of how to deal with
372
+ this.
373
+
374
+ Args:
375
+ size (sequence or int): Desired output size of the crop. If size is an
376
+ int instead of sequence like (h, w), a square crop (size, size) is
377
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
378
+ vertical_flip (bool, optional): Use vertical flipping instead of horizontal
379
+ """
380
+
381
+ _v1_transform_cls = _transforms.TenCrop
382
+
383
+ def __init__(self, size: Union[int, Sequence[int]], vertical_flip: bool = False) -> None:
384
+ super().__init__()
385
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
386
+ self.vertical_flip = vertical_flip
387
+
388
+ def _call_kernel(self, functional: Callable, inpt: Any, *args: Any, **kwargs: Any) -> Any:
389
+ if isinstance(inpt, (tv_tensors.BoundingBoxes, tv_tensors.Mask)):
390
+ warnings.warn(
391
+ f"{type(self).__name__}() is currently passing through inputs of type "
392
+ f"tv_tensors.{type(inpt).__name__}. This will likely change in the future."
393
+ )
394
+ return super()._call_kernel(functional, inpt, *args, **kwargs)
395
+
396
+ def _check_inputs(self, flat_inputs: List[Any]) -> None:
397
+ if has_any(flat_inputs, tv_tensors.BoundingBoxes, tv_tensors.Mask):
398
+ raise TypeError(f"BoundingBoxes'es and Mask's are not supported by {type(self).__name__}()")
399
+
400
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
401
+ return self._call_kernel(F.ten_crop, inpt, self.size, vertical_flip=self.vertical_flip)
402
+
403
+
404
+ class Pad(Transform):
405
+ """Pad the input on all sides with the given "pad" value.
406
+
407
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
408
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
409
+ it can have arbitrary number of leading batch dimensions. For example,
410
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
411
+
412
+ Args:
413
+ padding (int or sequence): Padding on each border. If a single int is provided this
414
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
415
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
416
+ this is the padding for the left, top, right and bottom borders respectively.
417
+
418
+ .. note::
419
+ In torchscript mode padding as single int is not supported, use a sequence of
420
+ length 1: ``[padding, ]``.
421
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
422
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
423
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
424
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
425
+ ``Mask`` will be filled with 0.
426
+ padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric.
427
+ Default is "constant".
428
+
429
+ - constant: pads with a constant value, this value is specified with fill
430
+
431
+ - edge: pads with the last value at the edge of the image.
432
+
433
+ - reflect: pads with reflection of image without repeating the last value on the edge.
434
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
435
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
436
+
437
+ - symmetric: pads with reflection of image repeating the last value on the edge.
438
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
439
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
440
+ """
441
+
442
+ _v1_transform_cls = _transforms.Pad
443
+
444
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
445
+ params = super()._extract_params_for_v1_transform()
446
+
447
+ if not (params["fill"] is None or isinstance(params["fill"], (int, float))):
448
+ raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.")
449
+
450
+ return params
451
+
452
+ def __init__(
453
+ self,
454
+ padding: Union[int, Sequence[int]],
455
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
456
+ padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant",
457
+ ) -> None:
458
+ super().__init__()
459
+
460
+ _check_padding_arg(padding)
461
+ _check_padding_mode_arg(padding_mode)
462
+
463
+ # This cast does Sequence[int] -> List[int] and is required to make mypy happy
464
+ if not isinstance(padding, int):
465
+ padding = list(padding)
466
+ self.padding = padding
467
+ self.fill = fill
468
+ self._fill = _setup_fill_arg(fill)
469
+ self.padding_mode = padding_mode
470
+
471
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
472
+ fill = _get_fill(self._fill, type(inpt))
473
+ return self._call_kernel(F.pad, inpt, padding=self.padding, fill=fill, padding_mode=self.padding_mode) # type: ignore[arg-type]
474
+
475
+
476
+ class RandomZoomOut(_RandomApplyTransform):
477
+ """ "Zoom out" transformation from
478
+ `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.
479
+
480
+ This transformation randomly pads images, videos, bounding boxes and masks creating a zoom out effect.
481
+ Output spatial size is randomly sampled from original size up to a maximum size configured
482
+ with ``side_range`` parameter:
483
+
484
+ .. code-block:: python
485
+
486
+ r = uniform_sample(side_range[0], side_range[1])
487
+ output_width = input_width * r
488
+ output_height = input_height * r
489
+
490
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
491
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
492
+ it can have arbitrary number of leading batch dimensions. For example,
493
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
494
+
495
+ Args:
496
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
497
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
498
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
499
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
500
+ ``Mask`` will be filled with 0.
501
+ side_range (sequence of floats, optional): tuple of two floats defines minimum and maximum factors to
502
+ scale the input size.
503
+ p (float, optional): probability that the zoom operation will be performed.
504
+ """
505
+
506
+ def __init__(
507
+ self,
508
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
509
+ side_range: Sequence[float] = (1.0, 4.0),
510
+ p: float = 0.5,
511
+ ) -> None:
512
+ super().__init__(p=p)
513
+
514
+ self.fill = fill
515
+ self._fill = _setup_fill_arg(fill)
516
+
517
+ _check_sequence_input(side_range, "side_range", req_sizes=(2,))
518
+
519
+ self.side_range = side_range
520
+ if side_range[0] < 1.0 or side_range[0] > side_range[1]:
521
+ raise ValueError(f"Invalid side range provided {side_range}.")
522
+
523
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
524
+ orig_h, orig_w = query_size(flat_inputs)
525
+
526
+ r = self.side_range[0] + torch.rand(1) * (self.side_range[1] - self.side_range[0])
527
+ canvas_width = int(orig_w * r)
528
+ canvas_height = int(orig_h * r)
529
+
530
+ r = torch.rand(2)
531
+ left = int((canvas_width - orig_w) * r[0])
532
+ top = int((canvas_height - orig_h) * r[1])
533
+ right = canvas_width - (left + orig_w)
534
+ bottom = canvas_height - (top + orig_h)
535
+ padding = [left, top, right, bottom]
536
+
537
+ return dict(padding=padding)
538
+
539
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
540
+ fill = _get_fill(self._fill, type(inpt))
541
+ return self._call_kernel(F.pad, inpt, **params, fill=fill)
542
+
543
+
544
+ class RandomRotation(Transform):
545
+ """Rotate the input by angle.
546
+
547
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
548
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
549
+ it can have arbitrary number of leading batch dimensions. For example,
550
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
551
+
552
+ Args:
553
+ degrees (sequence or number): Range of degrees to select from.
554
+ If degrees is a number instead of sequence like (min, max), the range of degrees
555
+ will be (-degrees, +degrees).
556
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
557
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
558
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
559
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
560
+ expand (bool, optional): Optional expansion flag.
561
+ If true, expands the output to make it large enough to hold the entire rotated image.
562
+ If false or omitted, make the output image the same size as the input image.
563
+ Note that the expand flag assumes rotation around the center (see note below) and no translation.
564
+ center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
565
+ Default is the center of the image.
566
+
567
+ .. note::
568
+
569
+ In theory, setting ``center`` has no effect if ``expand=True``, since the image center will become the
570
+ center of rotation. In practice however, due to numerical precision, this can lead to off-by-one
571
+ differences of the resulting image size compared to using the image center in the first place. Thus, when
572
+ setting ``expand=True``, it's best to leave ``center=None`` (default).
573
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
574
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
575
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
576
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
577
+ ``Mask`` will be filled with 0.
578
+
579
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
580
+
581
+ """
582
+
583
+ _v1_transform_cls = _transforms.RandomRotation
584
+
585
+ def __init__(
586
+ self,
587
+ degrees: Union[numbers.Number, Sequence],
588
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
589
+ expand: bool = False,
590
+ center: Optional[List[float]] = None,
591
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
592
+ ) -> None:
593
+ super().__init__()
594
+ self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
595
+ self.interpolation = interpolation
596
+ self.expand = expand
597
+
598
+ self.fill = fill
599
+ self._fill = _setup_fill_arg(fill)
600
+
601
+ if center is not None:
602
+ _check_sequence_input(center, "center", req_sizes=(2,))
603
+
604
+ self.center = center
605
+
606
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
607
+ angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item()
608
+ return dict(angle=angle)
609
+
610
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
611
+ fill = _get_fill(self._fill, type(inpt))
612
+ return self._call_kernel(
613
+ F.rotate,
614
+ inpt,
615
+ **params,
616
+ interpolation=self.interpolation,
617
+ expand=self.expand,
618
+ center=self.center,
619
+ fill=fill,
620
+ )
621
+
622
+
623
+ class RandomAffine(Transform):
624
+ """Random affine transformation the input keeping center invariant.
625
+
626
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
627
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
628
+ it can have arbitrary number of leading batch dimensions. For example,
629
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
630
+
631
+ Args:
632
+ degrees (sequence or number): Range of degrees to select from.
633
+ If degrees is a number instead of sequence like (min, max), the range of degrees
634
+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.
635
+ translate (tuple, optional): tuple of maximum absolute fraction for horizontal
636
+ and vertical translations. For example translate=(a, b), then horizontal shift
637
+ is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
638
+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
639
+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
640
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
641
+ shear (sequence or number, optional): Range of degrees to select from.
642
+ If shear is a number, a shear parallel to the x-axis in the range (-shear, +shear)
643
+ will be applied. Else if shear is a sequence of 2 values a shear parallel to the x-axis in the
644
+ range (shear[0], shear[1]) will be applied. Else if shear is a sequence of 4 values,
645
+ an x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
646
+ Will not apply shear by default.
647
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
648
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.NEAREST``.
649
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
650
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
651
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
652
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
653
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
654
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
655
+ ``Mask`` will be filled with 0.
656
+ center (sequence, optional): Optional center of rotation, (x, y). Origin is the upper left corner.
657
+ Default is the center of the image.
658
+
659
+ .. _filters: https://pillow.readthedocs.io/en/latest/handbook/concepts.html#filters
660
+
661
+ """
662
+
663
+ _v1_transform_cls = _transforms.RandomAffine
664
+
665
+ def __init__(
666
+ self,
667
+ degrees: Union[numbers.Number, Sequence],
668
+ translate: Optional[Sequence[float]] = None,
669
+ scale: Optional[Sequence[float]] = None,
670
+ shear: Optional[Union[int, float, Sequence[float]]] = None,
671
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.NEAREST,
672
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
673
+ center: Optional[List[float]] = None,
674
+ ) -> None:
675
+ super().__init__()
676
+ self.degrees = _setup_angle(degrees, name="degrees", req_sizes=(2,))
677
+ if translate is not None:
678
+ _check_sequence_input(translate, "translate", req_sizes=(2,))
679
+ for t in translate:
680
+ if not (0.0 <= t <= 1.0):
681
+ raise ValueError("translation values should be between 0 and 1")
682
+ self.translate = translate
683
+ if scale is not None:
684
+ _check_sequence_input(scale, "scale", req_sizes=(2,))
685
+ for s in scale:
686
+ if s <= 0:
687
+ raise ValueError("scale values should be positive")
688
+ self.scale = scale
689
+
690
+ if shear is not None:
691
+ self.shear = _setup_angle(shear, name="shear", req_sizes=(2, 4))
692
+ else:
693
+ self.shear = shear
694
+
695
+ self.interpolation = interpolation
696
+ self.fill = fill
697
+ self._fill = _setup_fill_arg(fill)
698
+
699
+ if center is not None:
700
+ _check_sequence_input(center, "center", req_sizes=(2,))
701
+
702
+ self.center = center
703
+
704
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
705
+ height, width = query_size(flat_inputs)
706
+
707
+ angle = torch.empty(1).uniform_(self.degrees[0], self.degrees[1]).item()
708
+ if self.translate is not None:
709
+ max_dx = float(self.translate[0] * width)
710
+ max_dy = float(self.translate[1] * height)
711
+ tx = int(round(torch.empty(1).uniform_(-max_dx, max_dx).item()))
712
+ ty = int(round(torch.empty(1).uniform_(-max_dy, max_dy).item()))
713
+ translate = (tx, ty)
714
+ else:
715
+ translate = (0, 0)
716
+
717
+ if self.scale is not None:
718
+ scale = torch.empty(1).uniform_(self.scale[0], self.scale[1]).item()
719
+ else:
720
+ scale = 1.0
721
+
722
+ shear_x = shear_y = 0.0
723
+ if self.shear is not None:
724
+ shear_x = torch.empty(1).uniform_(self.shear[0], self.shear[1]).item()
725
+ if len(self.shear) == 4:
726
+ shear_y = torch.empty(1).uniform_(self.shear[2], self.shear[3]).item()
727
+
728
+ shear = (shear_x, shear_y)
729
+ return dict(angle=angle, translate=translate, scale=scale, shear=shear)
730
+
731
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
732
+ fill = _get_fill(self._fill, type(inpt))
733
+ return self._call_kernel(
734
+ F.affine,
735
+ inpt,
736
+ **params,
737
+ interpolation=self.interpolation,
738
+ fill=fill,
739
+ center=self.center,
740
+ )
741
+
742
+
743
+ class RandomCrop(Transform):
744
+ """Crop the input at a random location.
745
+
746
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
747
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
748
+ it can have arbitrary number of leading batch dimensions. For example,
749
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
750
+
751
+ Args:
752
+ size (sequence or int): Desired output size of the crop. If size is an
753
+ int instead of sequence like (h, w), a square crop (size, size) is
754
+ made. If provided a sequence of length 1, it will be interpreted as (size[0], size[0]).
755
+ padding (int or sequence, optional): Optional padding on each border
756
+ of the image. Default is None. If a single int is provided this
757
+ is used to pad all borders. If sequence of length 2 is provided this is the padding
758
+ on left/right and top/bottom respectively. If a sequence of length 4 is provided
759
+ this is the padding for the left, top, right and bottom borders respectively.
760
+
761
+ .. note::
762
+ In torchscript mode padding as single int is not supported, use a sequence of
763
+ length 1: ``[padding, ]``.
764
+ pad_if_needed (boolean, optional): It will pad the image if smaller than the
765
+ desired size to avoid raising an exception. Since cropping is done
766
+ after padding, the padding seems to be done at a random offset.
767
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
768
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
769
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
770
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
771
+ ``Mask`` will be filled with 0.
772
+ padding_mode (str, optional): Type of padding. Should be: constant, edge, reflect or symmetric.
773
+ Default is constant.
774
+
775
+ - constant: pads with a constant value, this value is specified with fill
776
+
777
+ - edge: pads with the last value at the edge of the image.
778
+
779
+ - reflect: pads with reflection of image without repeating the last value on the edge.
780
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in reflect mode
781
+ will result in [3, 2, 1, 2, 3, 4, 3, 2]
782
+
783
+ - symmetric: pads with reflection of image repeating the last value on the edge.
784
+ For example, padding [1, 2, 3, 4] with 2 elements on both sides in symmetric mode
785
+ will result in [2, 1, 1, 2, 3, 4, 4, 3]
786
+ """
787
+
788
+ _v1_transform_cls = _transforms.RandomCrop
789
+
790
+ def _extract_params_for_v1_transform(self) -> Dict[str, Any]:
791
+ params = super()._extract_params_for_v1_transform()
792
+
793
+ if not (params["fill"] is None or isinstance(params["fill"], (int, float))):
794
+ raise ValueError(f"{type(self).__name__}() can only be scripted for a scalar `fill`, but got {self.fill}.")
795
+
796
+ padding = self.padding
797
+ if padding is not None:
798
+ pad_left, pad_right, pad_top, pad_bottom = padding
799
+ padding = [pad_left, pad_top, pad_right, pad_bottom]
800
+ params["padding"] = padding
801
+
802
+ return params
803
+
804
+ def __init__(
805
+ self,
806
+ size: Union[int, Sequence[int]],
807
+ padding: Optional[Union[int, Sequence[int]]] = None,
808
+ pad_if_needed: bool = False,
809
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
810
+ padding_mode: Literal["constant", "edge", "reflect", "symmetric"] = "constant",
811
+ ) -> None:
812
+ super().__init__()
813
+
814
+ self.size = _setup_size(size, error_msg="Please provide only two dimensions (h, w) for size.")
815
+
816
+ if pad_if_needed or padding is not None:
817
+ if padding is not None:
818
+ _check_padding_arg(padding)
819
+ _check_padding_mode_arg(padding_mode)
820
+
821
+ self.padding = F._geometry._parse_pad_padding(padding) if padding else None # type: ignore[arg-type]
822
+ self.pad_if_needed = pad_if_needed
823
+ self.fill = fill
824
+ self._fill = _setup_fill_arg(fill)
825
+ self.padding_mode = padding_mode
826
+
827
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
828
+ padded_height, padded_width = query_size(flat_inputs)
829
+
830
+ if self.padding is not None:
831
+ pad_left, pad_right, pad_top, pad_bottom = self.padding
832
+ padded_height += pad_top + pad_bottom
833
+ padded_width += pad_left + pad_right
834
+ else:
835
+ pad_left = pad_right = pad_top = pad_bottom = 0
836
+
837
+ cropped_height, cropped_width = self.size
838
+
839
+ if self.pad_if_needed:
840
+ if padded_height < cropped_height:
841
+ diff = cropped_height - padded_height
842
+
843
+ pad_top += diff
844
+ pad_bottom += diff
845
+ padded_height += 2 * diff
846
+
847
+ if padded_width < cropped_width:
848
+ diff = cropped_width - padded_width
849
+
850
+ pad_left += diff
851
+ pad_right += diff
852
+ padded_width += 2 * diff
853
+
854
+ if padded_height < cropped_height or padded_width < cropped_width:
855
+ raise ValueError(
856
+ f"Required crop size {(cropped_height, cropped_width)} is larger than "
857
+ f"{'padded ' if self.padding is not None else ''}input image size {(padded_height, padded_width)}."
858
+ )
859
+
860
+ # We need a different order here than we have in self.padding since this padding will be parsed again in `F.pad`
861
+ padding = [pad_left, pad_top, pad_right, pad_bottom]
862
+ needs_pad = any(padding)
863
+
864
+ needs_vert_crop, top = (
865
+ (True, int(torch.randint(0, padded_height - cropped_height + 1, size=())))
866
+ if padded_height > cropped_height
867
+ else (False, 0)
868
+ )
869
+ needs_horz_crop, left = (
870
+ (True, int(torch.randint(0, padded_width - cropped_width + 1, size=())))
871
+ if padded_width > cropped_width
872
+ else (False, 0)
873
+ )
874
+
875
+ return dict(
876
+ needs_crop=needs_vert_crop or needs_horz_crop,
877
+ top=top,
878
+ left=left,
879
+ height=cropped_height,
880
+ width=cropped_width,
881
+ needs_pad=needs_pad,
882
+ padding=padding,
883
+ )
884
+
885
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
886
+ if params["needs_pad"]:
887
+ fill = _get_fill(self._fill, type(inpt))
888
+ inpt = self._call_kernel(F.pad, inpt, padding=params["padding"], fill=fill, padding_mode=self.padding_mode)
889
+
890
+ if params["needs_crop"]:
891
+ inpt = self._call_kernel(
892
+ F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"]
893
+ )
894
+
895
+ return inpt
896
+
897
+
898
+ class RandomPerspective(_RandomApplyTransform):
899
+ """Perform a random perspective transformation of the input with a given probability.
900
+
901
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
902
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
903
+ it can have arbitrary number of leading batch dimensions. For example,
904
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
905
+
906
+ Args:
907
+ distortion_scale (float, optional): argument to control the degree of distortion and ranges from 0 to 1.
908
+ Default is 0.5.
909
+ p (float, optional): probability of the input being transformed. Default is 0.5.
910
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
911
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
912
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
913
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
914
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
915
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
916
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
917
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
918
+ ``Mask`` will be filled with 0.
919
+ """
920
+
921
+ _v1_transform_cls = _transforms.RandomPerspective
922
+
923
+ def __init__(
924
+ self,
925
+ distortion_scale: float = 0.5,
926
+ p: float = 0.5,
927
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
928
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
929
+ ) -> None:
930
+ super().__init__(p=p)
931
+
932
+ if not (0 <= distortion_scale <= 1):
933
+ raise ValueError("Argument distortion_scale value should be between 0 and 1")
934
+
935
+ self.distortion_scale = distortion_scale
936
+ self.interpolation = interpolation
937
+ self.fill = fill
938
+ self._fill = _setup_fill_arg(fill)
939
+
940
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
941
+ height, width = query_size(flat_inputs)
942
+
943
+ distortion_scale = self.distortion_scale
944
+
945
+ half_height = height // 2
946
+ half_width = width // 2
947
+ bound_height = int(distortion_scale * half_height) + 1
948
+ bound_width = int(distortion_scale * half_width) + 1
949
+ topleft = [
950
+ int(torch.randint(0, bound_width, size=(1,))),
951
+ int(torch.randint(0, bound_height, size=(1,))),
952
+ ]
953
+ topright = [
954
+ int(torch.randint(width - bound_width, width, size=(1,))),
955
+ int(torch.randint(0, bound_height, size=(1,))),
956
+ ]
957
+ botright = [
958
+ int(torch.randint(width - bound_width, width, size=(1,))),
959
+ int(torch.randint(height - bound_height, height, size=(1,))),
960
+ ]
961
+ botleft = [
962
+ int(torch.randint(0, bound_width, size=(1,))),
963
+ int(torch.randint(height - bound_height, height, size=(1,))),
964
+ ]
965
+ startpoints = [[0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]
966
+ endpoints = [topleft, topright, botright, botleft]
967
+ perspective_coeffs = _get_perspective_coeffs(startpoints, endpoints)
968
+ return dict(coefficients=perspective_coeffs)
969
+
970
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
971
+ fill = _get_fill(self._fill, type(inpt))
972
+ return self._call_kernel(
973
+ F.perspective,
974
+ inpt,
975
+ startpoints=None,
976
+ endpoints=None,
977
+ fill=fill,
978
+ interpolation=self.interpolation,
979
+ **params,
980
+ )
981
+
982
+
983
+ class ElasticTransform(Transform):
984
+ """Transform the input with elastic transformations.
985
+
986
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
987
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
988
+ it can have arbitrary number of leading batch dimensions. For example,
989
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
990
+
991
+ Given alpha and sigma, it will generate displacement
992
+ vectors for all pixels based on random offsets. Alpha controls the strength
993
+ and sigma controls the smoothness of the displacements.
994
+ The displacements are added to an identity grid and the resulting grid is
995
+ used to transform the input.
996
+
997
+ .. note::
998
+ Implementation to transform bounding boxes is approximative (not exact).
999
+ We construct an approximation of the inverse grid as ``inverse_grid = identity - displacement``.
1000
+ This is not an exact inverse of the grid used to transform images, i.e. ``grid = identity + displacement``.
1001
+ Our assumption is that ``displacement * displacement`` is small and can be ignored.
1002
+ Large displacements would lead to large errors in the approximation.
1003
+
1004
+ Applications:
1005
+ Randomly transforms the morphology of objects in images and produces a
1006
+ see-through-water-like effect.
1007
+
1008
+ Args:
1009
+ alpha (float or sequence of floats, optional): Magnitude of displacements. Default is 50.0.
1010
+ sigma (float or sequence of floats, optional): Smoothness of displacements. Default is 5.0.
1011
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1012
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1013
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.BILINEAR`` are supported.
1014
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1015
+ fill (number or tuple or dict, optional): Pixel fill value used when the ``padding_mode`` is constant.
1016
+ Default is 0. If a tuple of length 3, it is used to fill R, G, B channels respectively.
1017
+ Fill value can be also a dictionary mapping data type to the fill value, e.g.
1018
+ ``fill={tv_tensors.Image: 127, tv_tensors.Mask: 0}`` where ``Image`` will be filled with 127 and
1019
+ ``Mask`` will be filled with 0.
1020
+ """
1021
+
1022
+ _v1_transform_cls = _transforms.ElasticTransform
1023
+
1024
+ def __init__(
1025
+ self,
1026
+ alpha: Union[float, Sequence[float]] = 50.0,
1027
+ sigma: Union[float, Sequence[float]] = 5.0,
1028
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1029
+ fill: Union[_FillType, Dict[Union[Type, str], _FillType]] = 0,
1030
+ ) -> None:
1031
+ super().__init__()
1032
+ self.alpha = _setup_number_or_seq(alpha, "alpha")
1033
+ self.sigma = _setup_number_or_seq(sigma, "sigma")
1034
+
1035
+ self.interpolation = interpolation
1036
+ self.fill = fill
1037
+ self._fill = _setup_fill_arg(fill)
1038
+
1039
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1040
+ size = list(query_size(flat_inputs))
1041
+
1042
+ dx = torch.rand([1, 1] + size) * 2 - 1
1043
+ if self.sigma[0] > 0.0:
1044
+ kx = int(8 * self.sigma[0] + 1)
1045
+ # if kernel size is even we have to make it odd
1046
+ if kx % 2 == 0:
1047
+ kx += 1
1048
+ dx = self._call_kernel(F.gaussian_blur, dx, [kx, kx], list(self.sigma))
1049
+ dx = dx * self.alpha[0] / size[0]
1050
+
1051
+ dy = torch.rand([1, 1] + size) * 2 - 1
1052
+ if self.sigma[1] > 0.0:
1053
+ ky = int(8 * self.sigma[1] + 1)
1054
+ # if kernel size is even we have to make it odd
1055
+ if ky % 2 == 0:
1056
+ ky += 1
1057
+ dy = self._call_kernel(F.gaussian_blur, dy, [ky, ky], list(self.sigma))
1058
+ dy = dy * self.alpha[1] / size[1]
1059
+ displacement = torch.concat([dx, dy], 1).permute([0, 2, 3, 1]) # 1 x H x W x 2
1060
+ return dict(displacement=displacement)
1061
+
1062
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1063
+ fill = _get_fill(self._fill, type(inpt))
1064
+ return self._call_kernel(
1065
+ F.elastic,
1066
+ inpt,
1067
+ **params,
1068
+ fill=fill,
1069
+ interpolation=self.interpolation,
1070
+ )
1071
+
1072
+
1073
+ class RandomIoUCrop(Transform):
1074
+ """Random IoU crop transformation from
1075
+ `"SSD: Single Shot MultiBox Detector" <https://arxiv.org/abs/1512.02325>`_.
1076
+
1077
+ This transformation requires an image or video data and ``tv_tensors.BoundingBoxes`` in the input.
1078
+
1079
+ .. warning::
1080
+ In order to properly remove the bounding boxes below the IoU threshold, `RandomIoUCrop`
1081
+ must be followed by :class:`~torchvision.transforms.v2.SanitizeBoundingBoxes`, either immediately
1082
+ after or later in the transforms pipeline.
1083
+
1084
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1085
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1086
+ it can have arbitrary number of leading batch dimensions. For example,
1087
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1088
+
1089
+ Args:
1090
+ min_scale (float, optional): Minimum factors to scale the input size.
1091
+ max_scale (float, optional): Maximum factors to scale the input size.
1092
+ min_aspect_ratio (float, optional): Minimum aspect ratio for the cropped image or video.
1093
+ max_aspect_ratio (float, optional): Maximum aspect ratio for the cropped image or video.
1094
+ sampler_options (list of float, optional): List of minimal IoU (Jaccard) overlap between all the boxes and
1095
+ a cropped image or video. Default, ``None`` which corresponds to ``[0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]``
1096
+ trials (int, optional): Number of trials to find a crop for a given value of minimal IoU (Jaccard) overlap.
1097
+ Default, 40.
1098
+ """
1099
+
1100
+ def __init__(
1101
+ self,
1102
+ min_scale: float = 0.3,
1103
+ max_scale: float = 1.0,
1104
+ min_aspect_ratio: float = 0.5,
1105
+ max_aspect_ratio: float = 2.0,
1106
+ sampler_options: Optional[List[float]] = None,
1107
+ trials: int = 40,
1108
+ ):
1109
+ super().__init__()
1110
+ # Configuration similar to https://github.com/weiliu89/caffe/blob/ssd/examples/ssd/ssd_coco.py#L89-L174
1111
+ self.min_scale = min_scale
1112
+ self.max_scale = max_scale
1113
+ self.min_aspect_ratio = min_aspect_ratio
1114
+ self.max_aspect_ratio = max_aspect_ratio
1115
+ if sampler_options is None:
1116
+ sampler_options = [0.0, 0.1, 0.3, 0.5, 0.7, 0.9, 1.0]
1117
+ self.options = sampler_options
1118
+ self.trials = trials
1119
+
1120
+ def _check_inputs(self, flat_inputs: List[Any]) -> None:
1121
+ if not (
1122
+ has_all(flat_inputs, tv_tensors.BoundingBoxes)
1123
+ and has_any(flat_inputs, PIL.Image.Image, tv_tensors.Image, is_pure_tensor)
1124
+ ):
1125
+ raise TypeError(
1126
+ f"{type(self).__name__}() requires input sample to contain tensor or PIL images "
1127
+ "and bounding boxes. Sample can also contain masks."
1128
+ )
1129
+
1130
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1131
+ orig_h, orig_w = query_size(flat_inputs)
1132
+ bboxes = get_bounding_boxes(flat_inputs)
1133
+
1134
+ while True:
1135
+ # sample an option
1136
+ idx = int(torch.randint(low=0, high=len(self.options), size=(1,)))
1137
+ min_jaccard_overlap = self.options[idx]
1138
+ if min_jaccard_overlap >= 1.0: # a value larger than 1 encodes the leave as-is option
1139
+ return dict()
1140
+
1141
+ for _ in range(self.trials):
1142
+ # check the aspect ratio limitations
1143
+ r = self.min_scale + (self.max_scale - self.min_scale) * torch.rand(2)
1144
+ new_w = int(orig_w * r[0])
1145
+ new_h = int(orig_h * r[1])
1146
+ aspect_ratio = new_w / new_h
1147
+ if not (self.min_aspect_ratio <= aspect_ratio <= self.max_aspect_ratio):
1148
+ continue
1149
+
1150
+ # check for 0 area crops
1151
+ r = torch.rand(2)
1152
+ left = int((orig_w - new_w) * r[0])
1153
+ top = int((orig_h - new_h) * r[1])
1154
+ right = left + new_w
1155
+ bottom = top + new_h
1156
+ if left == right or top == bottom:
1157
+ continue
1158
+
1159
+ # check for any valid boxes with centers within the crop area
1160
+ xyxy_bboxes = F.convert_bounding_box_format(
1161
+ bboxes.as_subclass(torch.Tensor),
1162
+ bboxes.format,
1163
+ tv_tensors.BoundingBoxFormat.XYXY,
1164
+ )
1165
+ cx = 0.5 * (xyxy_bboxes[..., 0] + xyxy_bboxes[..., 2])
1166
+ cy = 0.5 * (xyxy_bboxes[..., 1] + xyxy_bboxes[..., 3])
1167
+ is_within_crop_area = (left < cx) & (cx < right) & (top < cy) & (cy < bottom)
1168
+ if not is_within_crop_area.any():
1169
+ continue
1170
+
1171
+ # check at least 1 box with jaccard limitations
1172
+ xyxy_bboxes = xyxy_bboxes[is_within_crop_area]
1173
+ ious = box_iou(
1174
+ xyxy_bboxes,
1175
+ torch.tensor([[left, top, right, bottom]], dtype=xyxy_bboxes.dtype, device=xyxy_bboxes.device),
1176
+ )
1177
+ if ious.max() < min_jaccard_overlap:
1178
+ continue
1179
+
1180
+ return dict(top=top, left=left, height=new_h, width=new_w, is_within_crop_area=is_within_crop_area)
1181
+
1182
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1183
+
1184
+ if len(params) < 1:
1185
+ return inpt
1186
+
1187
+ output = self._call_kernel(
1188
+ F.crop, inpt, top=params["top"], left=params["left"], height=params["height"], width=params["width"]
1189
+ )
1190
+
1191
+ if isinstance(output, tv_tensors.BoundingBoxes):
1192
+ # We "mark" the invalid boxes as degenreate, and they can be
1193
+ # removed by a later call to SanitizeBoundingBoxes()
1194
+ output[~params["is_within_crop_area"]] = 0
1195
+
1196
+ return output
1197
+
1198
+
1199
+ class ScaleJitter(Transform):
1200
+ """Perform Large Scale Jitter on the input according to
1201
+ `"Simple Copy-Paste is a Strong Data Augmentation Method for Instance Segmentation" <https://arxiv.org/abs/2012.07177>`_.
1202
+
1203
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1204
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1205
+ it can have arbitrary number of leading batch dimensions. For example,
1206
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1207
+
1208
+ Args:
1209
+ target_size (tuple of int): Target size. This parameter defines base scale for jittering,
1210
+ e.g. ``min(target_size[0] / width, target_size[1] / height)``.
1211
+ scale_range (tuple of float, optional): Minimum and maximum of the scale range. Default, ``(0.1, 2.0)``.
1212
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1213
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1214
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
1215
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
1216
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1217
+ antialias (bool, optional): Whether to apply antialiasing.
1218
+ It only affects **tensors** with bilinear or bicubic modes and it is
1219
+ ignored otherwise: on PIL images, antialiasing is always applied on
1220
+ bilinear or bicubic modes; on other modes (for PIL images and
1221
+ tensors), antialiasing makes no sense and this parameter is ignored.
1222
+ Possible values are:
1223
+
1224
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
1225
+ Other mode aren't affected. This is probably what you want to use.
1226
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
1227
+ images are still antialiased on bilinear or bicubic modes, because
1228
+ PIL doesn't support no antialias.
1229
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
1230
+ PIL images. This value exists for legacy reasons and you probably
1231
+ don't want to use it unless you really know what you are doing.
1232
+
1233
+ The default value changed from ``None`` to ``True`` in
1234
+ v0.17, for the PIL and Tensor backends to be consistent.
1235
+ """
1236
+
1237
+ def __init__(
1238
+ self,
1239
+ target_size: Tuple[int, int],
1240
+ scale_range: Tuple[float, float] = (0.1, 2.0),
1241
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1242
+ antialias: Optional[bool] = True,
1243
+ ):
1244
+ super().__init__()
1245
+ self.target_size = target_size
1246
+ self.scale_range = scale_range
1247
+ self.interpolation = interpolation
1248
+ self.antialias = antialias
1249
+
1250
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1251
+ orig_height, orig_width = query_size(flat_inputs)
1252
+
1253
+ scale = self.scale_range[0] + torch.rand(1) * (self.scale_range[1] - self.scale_range[0])
1254
+ r = min(self.target_size[1] / orig_height, self.target_size[0] / orig_width) * scale
1255
+ new_width = int(orig_width * r)
1256
+ new_height = int(orig_height * r)
1257
+
1258
+ return dict(size=(new_height, new_width))
1259
+
1260
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1261
+ return self._call_kernel(
1262
+ F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias
1263
+ )
1264
+
1265
+
1266
+ class RandomShortestSize(Transform):
1267
+ """Randomly resize the input.
1268
+
1269
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1270
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1271
+ it can have arbitrary number of leading batch dimensions. For example,
1272
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1273
+
1274
+ Args:
1275
+ min_size (int or sequence of int): Minimum spatial size. Single integer value or a sequence of integer values.
1276
+ max_size (int, optional): Maximum spatial size. Default, None.
1277
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1278
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1279
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
1280
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
1281
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1282
+ antialias (bool, optional): Whether to apply antialiasing.
1283
+ It only affects **tensors** with bilinear or bicubic modes and it is
1284
+ ignored otherwise: on PIL images, antialiasing is always applied on
1285
+ bilinear or bicubic modes; on other modes (for PIL images and
1286
+ tensors), antialiasing makes no sense and this parameter is ignored.
1287
+ Possible values are:
1288
+
1289
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
1290
+ Other mode aren't affected. This is probably what you want to use.
1291
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
1292
+ images are still antialiased on bilinear or bicubic modes, because
1293
+ PIL doesn't support no antialias.
1294
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
1295
+ PIL images. This value exists for legacy reasons and you probably
1296
+ don't want to use it unless you really know what you are doing.
1297
+
1298
+ The default value changed from ``None`` to ``True`` in
1299
+ v0.17, for the PIL and Tensor backends to be consistent.
1300
+ """
1301
+
1302
+ def __init__(
1303
+ self,
1304
+ min_size: Union[List[int], Tuple[int], int],
1305
+ max_size: Optional[int] = None,
1306
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1307
+ antialias: Optional[bool] = True,
1308
+ ):
1309
+ super().__init__()
1310
+ self.min_size = [min_size] if isinstance(min_size, int) else list(min_size)
1311
+ self.max_size = max_size
1312
+ self.interpolation = interpolation
1313
+ self.antialias = antialias
1314
+
1315
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1316
+ orig_height, orig_width = query_size(flat_inputs)
1317
+
1318
+ min_size = self.min_size[int(torch.randint(len(self.min_size), ()))]
1319
+ r = min_size / min(orig_height, orig_width)
1320
+ if self.max_size is not None:
1321
+ r = min(r, self.max_size / max(orig_height, orig_width))
1322
+
1323
+ new_width = int(orig_width * r)
1324
+ new_height = int(orig_height * r)
1325
+
1326
+ return dict(size=(new_height, new_width))
1327
+
1328
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1329
+ return self._call_kernel(
1330
+ F.resize, inpt, size=params["size"], interpolation=self.interpolation, antialias=self.antialias
1331
+ )
1332
+
1333
+
1334
+ class RandomResize(Transform):
1335
+ """Randomly resize the input.
1336
+
1337
+ This transformation can be used together with ``RandomCrop`` as data augmentations to train
1338
+ models on image segmentation task.
1339
+
1340
+ Output spatial size is randomly sampled from the interval ``[min_size, max_size]``:
1341
+
1342
+ .. code-block:: python
1343
+
1344
+ size = uniform_sample(min_size, max_size)
1345
+ output_width = size
1346
+ output_height = size
1347
+
1348
+ If the input is a :class:`torch.Tensor` or a ``TVTensor`` (e.g. :class:`~torchvision.tv_tensors.Image`,
1349
+ :class:`~torchvision.tv_tensors.Video`, :class:`~torchvision.tv_tensors.BoundingBoxes` etc.)
1350
+ it can have arbitrary number of leading batch dimensions. For example,
1351
+ the image can have ``[..., C, H, W]`` shape. A bounding box can have ``[..., 4]`` shape.
1352
+
1353
+ Args:
1354
+ min_size (int): Minimum output size for random sampling
1355
+ max_size (int): Maximum output size for random sampling
1356
+ interpolation (InterpolationMode, optional): Desired interpolation enum defined by
1357
+ :class:`torchvision.transforms.InterpolationMode`. Default is ``InterpolationMode.BILINEAR``.
1358
+ If input is Tensor, only ``InterpolationMode.NEAREST``, ``InterpolationMode.NEAREST_EXACT``,
1359
+ ``InterpolationMode.BILINEAR`` and ``InterpolationMode.BICUBIC`` are supported.
1360
+ The corresponding Pillow integer constants, e.g. ``PIL.Image.BILINEAR`` are accepted as well.
1361
+ antialias (bool, optional): Whether to apply antialiasing.
1362
+ It only affects **tensors** with bilinear or bicubic modes and it is
1363
+ ignored otherwise: on PIL images, antialiasing is always applied on
1364
+ bilinear or bicubic modes; on other modes (for PIL images and
1365
+ tensors), antialiasing makes no sense and this parameter is ignored.
1366
+ Possible values are:
1367
+
1368
+ - ``True`` (default): will apply antialiasing for bilinear or bicubic modes.
1369
+ Other mode aren't affected. This is probably what you want to use.
1370
+ - ``False``: will not apply antialiasing for tensors on any mode. PIL
1371
+ images are still antialiased on bilinear or bicubic modes, because
1372
+ PIL doesn't support no antialias.
1373
+ - ``None``: equivalent to ``False`` for tensors and ``True`` for
1374
+ PIL images. This value exists for legacy reasons and you probably
1375
+ don't want to use it unless you really know what you are doing.
1376
+
1377
+ The default value changed from ``None`` to ``True`` in
1378
+ v0.17, for the PIL and Tensor backends to be consistent.
1379
+ """
1380
+
1381
+ def __init__(
1382
+ self,
1383
+ min_size: int,
1384
+ max_size: int,
1385
+ interpolation: Union[InterpolationMode, int] = InterpolationMode.BILINEAR,
1386
+ antialias: Optional[bool] = True,
1387
+ ) -> None:
1388
+ super().__init__()
1389
+ self.min_size = min_size
1390
+ self.max_size = max_size
1391
+ self.interpolation = interpolation
1392
+ self.antialias = antialias
1393
+
1394
+ def _get_params(self, flat_inputs: List[Any]) -> Dict[str, Any]:
1395
+ size = int(torch.randint(self.min_size, self.max_size, ()))
1396
+ return dict(size=[size])
1397
+
1398
+ def _transform(self, inpt: Any, params: Dict[str, Any]) -> Any:
1399
+ return self._call_kernel(
1400
+ F.resize, inpt, params["size"], interpolation=self.interpolation, antialias=self.antialias
1401
+ )
vlmpy310/lib/python3.10/site-packages/torchvision/transforms/v2/_meta.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Union
2
+
3
+ from torchvision import tv_tensors
4
+ from torchvision.transforms.v2 import functional as F, Transform
5
+
6
+
7
+ class ConvertBoundingBoxFormat(Transform):
8
+ """Convert bounding box coordinates to the given ``format``, eg from "CXCYWH" to "XYXY".
9
+
10
+ Args:
11
+ format (str or tv_tensors.BoundingBoxFormat): output bounding box format.
12
+ Possible values are defined by :class:`~torchvision.tv_tensors.BoundingBoxFormat` and
13
+ string values match the enums, e.g. "XYXY" or "XYWH" etc.
14
+ """
15
+
16
+ _transformed_types = (tv_tensors.BoundingBoxes,)
17
+
18
+ def __init__(self, format: Union[str, tv_tensors.BoundingBoxFormat]) -> None:
19
+ super().__init__()
20
+ if isinstance(format, str):
21
+ format = tv_tensors.BoundingBoxFormat[format]
22
+ self.format = format
23
+
24
+ def _transform(self, inpt: tv_tensors.BoundingBoxes, params: Dict[str, Any]) -> tv_tensors.BoundingBoxes:
25
+ return F.convert_bounding_box_format(inpt, new_format=self.format) # type: ignore[return-value]
26
+
27
+
28
+ class ClampBoundingBoxes(Transform):
29
+ """Clamp bounding boxes to their corresponding image dimensions.
30
+
31
+ The clamping is done according to the bounding boxes' ``canvas_size`` meta-data.
32
+
33
+ """
34
+
35
+ _transformed_types = (tv_tensors.BoundingBoxes,)
36
+
37
+ def _transform(self, inpt: tv_tensors.BoundingBoxes, params: Dict[str, Any]) -> tv_tensors.BoundingBoxes:
38
+ return F.clamp_bounding_boxes(inpt) # type: ignore[return-value]