Spaces:
Paused
Paused
# Copyright 2024 The HuggingFace Inc. team. All rights reserved. | |
# | |
# Licensed under the Apache License, Version 2.0 (the "License"); | |
# you may not use this file except in compliance with the License. | |
# You may obtain a copy of the License at | |
# | |
# http://www.apache.org/licenses/LICENSE-2.0 | |
# | |
# Unless required by applicable law or agreed to in writing, software | |
# distributed under the License is distributed on an "AS IS" BASIS, | |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
# See the License for the specific language governing permissions and | |
# limitations under the License. | |
import os | |
from typing import Callable, Union | |
import PIL.Image | |
import PIL.ImageOps | |
import requests | |
def load_image( | |
image: Union[str, PIL.Image.Image], convert_method: Callable[[PIL.Image.Image], PIL.Image.Image] = None | |
) -> PIL.Image.Image: | |
""" | |
Loads `image` to a PIL Image. | |
Args: | |
image (`str` or `PIL.Image.Image`): | |
The image to convert to the PIL Image format. | |
convert_method (Callable[[PIL.Image.Image], PIL.Image.Image], optional): | |
A conversion method to apply to the image after loading it. When set to `None` the image will be converted | |
"RGB". | |
Returns: | |
`PIL.Image.Image`: | |
A PIL Image. | |
""" | |
if isinstance(image, str): | |
if image.startswith("http://") or image.startswith("https://"): | |
image = PIL.Image.open(requests.get(image, stream=True).raw) | |
elif os.path.isfile(image): | |
image = PIL.Image.open(image) | |
else: | |
raise ValueError( | |
f"Incorrect path or URL. URLs must start with `http://` or `https://`, and {image} is not a valid path." | |
) | |
elif isinstance(image, PIL.Image.Image): | |
image = image | |
else: | |
raise ValueError( | |
"Incorrect format used for the image. Should be a URL linking to an image, a local path, or a PIL image." | |
) | |
image = PIL.ImageOps.exif_transpose(image) | |
if convert_method is not None: | |
image = convert_method(image) | |
else: | |
image = image.convert("RGB") | |
return image | |