使用 scikit-image 中的 match_template 检查模板是否存在

Check if a template exists using match_template from scikit-image

我正在尝试使用 match_template method from the scikit-image library to check if a template exists inside an image and get its X and Y positions. I'm using the scikit-image template matching example

我的代码如下所示:

#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import numpy as np
from skimage import io
from skimage.color import rgb2gray
from skimage.feature import match_template


def exists(image, template):
    """Perform a template match and returns the X and Y positions.

    Args:
        image (str): path to the full image.
        template (str): path to the template image.

    Returns:
        If there is a match, return the X and Y positions.
        If there is not match, return None.
    """

    image = io.imread(image, as_gray=True)
    template = io.imread(template, as_gray=True)

    result = match_template(image, template, pad_input=True)

    return np.unravel_index(np.argmax(result), result.shape)[::-1]

    # unreachable
    return None

当它存在于图像中时它正确地执行模板匹配,但是当模板不存在时它给了我错误的 X 和 Y 位置。

如何检查模板是否不存在以及 return None 在这种情况下?

我对 match_template 的输出了解不够,无法给你一个明确的答案,但关键是函数 always returns 只是相关图像:

Returns
-------
output : array
    Response image with correlation coefficients.

因此,要确定您没有找到模板匹配项,您必须确定 output 的最大值低于某个阈值。我不知道什么是好的门槛。一般来说,我认为它会根据您的模板大小和您想要允许的 noise/variation 大小而有所不同。我的建议是你 运行 match_template 在一些正例(包含模板,有不同数量的噪声)和一些负例(没有)上,绘制两个分布以选择一个阈值。然后你可以添加:

def exists(image, template, threshold):
    ...
    max_corr = np.max(result)
    if max_corr > threshold:
        return np.unravel_index(np.argmax(result), result.shape)[::-1]
    else:
        return None