p1atdev commited on
Commit
5495955
1 Parent(s): f77624e

Upload 2 files

Browse files
Files changed (2) hide show
  1. image_processor_mle.py +443 -0
  2. modeling_mle.py +8 -5
image_processor_mle.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # copied from ViTImageProcessor (https://github.com/huggingface/transformers/blob/v4.37.2/src/transformers/models/vit/image_processing_vit.py)
2
+
3
+ """Image processor class for WD v14 Tagger."""
4
+
5
+ from typing import Optional, List, Dict, Union, Tuple
6
+
7
+ import numpy as np
8
+ import cv2
9
+ from PIL import Image
10
+
11
+ from transformers.image_processing_utils import (
12
+ BaseImageProcessor,
13
+ BatchFeature,
14
+ get_size_dict,
15
+ )
16
+ from transformers.image_transforms import (
17
+ rescale,
18
+ to_channel_dimension_format,
19
+ _rescale_for_pil_conversion,
20
+ to_pil_image,
21
+ )
22
+ from transformers.image_utils import (
23
+ IMAGENET_STANDARD_MEAN,
24
+ IMAGENET_STANDARD_STD,
25
+ ChannelDimension,
26
+ ImageInput,
27
+ PILImageResampling,
28
+ infer_channel_dimension_format,
29
+ is_scaled_image,
30
+ make_list_of_images,
31
+ to_numpy_array,
32
+ valid_images,
33
+ )
34
+ from transformers.utils import TensorType, logging
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+
39
+ def resize_by_factor(
40
+ image: np.ndarray,
41
+ resize_factor: int,
42
+ resample: PILImageResampling = None,
43
+ data_format: Optional[Union[str, ChannelDimension]] = None,
44
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
45
+ return_numpy: bool = True,
46
+ ):
47
+ """
48
+ Resizes `image` to `(height, width)` specified by `size` using the PIL library.
49
+
50
+ Args:
51
+ image (`np.ndarray`):
52
+ The image to resize.
53
+ resize_factor (`int`):
54
+ Value for padding the image to a multiple of the factor.
55
+ resample (`int`, *optional*, defaults to `PILImageResampling.BILINEAR`):
56
+ The filter to user for resampling.
57
+ data_format (`ChannelDimension`, *optional*):
58
+ The channel dimension format of the output image. If unset, will use the inferred format from the input.
59
+ return_numpy (`bool`, *optional*, defaults to `True`):
60
+ Whether or not to return the resized image as a numpy array. If False a `PIL.Image.Image` object is
61
+ returned.
62
+ input_data_format (`ChannelDimension`, *optional*):
63
+ The channel dimension format of the input image. If unset, will use the inferred format from the input.
64
+
65
+ Returns:
66
+ `np.ndarray`: The resized image.
67
+ """
68
+
69
+ resample = resample if resample is not None else PILImageResampling.BILINEAR
70
+
71
+ # For all transformations, we want to keep the same data format as the input image unless otherwise specified.
72
+ # The resized image from PIL will always have channels last, so find the input format first.
73
+ if input_data_format is None:
74
+ input_data_format = infer_channel_dimension_format(image)
75
+ data_format = input_data_format if data_format is None else data_format
76
+
77
+ # To maintain backwards compatibility with the resizing done in previous image feature extractors, we use
78
+ # the pillow library to resize the image and then convert back to numpy
79
+ do_rescale = False
80
+ if not isinstance(image, Image.Image):
81
+ do_rescale = _rescale_for_pil_conversion(image)
82
+ image = to_pil_image(
83
+ image, do_rescale=do_rescale, input_data_format=input_data_format
84
+ )
85
+
86
+ assert isinstance(image, Image.Image)
87
+
88
+ width, height = (
89
+ int(np.ceil(image.size[0] // resize_factor) * resize_factor),
90
+ int(np.ceil(image.size[1] // resize_factor) * resize_factor),
91
+ )
92
+ # solid image
93
+ new_image = Image.new(image.mode, (width, height), "white")
94
+
95
+ # paste original image on top left
96
+ new_image.paste(image)
97
+
98
+ if return_numpy:
99
+ new_image = np.array(new_image)
100
+ # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image
101
+ # so we need to add it back if necessary.
102
+ new_image = (
103
+ np.expand_dims(new_image, axis=-1) if new_image.ndim == 2 else new_image
104
+ )
105
+ # The image is always in channels last format after converting from a PIL image
106
+ new_image = to_channel_dimension_format(
107
+ new_image, data_format, input_channel_dim=ChannelDimension.LAST
108
+ )
109
+ # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to
110
+ # rescale it back to the original range.
111
+ new_image = rescale(new_image, 1 / 255) if do_rescale else new_image
112
+
113
+ return new_image
114
+
115
+
116
+ def greyscale(
117
+ image: np.ndarray,
118
+ data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,
119
+ input_data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,
120
+ return_numpy: bool = True,
121
+ ):
122
+ """
123
+ Convert `image` to `greyscale` using the PIL library.
124
+
125
+ Args:
126
+ image (`np.ndarray`):
127
+ The image to greyscale.
128
+ Returns:
129
+ `np.ndarray`: The greyscaled image.
130
+ """
131
+
132
+ if not isinstance(image, Image.Image):
133
+ do_rescale = _rescale_for_pil_conversion(image)
134
+ image = to_pil_image(
135
+ image, do_rescale=do_rescale, input_data_format=input_data_format
136
+ )
137
+
138
+ assert isinstance(image, Image.Image)
139
+
140
+ # do greyscale
141
+ image = image.convert("L")
142
+
143
+ if return_numpy:
144
+ image = np.array(image)
145
+
146
+ # If the input image channel dimension was of size 1, then it is dropped when converting to a PIL image
147
+ # so we need to add it back if necessary.
148
+ image = np.expand_dims(image, axis=-1) if image.ndim == 2 else image
149
+
150
+ # The image is always in channels last format after converting from a PIL image
151
+ image = to_channel_dimension_format(
152
+ image, data_format, input_channel_dim=ChannelDimension.LAST
153
+ )
154
+ # If an image was rescaled to be in the range [0, 255] before converting to a PIL image, then we need to
155
+ # rescale it back to the original range.
156
+ image = rescale(image, 1 / 255) if do_rescale else image
157
+
158
+ return image
159
+
160
+
161
+ class MLEImageProcessor(BaseImageProcessor):
162
+ r"""
163
+ Constructs a MLE image processor.
164
+
165
+ Args:
166
+ do_resize (`bool`, *optional*, defaults to `True`):
167
+ Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
168
+ size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
169
+ resize_factor (`int`, *optional*, defaults to `16`):
170
+ Value for padding the image to a multiple of the factor.
171
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BILINEAR`):
172
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
173
+ `preprocess` method.
174
+ do_rescale (`bool`, *optional*, defaults to `False`):
175
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
176
+ parameter in the `preprocess` method.
177
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
178
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
179
+ `preprocess` method.
180
+ do_normalize (`bool`, *optional*, defaults to `False`):
181
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
182
+ method.
183
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
184
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
185
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
186
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
187
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
188
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
189
+ """
190
+
191
+ model_input_names = ["pixel_values"]
192
+
193
+ def __init__(
194
+ self,
195
+ do_resize: bool = True,
196
+ resize_factor: int = 16,
197
+ do_greyscale: bool = True,
198
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
199
+ do_rescale: bool = True,
200
+ rescale_factor: Union[int, float] = 1.0,
201
+ do_normalize: bool = False,
202
+ image_mean: Optional[Union[float, List[float]]] = None,
203
+ image_std: Optional[Union[float, List[float]]] = None,
204
+ **kwargs,
205
+ ) -> None:
206
+ super().__init__(**kwargs)
207
+ self.do_resize = do_resize
208
+ self.resize_factor = resize_factor
209
+ self.do_greyscale = do_greyscale
210
+ self.do_rescale = do_rescale
211
+ self.do_normalize = do_normalize
212
+ self.resample = resample
213
+ self.rescale_factor = rescale_factor
214
+ self.image_mean = (
215
+ image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN[0]
216
+ )
217
+ self.image_std = (
218
+ image_std if image_std is not None else IMAGENET_STANDARD_STD[0]
219
+ )
220
+
221
+ def resize(
222
+ self,
223
+ image: np.ndarray,
224
+ resize_factor: int,
225
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
226
+ data_format: Optional[Union[str, ChannelDimension]] = None,
227
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
228
+ **kwargs,
229
+ ) -> np.ndarray:
230
+ """
231
+ Resize an image to `(size["height"], size["width"])`.
232
+
233
+ Args:
234
+ image (`np.ndarray`):
235
+ Image to resize.
236
+ resize_factor (`int`):
237
+ Value for padding the image to a multiple of the factor.
238
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
239
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
240
+ data_format (`ChannelDimension` or `str`, *optional*):
241
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
242
+ image is used. Can be one of:
243
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
244
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
245
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
246
+ input_data_format (`ChannelDimension` or `str`, *optional*):
247
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
248
+ from the input image. Can be one of:
249
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
250
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
251
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
252
+
253
+ Returns:
254
+ `np.ndarray`: The resized image.
255
+ """
256
+
257
+ return resize_by_factor(
258
+ image,
259
+ resize_factor=resize_factor,
260
+ resample=resample,
261
+ data_format=data_format,
262
+ input_data_format=input_data_format,
263
+ **kwargs,
264
+ )
265
+
266
+ def greyscale(
267
+ self,
268
+ image: np.ndarray,
269
+ data_format: Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST,
270
+ input_data_format: Optional[
271
+ Union[str, ChannelDimension]
272
+ ] = ChannelDimension.FIRST,
273
+ **kwargs,
274
+ ):
275
+ """
276
+ Convert an image to greyscale.
277
+
278
+ Args:
279
+ image (`np.ndarray`):
280
+ Image to greyscale
281
+
282
+ Returns:
283
+ `np.ndarray`: The greyscaled image.
284
+ """
285
+
286
+ return greyscale(
287
+ image,
288
+ data_format=data_format,
289
+ input_data_format=input_data_format,
290
+ **kwargs,
291
+ )
292
+
293
+ def preprocess(
294
+ self,
295
+ images: ImageInput,
296
+ do_resize: Optional[bool] = None,
297
+ resize_factor: Optional[int] = None,
298
+ do_greyscale: Optional[bool] = None,
299
+ resample: PILImageResampling = None,
300
+ do_rescale: Optional[bool] = None,
301
+ rescale_factor: Optional[float] = None,
302
+ do_normalize: Optional[bool] = None,
303
+ image_mean: Optional[Union[float, List[float]]] = None,
304
+ image_std: Optional[Union[float, List[float]]] = None,
305
+ return_tensors: Optional[Union[str, TensorType]] = None,
306
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
307
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
308
+ **kwargs,
309
+ ):
310
+ """
311
+ Preprocess an image or batch of images.
312
+
313
+ Args:
314
+ images (`ImageInput`):
315
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
316
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
317
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
318
+ Whether to resize the image.
319
+ resize_factor (`int`, *optional*, defaults to `self.resize_factor`):
320
+ Value for padding the image to a multiple of the factor.
321
+ resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
322
+ `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
323
+ an effect if `do_resize` is set to `True`.
324
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
325
+ Whether to rescale the image values between [0 - 1].
326
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
327
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
328
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
329
+ Whether to normalize the image.
330
+ return_tensors (`str` or `TensorType`, *optional*):
331
+ The type of tensors to return. Can be one of:
332
+ - Unset: Return a list of `np.ndarray`.
333
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
334
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
335
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
336
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
337
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
338
+ The channel dimension format for the output image. Can be one of:
339
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
340
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
341
+ - Unset: Use the channel dimension format of the input image.
342
+ input_data_format (`ChannelDimension` or `str`, *optional*):
343
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
344
+ from the input image. Can be one of:
345
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
346
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
347
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
348
+ """
349
+ do_resize = do_resize if do_resize is not None else self.do_resize
350
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
351
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
352
+ do_greyscale = do_greyscale if do_greyscale is not None else self.do_greyscale
353
+ resample = resample if resample is not None else self.resample
354
+ rescale_factor = (
355
+ rescale_factor if rescale_factor is not None else self.rescale_factor
356
+ )
357
+ image_mean = image_mean if image_mean is not None else self.image_mean
358
+ image_std = image_std if image_std is not None else self.image_std
359
+
360
+ resize_factor = (
361
+ resize_factor if resize_factor is not None else self.resize_factor
362
+ )
363
+
364
+ images = make_list_of_images(images)
365
+
366
+ if not valid_images(images):
367
+ raise ValueError(
368
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
369
+ "torch.Tensor, tf.Tensor or jax.ndarray."
370
+ )
371
+
372
+ if do_resize and resize_factor is None:
373
+ raise ValueError("Resize factor must be specified if do_resize is True.")
374
+
375
+ if do_rescale and rescale_factor is None:
376
+ raise ValueError("Rescale factor must be specified if do_rescale is True.")
377
+
378
+ # All transformations expect numpy arrays.
379
+ images = [to_numpy_array(image) for image in images]
380
+
381
+ if is_scaled_image(images[0]) and do_rescale:
382
+ logger.warning_once(
383
+ "It looks like you are trying to rescale already rescaled images. If the input"
384
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
385
+ )
386
+
387
+ if input_data_format is None:
388
+ # We assume that all images have the same channel dimension format.
389
+ input_data_format = infer_channel_dimension_format(images[0])
390
+
391
+ if do_resize:
392
+ images = [
393
+ self.resize(
394
+ image=image,
395
+ resize_factor=resize_factor,
396
+ resample=resample,
397
+ input_data_format=input_data_format,
398
+ )
399
+ for image in images
400
+ ]
401
+
402
+ if do_greyscale:
403
+ images = [
404
+ self.greyscale(
405
+ image=image,
406
+ data_format=data_format,
407
+ input_data_format=input_data_format,
408
+ )
409
+ for image in images
410
+ ]
411
+ # the channel would be set to 1, so input data format could't be estimated
412
+ input_data_format = ChannelDimension.FIRST
413
+
414
+ if do_rescale:
415
+ images = [
416
+ self.rescale(
417
+ image=image,
418
+ scale=rescale_factor,
419
+ input_data_format=input_data_format,
420
+ )
421
+ for image in images
422
+ ]
423
+
424
+ if do_normalize:
425
+ images = [
426
+ self.normalize(
427
+ image=image,
428
+ mean=image_mean,
429
+ std=image_std,
430
+ input_data_format=input_data_format,
431
+ )
432
+ for image in images
433
+ ]
434
+
435
+ images = [
436
+ to_channel_dimension_format(
437
+ image, data_format, input_channel_dim=input_data_format
438
+ )
439
+ for image in images
440
+ ]
441
+
442
+ data = {"pixel_values": images}
443
+ return BatchFeature(data=data, tensor_type=return_tensors)
modeling_mle.py CHANGED
@@ -391,23 +391,26 @@ class MLEForAnimeLineExtraction(MLEPretrainedModel):
391
 
392
  self.model = MLEModel(config)
393
 
394
- def postprocess(self, output_tensor: torch.Tensor, input_shape: torch.Size):
395
- pixel_values = output_tensor[0, 0, :, :]
396
  pixel_values = torch.clip(pixel_values, 0, 255)
397
 
398
- pixel_values = pixel_values[0 : input_shape[2], 0 : input_shape[3]]
399
  return pixel_values
400
 
401
  def forward(
402
  self, pixel_values: torch.Tensor, return_dict: bool = True
403
  ) -> tuple[torch.Tensor, ...] | MLEForAnimeLineExtractionOutput:
 
 
 
404
  model_output = self.model(pixel_values)
405
 
406
  if not return_dict:
407
- return (model_output, self.postprocess(model_output, pixel_values.shape))
408
 
409
  else:
410
  return MLEForAnimeLineExtractionOutput(
411
  last_hidden_state=model_output,
412
- pixel_values=self.postprocess(model_output, pixel_values.shape),
413
  )
 
391
 
392
  self.model = MLEModel(config)
393
 
394
+ def postprocess(self, output_tensor: torch.Tensor, input_shape: tuple[int, int]):
395
+ pixel_values = output_tensor[:, 0, :, :]
396
  pixel_values = torch.clip(pixel_values, 0, 255)
397
 
398
+ pixel_values = pixel_values[:, 0 : input_shape[0], 0 : input_shape[1]]
399
  return pixel_values
400
 
401
  def forward(
402
  self, pixel_values: torch.Tensor, return_dict: bool = True
403
  ) -> tuple[torch.Tensor, ...] | MLEForAnimeLineExtractionOutput:
404
+ # height, width
405
+ input_image_size = (pixel_values.shape[2], pixel_values.shape[3])
406
+
407
  model_output = self.model(pixel_values)
408
 
409
  if not return_dict:
410
+ return (model_output, self.postprocess(model_output, input_image_size))
411
 
412
  else:
413
  return MLEForAnimeLineExtractionOutput(
414
  last_hidden_state=model_output,
415
+ pixel_values=self.postprocess(model_output, input_image_size),
416
  )