Skip to content

对象

pipeline pipeline

对象管道读取图像列表并返回检测到的对象列表。

示例

以下展示了一个使用此管道的简单示例。

from txtai.pipeline import Objects

# 创建并运行管道
objects = Objects()
objects("图像文件路径")

请参阅以下链接以获取更详细的示例。

笔记本 描述
生成图像标题并检测对象 图像的标题和对象检测 在 Colab 中打开

配置驱动示例

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

config.yml

# 使用小写类名创建管道
objects:

# 使用工作流运行管道
workflow:
  objects:
    tasks:
      - action: objects

使用工作流运行

from txtai import Application

# 使用工作流创建并运行管道
app = Application("config.yml")
list(app.workflow("objects", ["图像文件路径"]))

使用 API 运行

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

curl \
  -X POST "http://localhost:8000/workflow" \
  -H "Content-Type: application/json" \
  -d '{"name":"objects", "elements":["图像文件路径"]}'

方法

管道的 Python 文档。

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

Source code in txtai/pipeline/image/objects.py
21
22
23
24
25
26
27
28
def __init__(self, path=None, quantize=False, gpu=True, model=None, classification=False, threshold=0.9, **kwargs):
    if not PIL:
        raise ImportError('Objects pipeline is not available - install "pipeline" extra to enable')

    super().__init__("image-classification" if classification else "object-detection", path, quantize, gpu, model, **kwargs)

    self.classification = classification
    self.threshold = threshold

__call__(images, flatten=False, workers=0)

Applies object detection/image classification models to images. Returns a list of (label, score).

This method supports a single image or a list of images. If the input is an image, the return type is a 1D list of (label, score). If text is a list, a 2D list of (label, score) is returned with a row per image.

Parameters:

Name Type Description Default
images

image|list

required
flatten

flatten output to a list of objects

False
workers

number of concurrent workers to use for processing data, defaults to None

0

Returns:

Type Description

list of (label, score)

Source code in txtai/pipeline/image/objects.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def __call__(self, images, flatten=False, workers=0):
    """
    Applies object detection/image classification models to images. Returns a list of (label, score).

    This method supports a single image or a list of images. If the input is an image, the return
    type is a 1D list of (label, score). If text is a list, a 2D list of (label, score) is
    returned with a row per image.

    Args:
        images: image|list
        flatten: flatten output to a list of objects
        workers: number of concurrent workers to use for processing data, defaults to None

    Returns:
        list of (label, score)
    """

    # 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]

    # Run pipeline
    results = (
        self.pipeline(values, num_workers=workers)
        if self.classification
        else self.pipeline(values, threshold=self.threshold, num_workers=workers)
    )

    # Build list of (id, score)
    outputs = []
    for result in results:
        # Convert to (label, score) tuples
        result = [(x["label"], x["score"]) for x in result if x["score"] > self.threshold]

        # Sort by score descending
        result = sorted(result, key=lambda x: x[1], reverse=True)

        # Deduplicate labels
        unique = set()
        elements = []
        for label, score in result:
            if label not in unique:
                elements.append(label if flatten else (label, score))
                unique.add(label)

        outputs.append(elements)

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