【深度学习】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
相关推荐
河南凹凸环境艺术设计14 分钟前
性价比高的民宿酒店设计企业
大数据·人工智能·python
饼饼学习空间智能22 分钟前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
千里念行客24026 分钟前
业绩与创新双兑现!科伦博泰的Biopharma进阶之路
大数据·人工智能
深蓝海域知识库1 小时前
评学问练考:大模型AI智能学院——重塑学习培训
人工智能
漂流瓶jz1 小时前
【AI】一文读懂大模型生态:分类/参数/结构/训练/GPU/评测/排行/社区
人工智能·llm·openai
一点一木1 小时前
Hermes Desktop 重磅更新,Bot Mode 正式上线——把你的 AI 变成一支可协作的专属团队
人工智能·agent
蛋先生DX2 小时前
你瘦不下来但大模型可以:量化原理了解一下
深度学习·算法·llm
xushichang123_2 小时前
客服中心想要依托 AI 升级客户服务体验,可选择哪些云联络中心架构方案?:优先评估 Amazon Connect+客服 AI Agent
人工智能
jikemaoshiyanshi2 小时前
企业如何借助一体化 AI 工作台赋能办公提效?Amazon Quick 可适配哪些企业业务场景?—— 从智能问答、数据解析到流程自动化的全域 AI 能力平台
人工智能
IT_陈寒2 小时前
Redis的DEL命令竟然没删掉数据?我踩的这个坑你得知道
前端·人工智能·后端