Gradio 的月用户量达到 100 万!

阅读更多
Gradio logo
  1. 组件
  2. AnnotatedImage

Gradio 新手? 从这里开始: 入门指南

查看发布历史

AnnotatedImage

gradio.AnnotatedImage(···)
import gradio as gr import numpy as np import requests from io import BytesIO from PIL import Image base_image = "https://gradio-docs-json.s3.us-west-2.amazonaws.com/base.png" building_image = requests.get("https://gradio-docs-json.s3.us-west-2.amazonaws.com/buildings.png") building_image = np.asarray(Image.open(BytesIO(building_image.content)))[:, :, -1] > 0 with gr.Blocks() as demo: gr.AnnotatedImage( value=(base_image, [(building_image, "buildings")]), height=500, ) demo.launch()requests pillow

描述

创建一个组件,用于显示基础图像和彩色注释。注释可以采用矩形(例如,对象检测)或蒙版(例如,图像分割)的形式。由于此组件不接受用户输入,因此很少用作输入组件。

行为

作为输入组件: 将其值作为tuple传递,其中包含一个基础图像的str文件路径和list注释。每个注释本身都是一个tuple,包含一个蒙版(作为图像的str文件路径)和一个str标签。

您的函数应接受以下类型之一
def predict(
	value: tuple[str, list[tuple[str, str]]] | None
)
	...

作为输出组件: 期望一个基础图像和注释列表的元组:tuple[Image, list[Annotation]]Image本身可以是str文件路径、numpy.ndarrayPIL.Image。每个Annotation是一个tuple[Mask, str]Mask可以是4个inttuple,表示边界框坐标(x1、y1、x2、y2),也可以是0-1置信度蒙版,形式为与图像形状相同的numpy.ndarray,而Annotation元组的第二个元素是str标签。

您的函数应返回以下类型之一
def predict(···) -> tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None
	...	
	return value

初始化

参数
🔗
value: tuple[np.ndarray | PIL.Image.Image | str, list[tuple[np.ndarray | tuple[int, int, int, int], str]]] | None
default = None

基础图像和(注释,标签)对列表的元组。

🔗
format: str
default = "webp"

用于保存图像的格式,然后再将其返回到前端,例如“jpeg”或“png”。仅当基础图像从预测函数返回为 numpy 数组或 PIL 图像时,此参数才生效。该格式应受 PIL 库支持。

🔗
show_legend: bool
default = True

如果为 True,将显示注释的图例。

🔗
height: int | str | None
default = None

组件的高度,如果传递数字,则以像素为单位指定;如果传递字符串,则以 CSS 单位指定。这对预处理的图像文件或 numpy 数组没有影响,但会影响显示的图像。

🔗
width: int | str | None
default = None

组件的宽度,如果传递数字,则以像素为单位指定;如果传递字符串,则以 CSS 单位指定。这对预处理的图像文件或 numpy 数组没有影响,但会影响显示的图像。

🔗
color_map: dict[str, str] | None
default = None

将标签映射到颜色的字典。颜色必须指定为十六进制代码。

🔗
label: str | None
default = None

此组件的标签。显示在组件上方,如果此组件有示例表,则也用作标题。如果为 None 且在 `gr.Interface` 中使用,则标签将为此组件分配到的参数名称。

🔗
every: Timer | float | None
default = None

如果 `value` 是函数(否则无效),则持续调用 `value` 以重新计算它。可以提供一个 Timer,其刻度重置 `value`,或提供一个浮点数,表示重置 Timer 的常规间隔。

🔗
inputs: Component | list[Component] | set[Component] | None
default = None

如果 `value` 是函数,则用作计算 `value` 输入的组件(否则无效)。每当输入更改时,`value` 都会重新计算。

🔗
show_label: bool | None
default = None

如果为 True,将显示标签。

🔗
container: bool
default = True

如果为 True,则将组件放置在容器中 - 在边框周围提供一些额外的填充。

🔗
scale: int | None
default = None

与 Row 中相邻组件相比的相对宽度。例如,如果组件 A 的 scale=2,而组件 B 的 scale=1,则 A 的宽度将是 B 的两倍。应为整数。

🔗
min_width: int
default = 160

最小像素宽度,如果屏幕空间不足以满足此值,则将换行。如果某个 scale 值导致此组件比 min_width 更窄,则将首先遵循 min_width 参数。

🔗
visible: bool
default = True

如果为 False,组件将被隐藏。

🔗
elem_id: str | None
default = None

一个可选字符串,用作此组件在 HTML DOM 中的 id。可用于定位 CSS 样式。

🔗
elem_classes: list[str] | str | None
default = None

一个可选的字符串列表,用作此组件在 HTML DOM 中的类。可用于定位 CSS 样式。

🔗
render: bool
default = True

如果为 False,组件将不会在 Blocks 上下文中呈现。如果目的是现在分配事件侦听器,但稍后呈现组件,则应使用此选项。

🔗
key: int | str | None
default = None

如果已分配,将用于在重新渲染时假定身份。在重新渲染中具有相同 key 的组件将保留其值。

🔗
show_fullscreen_button: bool
default = True

如果为 True,将显示一个按钮,允许以全屏模式查看图像。

快捷方式

Interface 字符串快捷方式 初始化

gradio.AnnotatedImage

"annotatedimage"

使用默认值

演示

import gradio as gr
import numpy as np
import random

with gr.Blocks() as demo:
    section_labels = [
        "apple",
        "banana",
        "carrot",
        "donut",
        "eggplant",
        "fish",
        "grapes",
        "hamburger",
        "ice cream",
        "juice",
    ]

    with gr.Row():
        num_boxes = gr.Slider(0, 5, 2, step=1, label="Number of boxes")
        num_segments = gr.Slider(0, 5, 1, step=1, label="Number of segments")

    with gr.Row():
        img_input = gr.Image()
        img_output = gr.AnnotatedImage(
            color_map={"banana": "#a89a00", "carrot": "#ffae00"}
        )

    section_btn = gr.Button("Identify Sections")
    selected_section = gr.Textbox(label="Selected Section")

    def section(img, num_boxes, num_segments):
        sections = []
        for a in range(num_boxes):
            x = random.randint(0, img.shape[1])
            y = random.randint(0, img.shape[0])
            w = random.randint(0, img.shape[1] - x)
            h = random.randint(0, img.shape[0] - y)
            sections.append(((x, y, x + w, y + h), section_labels[a]))
        for b in range(num_segments):
            x = random.randint(0, img.shape[1])
            y = random.randint(0, img.shape[0])
            r = random.randint(0, min(x, y, img.shape[1] - x, img.shape[0] - y))
            mask = np.zeros(img.shape[:2])
            for i in range(img.shape[0]):
                for j in range(img.shape[1]):
                    dist_square = (i - y) ** 2 + (j - x) ** 2
                    if dist_square < r**2:
                        mask[i, j] = round((r**2 - dist_square) / r**2 * 4) / 4
            sections.append((mask, section_labels[b + num_boxes]))
        return (img, sections)

    section_btn.click(section, [img_input, num_boxes, num_segments], img_output)

    def select_section(evt: gr.SelectData):
        return section_labels[evt.index]

    img_output.select(select_section, None, selected_section)

if __name__ == "__main__":
    demo.launch()

		

事件侦听器

描述

事件侦听器允许您响应用户与 Gradio Blocks 应用程序中定义的 UI 组件的交互。当用户与元素交互时,例如更改滑块值或上传图像,将调用一个函数。

支持的事件侦听器

AnnotatedImage 组件支持以下事件侦听器。每个事件侦听器都采用相同的参数,这些参数在下面的事件参数表中列出。

侦听器 描述

AnnotatedImage.select(fn, ···)

当用户选择或取消选择 AnnotatedImage 时的事件侦听器。使用事件数据 gradio.SelectData 来传递value,该值引用 AnnotatedImage 的标签,以及selected,该值引用 AnnotatedImage 的状态。有关如何使用此事件数据的信息,请参阅 EventData 文档

事件参数

参数
🔗
fn: Callable | None | Literal['decorator']
default = "decorator"

触发此事件时要调用的函数。通常是机器学习模型的预测函数。该函数的每个参数都对应一个输入组件,并且该函数应返回单个值或值元组,元组中的每个元素对应一个输出组件。

🔗
inputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default = None

用作输入的 gradio.components 列表。如果函数不接受任何输入,则应为空列表。

🔗
outputs: Component | BlockContext | list[Component | BlockContext] | Set[Component | BlockContext] | None
default = None

用作输出的 gradio.components 列表。如果函数不返回任何输出,则应为空列表。

🔗
api_name: str | None | Literal[False]
default = None

定义端点在 API 文档中的显示方式。可以是字符串、None 或 False。如果设置为字符串,则端点将在 API 文档中以给定名称公开。如果为 None(默认值),则函数的名称将用作 API 端点。如果为 False,则端点将不会在 API 文档中公开,并且下游应用程序(包括 `gr.load` 此应用程序的应用程序)将无法使用此事件。

🔗
scroll_to_output: bool
default = False

如果为 True,则在完成时滚动到输出组件

🔗
show_progress: Literal['full', 'minimal', 'hidden']
default = "full"

事件运行时如何显示进度动画:“full”显示一个覆盖输出组件区域的微调器以及右上角的运行时显示,“minimal”仅显示运行时显示,“hidden”不显示任何进度动画

🔗
show_progress_on: Component | list[Component] | None
default = None

要在其上显示进度动画的组件或组件列表。如果为 None,将在所有输出组件上显示进度动画。

🔗
queue: bool
default = True

如果为 True,则将请求放置在队列中(如果已启用队列)。如果为 False,即使已启用队列,也不会将此事件放入队列中。如果为 None,将使用 gradio 应用程序的队列设置。

🔗
batch: bool
default = False

如果为 True,则该函数应处理一批输入,这意味着它应接受每个参数的输入值列表。列表的长度应相等(并且最大长度为 `max_batch_size`)。然后*要求*该函数返回列表的元组(即使只有一个输出组件),元组中的每个列表对应一个输出组件。

🔗
max_batch_size: int
default = 4

如果从队列调用,则要批量处理的最大输入数(仅在 batch=True 时相关)

🔗
preprocess: bool
default = True

如果为 False,则在运行“fn”之前不会运行组件数据的预处理(例如,如果使用“Image”组件调用此方法,则将其保留为 base64 字符串)。

🔗
postprocess: bool
default = True

如果为 False,则在将“fn”输出返回到浏览器之前,不会运行组件数据的后处理。

🔗
cancels: dict[str, Any] | list[dict[str, Any]] | None
default = None

触发此侦听器时要取消的其他事件列表。例如,设置 cancels=[click_event] 将取消 click_event,其中 click_event 是另一个组件的 .click 方法的返回值。尚未运行的函数(或正在迭代的生成器)将被取消,但当前正在运行的函数将允许完成。

🔗
trigger_mode: Literal['once', 'multiple', 'always_last'] | None
default = None

如果为“once”(除 `.change()` 之外的所有事件的默认值),则在事件挂起时不允许任何提交。如果设置为“multiple”,则在挂起时允许无限提交,而“always_last”(`.change()` 和 `.key_up()` 事件的默认值)将在挂起事件完成后允许第二次提交。

🔗
js: str | Literal[True] | None
default = None

在运行“fn”之前要运行的可选前端 js 方法。js 方法的输入参数是“inputs”和“outputs”的值,返回值应为输出组件的值列表。

🔗
concurrency_limit: int | None | Literal['default']
default = "default"

如果设置,则这是可以同时运行的此事件的最大数目。可以设置为 None 表示没有 concurrency_limit(可以同时运行此事件的任意数量)。设置为“default”以使用默认并发限制(由 `Blocks.queue()` 中的 `default_concurrency_limit` 参数定义,该参数本身默认为 1)。

🔗
concurrency_id: str | None
default = None

如果设置,则这是并发组的 ID。具有相同 concurrency_id 的事件将受到最低设置的 concurrency_limit 的限制。

🔗
show_api: bool
default = True

是否在 Gradio 应用程序的“查看 API”页面或 Gradio 客户端的 “.view_api()” 方法中显示此事件。与将 api_name 设置为 False 不同,将 show_api 设置为 False 仍将允许下游应用程序以及客户端使用此事件。如果 fn 为 None,show_api 将自动设置为 False。

🔗
time_limit: int | None
default = None
🔗
stream_every: float
default = 0.5
🔗
like_user_message: bool
default = False