Upload monochrome_detection/image.py with huggingface_hub
Browse files
monochrome_detection/image.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from os import PathLike
|
| 2 |
+
from typing import Union, BinaryIO, List, Tuple
|
| 3 |
+
|
| 4 |
+
from PIL import Image
|
| 5 |
+
|
| 6 |
+
__all__ = [
|
| 7 |
+
'ImageTyping', 'load_image',
|
| 8 |
+
'MultiImagesTyping', 'load_images',
|
| 9 |
+
]
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _is_readable(obj):
|
| 13 |
+
return hasattr(obj, 'read') and hasattr(obj, 'seek')
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
ImageTyping = Union[str, PathLike, bytes, bytearray, BinaryIO, Image.Image]
|
| 17 |
+
MultiImagesTyping = Union[ImageTyping, List[ImageTyping], Tuple[ImageTyping, ...]]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def load_image(image: ImageTyping, mode=None):
|
| 21 |
+
if isinstance(image, (str, PathLike, bytes, bytearray, BinaryIO)) or _is_readable(image):
|
| 22 |
+
image = Image.open(image)
|
| 23 |
+
elif isinstance(image, Image.Image):
|
| 24 |
+
pass # just do nothing
|
| 25 |
+
else:
|
| 26 |
+
raise TypeError(f'Unknown image type - {image!r}.')
|
| 27 |
+
|
| 28 |
+
if mode is not None and image.mode != mode:
|
| 29 |
+
image = image.convert(mode)
|
| 30 |
+
|
| 31 |
+
return image
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_images(images: MultiImagesTyping, mode=None) -> List[Image.Image]:
|
| 35 |
+
if not isinstance(images, (list, tuple)):
|
| 36 |
+
images = [images]
|
| 37 |
+
|
| 38 |
+
return [load_image(item, mode) for item in images]
|