【深度学习】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
相关推荐
taoqick2 小时前
对PosWiseFFN的改进: MoE、PKM、UltraMem
人工智能·pytorch·深度学习
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
预测模型的开发与应用研究3 小时前
数据分析的AI+流程(个人经验)
人工智能·数据挖掘·数据分析
源大模型3 小时前
OS-Genesis:基于逆向任务合成的 GUI 代理轨迹自动化生成
人工智能·gpt·智能体
PowerBI学谦4 小时前
Python in Excel高级分析:一键RFM分析
大数据·人工智能·pandas
运维开发王义杰5 小时前
AI: Unsloth + Llama 3 微调实践,基于Colab
人工智能·llama
charles_vaez5 小时前
开源模型应用落地-LangGraph101-探索 LangGraph 短期记忆
深度学习·语言模型·自然语言处理
文心快码 Baidu Comate5 小时前
文心快码|AI重构开发新范式,从工具到人机协同
人工智能·ai编程·文心快码·智能编程助手·全栈编程
WHATEVER_LEO6 小时前
【每日论文】Latent Radiance Fields with 3D-aware 2D Representations
人工智能·深度学习·神经网络·机器学习·计算机视觉·自然语言处理
浮华落定6 小时前
DeepSeek+即梦 做AI视频
人工智能·chatgpt·音视频