跳过内容

ImageHash

pipeline pipeline

图像哈希流水线生成感知图像哈希。这些哈希可用于检测近似重复的图像。此方法不由机器学习模型支持,并非旨在查找概念上相似的图像。

示例

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

from txtai.pipeline import ImageHash

# Create and run pipeline
ihash = ImageHash()
ihash("path to image file")

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

Notebook 描述
近似重复图像检测 识别重复和近似重复的图像 Open In Colab

配置驱动的示例

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

config.yml

# Create pipeline using lower case class name
imagehash:

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

使用工作流运行

from txtai import Application

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

使用API运行

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

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

方法

该流水线的 Python 文档。

__init__(algorithm='average', size=8, strings=True)

创建一个 ImageHash 流水线。

参数

名称 类型 描述 默认值
algorithm

图像哈希算法 (average, perceptual, difference, wavelet, color)

'average'
size

哈希大小

8
strings

如果为 True(默认值),则输出十六进制字符串;否则,流水线返回 numpy 数组

True
源代码位于 txtai/pipeline/image/imagehash.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def __init__(self, algorithm="average", size=8, strings=True):
    """
    Creates an ImageHash pipeline.

    Args:
        algorithm: image hashing algorithm (average, perceptual, difference, wavelet, color)
        size: hash size
        strings: outputs hex strings if True (default), otherwise the pipeline returns numpy arrays
    """

    if not PIL:
        raise ImportError('ImageHash pipeline is not available - install "pipeline" extra to enable')

    self.algorithm = algorithm
    self.size = size
    self.strings = strings

__call__(images)

生成感知图像哈希。

参数

名称 类型 描述 默认值
images

image|list

必需

返回值

类型 描述

哈希列表

源代码位于 txtai/pipeline/image/imagehash.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def __call__(self, images):
    """
    Generates perceptual image hashes.

    Args:
        images: image|list

    Returns:
        list of hashes
    """

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

    # Convert images to hashes
    hashes = [self.ihash(image) for image in values]

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