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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Optional, Union
|
2 |
+
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
from transformers.image_processing_utils import (
|
6 |
+
BaseImageProcessor,
|
7 |
+
BatchFeature,
|
8 |
+
get_size_dict,
|
9 |
+
)
|
10 |
+
from transformers.image_transforms import (
|
11 |
+
normalize,
|
12 |
+
rescale,
|
13 |
+
resize,
|
14 |
+
to_channel_dimension_format,
|
15 |
+
)
|
16 |
+
from transformers.image_utils import (
|
17 |
+
IMAGENET_STANDARD_MEAN,
|
18 |
+
IMAGENET_STANDARD_STD,
|
19 |
+
ChannelDimension,
|
20 |
+
ImageInput,
|
21 |
+
PILImageResampling,
|
22 |
+
make_list_of_images,
|
23 |
+
to_numpy_array,
|
24 |
+
valid_images,
|
25 |
+
)
|
26 |
+
from transformers.utils import TensorType
|
27 |
+
|
28 |
+
|
29 |
+
class SpiceCNNImageProcessor(BaseImageProcessor):
|
30 |
+
"""
|
31 |
+
Constructs a SpiceCNN image processor.
|
32 |
+
|
33 |
+
Args:
|
34 |
+
do_resize (`bool`, *optional*, defaults to `True`):
|
35 |
+
Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
|
36 |
+
size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
|
37 |
+
size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
|
38 |
+
Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
|
39 |
+
method.
|
40 |
+
resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
|
41 |
+
Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
|
42 |
+
`preprocess` method.
|
43 |
+
do_rescale (`bool`, *optional*, defaults to `True`):
|
44 |
+
Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
|
45 |
+
parameter in the `preprocess` method.
|
46 |
+
rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
|
47 |
+
Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
|
48 |
+
`preprocess` method.
|
49 |
+
do_normalize (`bool`, *optional*, defaults to `True`):
|
50 |
+
Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
|
51 |
+
method.
|
52 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
|
53 |
+
Mean to use if normalizing the image. This is a float or list of floats the length of the number of
|
54 |
+
channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
|
55 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
|
56 |
+
Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
|
57 |
+
number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
|
58 |
+
""" # noqa
|
59 |
+
|
60 |
+
def __init__(
|
61 |
+
self,
|
62 |
+
do_resize: bool = True,
|
63 |
+
size: Optional[Dict[str, int]] = None,
|
64 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
65 |
+
do_rescale: bool = True,
|
66 |
+
rescale_factor: Union[int, float] = 1 / 255,
|
67 |
+
do_normalize: bool = True,
|
68 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
69 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
70 |
+
**kwargs,
|
71 |
+
) -> None:
|
72 |
+
super().__init__(**kwargs)
|
73 |
+
size = size if size is not None else {"height": 224, "width": 224}
|
74 |
+
size = get_size_dict(size)
|
75 |
+
self.do_resize = do_resize
|
76 |
+
self.do_rescale = do_rescale
|
77 |
+
self.do_normalize = do_normalize
|
78 |
+
self.size = size
|
79 |
+
self.resample = resample
|
80 |
+
self.rescale_factor = rescale_factor
|
81 |
+
self.image_mean = (
|
82 |
+
image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
|
83 |
+
)
|
84 |
+
self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
|
85 |
+
|
86 |
+
def resize(
|
87 |
+
self,
|
88 |
+
image: np.ndarray,
|
89 |
+
size: Dict[str, int],
|
90 |
+
resample: PILImageResampling = PILImageResampling.BILINEAR,
|
91 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
92 |
+
**kwargs,
|
93 |
+
) -> np.ndarray:
|
94 |
+
"""
|
95 |
+
Resize an image to `(size["height"], size["width"])`.
|
96 |
+
|
97 |
+
Args:
|
98 |
+
image (`np.ndarray`):
|
99 |
+
Image to resize.
|
100 |
+
size (`Dict[str, int]`):
|
101 |
+
Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
|
102 |
+
resample:
|
103 |
+
`PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
|
104 |
+
data_format (`ChannelDimension` or `str`, *optional*):
|
105 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
106 |
+
image is used. Can be one of:
|
107 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
108 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
109 |
+
|
110 |
+
Returns:
|
111 |
+
`np.ndarray`: The resized image.
|
112 |
+
""" # noqa
|
113 |
+
size = get_size_dict(size)
|
114 |
+
if "height" not in size or "width" not in size:
|
115 |
+
raise ValueError(
|
116 |
+
f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" # noqa
|
117 |
+
)
|
118 |
+
return resize(
|
119 |
+
image,
|
120 |
+
size=(size["height"], size["width"]),
|
121 |
+
resample=resample,
|
122 |
+
data_format=data_format,
|
123 |
+
**kwargs,
|
124 |
+
)
|
125 |
+
|
126 |
+
def rescale(
|
127 |
+
self,
|
128 |
+
image: np.ndarray,
|
129 |
+
scale: float,
|
130 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
131 |
+
**kwargs,
|
132 |
+
) -> np.ndarray:
|
133 |
+
"""
|
134 |
+
Rescale an image by a scale factor. image = image * scale.
|
135 |
+
|
136 |
+
Args:
|
137 |
+
image (`np.ndarray`):
|
138 |
+
Image to rescale.
|
139 |
+
scale (`float`):
|
140 |
+
The scaling factor to rescale pixel values by.
|
141 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
142 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
143 |
+
image is used. Can be one of:
|
144 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
145 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
146 |
+
|
147 |
+
Returns:
|
148 |
+
`np.ndarray`: The rescaled image.
|
149 |
+
""" # noqa
|
150 |
+
return rescale(image, scale=scale, data_format=data_format, **kwargs)
|
151 |
+
|
152 |
+
def normalize(
|
153 |
+
self,
|
154 |
+
image: np.ndarray,
|
155 |
+
mean: Union[float, List[float]],
|
156 |
+
std: Union[float, List[float]],
|
157 |
+
data_format: Optional[Union[str, ChannelDimension]] = None,
|
158 |
+
**kwargs,
|
159 |
+
) -> np.ndarray:
|
160 |
+
"""
|
161 |
+
Normalize an image. image = (image - image_mean) / image_std.
|
162 |
+
|
163 |
+
Args:
|
164 |
+
image (`np.ndarray`):
|
165 |
+
Image to normalize.
|
166 |
+
mean (`float` or `List[float]`):
|
167 |
+
Image mean to use for normalization.
|
168 |
+
std (`float` or `List[float]`):
|
169 |
+
Image standard deviation to use for normalization.
|
170 |
+
data_format (`str` or `ChannelDimension`, *optional*):
|
171 |
+
The channel dimension format for the output image. If unset, the channel dimension format of the input
|
172 |
+
image is used. Can be one of:
|
173 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
174 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
175 |
+
|
176 |
+
Returns:
|
177 |
+
`np.ndarray`: The normalized image.
|
178 |
+
""" # noqa
|
179 |
+
return normalize(image, mean=mean, std=std, data_format=data_format, **kwargs)
|
180 |
+
|
181 |
+
def preprocess(
|
182 |
+
self,
|
183 |
+
images: ImageInput,
|
184 |
+
do_resize: Optional[bool] = None,
|
185 |
+
size: Dict[str, int] = None,
|
186 |
+
resample: PILImageResampling = None,
|
187 |
+
do_rescale: Optional[bool] = None,
|
188 |
+
rescale_factor: Optional[float] = None,
|
189 |
+
do_normalize: Optional[bool] = None,
|
190 |
+
image_mean: Optional[Union[float, List[float]]] = None,
|
191 |
+
image_std: Optional[Union[float, List[float]]] = None,
|
192 |
+
return_tensors: Optional[Union[str, TensorType]] = None,
|
193 |
+
data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
|
194 |
+
**kwargs,
|
195 |
+
):
|
196 |
+
"""
|
197 |
+
Preprocess an image or batch of images.
|
198 |
+
|
199 |
+
Args:
|
200 |
+
images (`ImageInput`):
|
201 |
+
Image to preprocess.
|
202 |
+
do_resize (`bool`, *optional*, defaults to `self.do_resize`):
|
203 |
+
Whether to resize the image.
|
204 |
+
size (`Dict[str, int]`, *optional*, defaults to `self.size`):
|
205 |
+
Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
|
206 |
+
resizing.
|
207 |
+
resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
|
208 |
+
`PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
|
209 |
+
an effect if `do_resize` is set to `True`.
|
210 |
+
do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
|
211 |
+
Whether to rescale the image values between [0 - 1].
|
212 |
+
rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
|
213 |
+
Rescale factor to rescale the image by if `do_rescale` is set to `True`.
|
214 |
+
do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
|
215 |
+
Whether to normalize the image.
|
216 |
+
image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
|
217 |
+
Image mean to use if `do_normalize` is set to `True`.
|
218 |
+
image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
|
219 |
+
Image standard deviation to use if `do_normalize` is set to `True`.
|
220 |
+
return_tensors (`str` or `TensorType`, *optional*):
|
221 |
+
The type of tensors to return. Can be one of:
|
222 |
+
- Unset: Return a list of `np.ndarray`.
|
223 |
+
- `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
|
224 |
+
- `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
|
225 |
+
- `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
|
226 |
+
- `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
|
227 |
+
data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
|
228 |
+
The channel dimension format for the output image. Can be one of:
|
229 |
+
- `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
|
230 |
+
- `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
|
231 |
+
- Unset: Use the channel dimension format of the input image.
|
232 |
+
""" # noqa
|
233 |
+
do_resize = do_resize if do_resize is not None else self.do_resize
|
234 |
+
do_rescale = do_rescale if do_rescale is not None else self.do_rescale
|
235 |
+
do_normalize = do_normalize if do_normalize is not None else self.do_normalize
|
236 |
+
resample = resample if resample is not None else self.resample
|
237 |
+
rescale_factor = (
|
238 |
+
rescale_factor if rescale_factor is not None else self.rescale_factor
|
239 |
+
)
|
240 |
+
image_mean = image_mean if image_mean is not None else self.image_mean
|
241 |
+
image_std = image_std if image_std is not None else self.image_std
|
242 |
+
|
243 |
+
size = size if size is not None else self.size
|
244 |
+
size_dict = get_size_dict(size)
|
245 |
+
|
246 |
+
images = make_list_of_images(images)
|
247 |
+
|
248 |
+
if not valid_images(images):
|
249 |
+
raise ValueError(
|
250 |
+
"Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
|
251 |
+
"torch.Tensor, tf.Tensor or jax.ndarray."
|
252 |
+
)
|
253 |
+
|
254 |
+
if do_resize and size is None:
|
255 |
+
raise ValueError("Size must be specified if do_resize is True.")
|
256 |
+
|
257 |
+
if do_rescale and rescale_factor is None:
|
258 |
+
raise ValueError("Rescale factor must be specified if do_rescale is True.")
|
259 |
+
|
260 |
+
# All transformations expect numpy arrays.
|
261 |
+
images = [to_numpy_array(image) for image in images]
|
262 |
+
|
263 |
+
if do_resize:
|
264 |
+
images = [
|
265 |
+
self.resize(image=image, size=size_dict, resample=resample)
|
266 |
+
for image in images
|
267 |
+
]
|
268 |
+
|
269 |
+
if do_rescale:
|
270 |
+
images = [
|
271 |
+
self.rescale(image=image, scale=rescale_factor) for image in images
|
272 |
+
]
|
273 |
+
|
274 |
+
if do_normalize:
|
275 |
+
images = [
|
276 |
+
self.normalize(image=image, mean=image_mean, std=image_std)
|
277 |
+
for image in images
|
278 |
+
]
|
279 |
+
|
280 |
+
images = [to_channel_dimension_format(image, data_format) for image in images]
|
281 |
+
|
282 |
+
data = {"pixel_values": images}
|
283 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|