【深度学习】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
相关推荐
心勤则明13 分钟前
用 Spring AI Alibaba 打造智能查询增强引擎
java·人工智能·spring
njsgcs38 分钟前
图卷积是如何处理不同输入长度的 消息传递
人工智能
哥本哈士奇1 小时前
使用OpenClaw的Skills对接本地系统
人工智能
IT_陈寒1 小时前
SpringBoot实战:3个隐藏技巧让你的应用性能飙升50%
前端·人工智能·后端
. . . . .1 小时前
Claude Code Plugins 目录结构与加载机制
人工智能
GJGCY1 小时前
2026企业级智能体架构:记忆机制、RAG检索与任务规划对比
人工智能·经验分享·ai·智能体
SuniaWang1 小时前
《Spring AI + 大模型全栈实战》学习手册系列 ·专题三:《Embedding 模型选型指南:从 MMTEB 排名到实际应用》
人工智能·学习·spring
爱学习的程序媛1 小时前
“数字孪生”详解与前端技术栈
前端·人工智能·计算机视觉·智慧城市·信息与通信
数业智能心大陆1 小时前
科技赋能心育服务,心大陆 AI 减压舱守护校园心灵健康
人工智能·心理健康
程序员Sunday1 小时前
Claude Code 生态爆发:5个必知的新工具
前端·人工智能·后端