跳到内容

图像描述

pipeline pipeline

图像描述流水线读取图像列表并返回这些图像的描述列表。

示例

下面展示了一个使用此流水线的简单示例。

from txtai.pipeline import Caption

# Create and run pipeline
caption = Caption()
caption("path to image file")

有关更详细的示例,请参见下方链接。

Notebook 描述
生成图像描述并检测对象 图像的描述和对象检测 Open In Colab

配置驱动示例

流水线可以通过 Python 或配置运行。可以使用流水线的全小写名称在 配置 中实例化流水线。配置驱动的流水线通过 工作流API 运行。

config.yml

# Create pipeline using lower case class name
caption:

# Run pipeline with workflow
workflow:
  caption:
    tasks:
      - action: caption

通过工作流运行

from txtai import Application

# Create and run pipeline with workflow
app = Application("config.yml")
list(app.workflow("caption", ["path to image file"]))

通过 API 运行

CONFIG=config.yml uvicorn "txtai.api:app" &

curl \
  -X POST "https://:8000/workflow" \
  -H "Content-Type: application/json" \
  -d '{"name":"caption", "elements":["path to image file"]}'

方法

该流水线的 Python 文档。

__init__(path=None, quantize=False, gpu=True, model=None, **kwargs)

源代码位于 txtai/pipeline/image/caption.py
21
22
23
24
25
26
def __init__(self, path=None, quantize=False, gpu=True, model=None, **kwargs):
    if not PIL:
        raise ImportError('Captions pipeline is not available - install "pipeline" extra to enable')

    # Call parent constructor
    super().__init__("image-to-text", path, quantize, gpu, model, **kwargs)

__call__(images)

为图像构建描述。

此方法支持单个图像或图像列表。如果输入是图像,返回类型为字符串。如果输入是列表,则返回字符串列表

参数

名称 类型 描述 默认值
images

image|list

必需

返回值

类型 描述

描述列表

源代码位于 txtai/pipeline/image/caption.py
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def __call__(self, images):
    """
    Builds captions for images.

    This method supports a single image or a list of images. If the input is an image, the return
    type is a string. If text is a list, a list of strings is returned

    Args:
        images: image|list

    Returns:
        list of captions
    """

    # Convert single element to list
    values = [images] if not isinstance(images, list) else images

    # Open images if file strings
    values = [Image.open(image) if isinstance(image, str) else image for image in values]

    # Get and clean captions
    captions = []
    for result in self.pipeline(values):
        text = " ".join([r["generated_text"] for r in result]).strip()
        captions.append(text)

    # Return single element if single element passed in
    return captions[0] if not isinstance(images, list) else captions