【深度学习】Diffusers Utilities load_image

go 复制代码
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

这个函数 load_image 允许以下几种类型的输入:

  1. 字符串类型 (str)

    • 代表图像的 URL (以 http://https:// 开头)。
    • 代表图像的 本地文件路径
  2. PIL 图像对象 (PIL.Image.Image)

    • 直接传入已经加载的 PIL 图像对象。

详细解释

  1. 字符串类型 (str)

    • URL :如果输入是一个 URL(以 http://https:// 开头),函数会通过网络请求获取图像并加载为 PIL 图像对象。

      python 复制代码
      if image.startswith("http://") or image.startswith("https://"):
          image = PIL.Image.open(requests.get(image, stream=True).raw)
    • 本地文件路径 :如果输入是一个本地文件路径,函数会打开该文件并加载为 PIL 图像对象。

      python 复制代码
      elif os.path.isfile(image):
          image = PIL.Image.open(image)
  2. PIL 图像对象 (PIL.Image.Image)

    • 如果输入已经是一个 PIL 图像对象,函数会直接使用该对象,无需再加载。

      python 复制代码
      elif isinstance(image, PIL.Image.Image):
          image = image
相关推荐
qq_42551618几秒前
iPhone录音文件怕意外丢失?支持云端备份的录音APP实测
人工智能·智能手机·powerpoint
guo_xiao_xiao_5 分钟前
YOLO室内训练场橙色环形训练圈目标检测数据集-156张
人工智能·yolo·目标检测
凡泰AI8 分钟前
金融机构如何选择自己的企业级 AI桌面终端?
人工智能·agent·企业级ai·企业级agent
微硬创新10 分钟前
耐达讯自动化:16路4-20mA模拟信号,该怎样平稳接入PROFINET控制系统?
人工智能·物联网·网络协议·自动化·信息与通信
水如烟14 分钟前
孤能子视角:原始思维篇·0 总纲——关系场的直接编织:认知的底层呼吸
人工智能
Luminbox紫创测控15 分钟前
太阳模拟器如何模拟真实太阳?积分球与氙灯光源技术解析
人工智能·测试工具·安全性测试·uv·测试标准
mlidongfeng15 分钟前
[AI][shmem] Aiv 直驱RDMA
人工智能
九硕智慧建筑一体化厂家23 分钟前
从电费支出到碳资产收益,直流照明如何让商业楼宇实现柔性用能
运维·人工智能·智慧城市
资深电气设计30 分钟前
800V直流断路器选型指南:ABB电气产品技术解析
人工智能·科技·创业创新·业界资讯
梦想的旅途241 分钟前
企业微信API二次开发:接入 AI 大模型实现外部群智能问答
人工智能·自动化·二次开发·企业微信