【深度学习】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
相关推荐
NeoGressAI外贸数字化5 分钟前
外贸独立站robots.txt怎么写:6个AI爬虫放行规则
人工智能·爬虫
米软科技25 分钟前
数字化转型:多元化集团如何构建高效的AI数字化中台?
大数据·人工智能
幼儿园蛋小黄26 分钟前
从 STM32N647 的 AI 部署入门嵌入式:一条可落地的学习路线
人工智能·stm32·学习
Leo.yuan31 分钟前
Dora企业级Data Agent应用指南:存量BI复用、私有化部署与权限管理
大数据·人工智能
火山引擎开发者社区35 分钟前
从代码执行到任务持续运行:企业级 Agent Sandbox 的云原生实践
人工智能
Nablai37 分钟前
LX系列多国语言能力技术解析:ESP32双栈架构下的语种策略设计
人工智能·架构
老牛日常随笔1 小时前
微软开源Flint Chart:AI画图表总是画不对?让编译器来画,AI只写数据就行
人工智能·microsoft
jimmyleeee1 小时前
Agent安全之六:(ASI06)记忆与上下文投毒——当 AI 把“昨天的错误”当成“今天的真理”
网络·人工智能·安全
deepseek231 小时前
Claude Code 2.1.314 新增工作目录写入边界:工具权限、沙箱与安全盲区怎么分层
人工智能·ai agent·claude code
Yolanda_20221 小时前
week3深度学习处理文本(上)
人工智能·深度学习