Upload image_processor.py with huggingface_hub
Browse files- image_processor.py +35 -0
image_processor.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
from typing import Dict, Any
|
3 |
+
|
4 |
+
from transformers.image_processing_utils import ImageProcessingMixin, BatchFeature
|
5 |
+
from timm.data.transforms_factory import create_transform
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
class ClassificationImageProprocessor(ImageProcessingMixin):
|
10 |
+
def __init__(self, data_config, **kwargs):
|
11 |
+
super().__init__(**kwargs)
|
12 |
+
self.data_config = data_config
|
13 |
+
self._transform = create_transform(**data_config)
|
14 |
+
|
15 |
+
def __call__(self, images, **kwargs) -> BatchFeature:
|
16 |
+
"""Preprocess an image or a batch of images."""
|
17 |
+
return self.preprocess(images, **kwargs)
|
18 |
+
|
19 |
+
def preprocess(self, images, return_tensors=None, **kwargs) -> BatchFeature:
|
20 |
+
images = [self._transform(image) for image in images]
|
21 |
+
data = {"pixel_values": images}
|
22 |
+
return BatchFeature(data=data, tensor_type=return_tensors)
|
23 |
+
|
24 |
+
def to_dict(self) -> Dict[str, Any]:
|
25 |
+
"""
|
26 |
+
Serializes this instance to a Python dictionary.
|
27 |
+
|
28 |
+
Returns:
|
29 |
+
`Dict[str, Any]`: Dictionary of all the attributes that make up this image processor instance.
|
30 |
+
"""
|
31 |
+
output = copy.deepcopy(self.__dict__)
|
32 |
+
output.pop("_transform", None)
|
33 |
+
output["image_processor_type"] = self.__class__.__name__
|
34 |
+
|
35 |
+
return output
|