用于查找相似图像的算法

Algorithm for finding similar images

提问人:kitsune 提问时间:9/17/2008 最后编辑:Robert Harveykitsune 更新时间:6/16/2022 访问量:63075

问:

我需要一种算法来确定两个图像是否“相似”,并识别相似的颜色、亮度、形状等模式。我可能需要一些关于人脑使用哪些参数来“分类”图像的指示。..

我看过基于 hausdorff 的匹配,但这似乎主要用于匹配转换后的对象和形状图案。

算法 数学 图像比较

评论

0赞 blak 7/3/2012
在另一个类似的问题中有一些很好的答案:stackoverflow.com/questions/25977/......
2赞 john k 1/27/2013
很多“可能”和“可能”。有人尝试所有这些建议,并知道什么是最好的吗?
0赞 Christian Safka 10/19/2021
已经过去了 13 年,但我想在这里更新一下,基于 ML 的图像特征向量可以很稳健,并且很容易与余弦相似度进行比较。您可以搜索 img2vec 项目或类似 latentvector.space,以获得更简单的 API 集成(免责声明:我运行该服务)。

答:

1赞 Dark Shikari 9/17/2008 #1

您可以在两个图像之间执行某种块匹配运动估计,并测量残差和运动矢量成本的总和(就像在视频编码器中所做的那样)。这将补偿运动;对于奖励点,请进行仿射变换运动估计(补偿缩放和拉伸等)。您也可以进行重叠块或光流。

5赞 Alejandro Bologna 9/17/2008 #2

您可以使用 Perceptual Image Diff

它是一个命令行实用程序,使用感知指标比较两个图像。也就是说,它使用人类视觉系统的计算模型来确定两个图像在视觉上是否不同,因此像素的微小变化被忽略。此外,它还大大减少了由随机数生成、操作系统或机器架构差异差异引起的误报数量。

1赞 Dima 9/17/2008 #3

首先,您可以尝试使用彩色直方图。但是,您确实需要缩小问题范围。通用图像匹配是一个非常困难的问题。

4赞 Ben 9/17/2008 #4

这是一个难题!这取决于您需要的准确性,也取决于您正在处理的图像类型。您可以使用直方图来比较颜色,但这显然没有考虑这些颜色在图像(即形状)中的空间分布。边缘检测,然后进行某种分割(即挑选形状)可以提供与另一张图像匹配的模式。通过将图像视为像素值的矩阵并比较这些矩阵,可以使用协调矩阵来比较纹理。市面上有一些关于图像匹配和机器视觉的好书——在亚马逊上搜索会发现一些。

希望这有帮助!

0赞 neuroguy123 9/17/2008 #5

关于这个问题,在另一个线程中有一些很好的答案,但我想知道涉及光谱分析的东西是否可行?即,将图像分解为相位和振幅信息并进行比较。这可以避免裁剪、转换和强度差异的一些问题。无论如何,这只是我的推测,因为这似乎是一个有趣的问题。如果你搜索 http://scholar.google.com 我相信你可以想出几篇关于这方面的论文。

评论

0赞 nlucaroni 9/17/2008
光谱分析是傅里叶变换,没有颜色直方图,因为您可以从两个部分重建图像 - 虚构的和真实的。(不知道它是否有效,只是让你知道它不在那个类别中)。
0赞 neuroguy123 9/17/2008
是的,傅里叶变换就是我的意思。
2赞 willasaywhat 9/17/2008 #6

这听起来像是视力问题。您可能需要研究自适应增强以及 Burns 线提取算法。这两个概念应该有助于解决这个问题。如果您不熟悉视觉算法,边缘检测是一个更简单的起点,因为它解释了基础知识。

至于分类参数:

  • 调色板和位置(渐变计算,颜色直方图)
  • 包含的形状 (Ada.提升/训练以检测形状)
2赞 JValente 9/17/2008 #7

根据您需要多少准确的结果,您可以简单地将图像分解为 n x n 像素块并对其进行分析。如果在第一个块中得到不同的结果,则无法停止处理,从而导致一些性能改进。

例如,为了分析正方形,您可以获取颜色值的总和。

3赞 petr k. 9/17/2008 #8

一些图像识别软件解决方案实际上并不是纯粹基于算法的,而是利用神经网络概念。查看 http://en.wikipedia.org/wiki/Artificial_neural_network,即 NeuronDotNet,其中还包括有趣的示例: http://neurondotnet.freehostia.com/index.html

评论

1赞 Monica Heddneck 5/6/2017
neurondotnet.freehostia.com 链接已失效
63赞 freespace 9/17/2008 #9

我做过类似的事情,通过使用小波变换将图像分解为签名。

我的方法是从每个转换通道中挑选最显着的 n 个系数,并记录它们的位置。这是通过根据 abs(power) 对 (power,location) 元组列表进行排序来完成的。相似的图像将具有相似之处,因为它们在相同位置具有显着的系数。

我发现最好将图像转换为 YUV 格式,这样可以有效地加权形状(Y 通道)和颜色(UV 通道)的相似性。

您可以在 mactorii 中找到我对上述内容的实现,不幸的是,我没有像我应该的那样努力:-)

我的一些朋友使用的另一种方法取得了令人惊讶的好效果,方法是简单地将图像大小缩小为4x4像素并将其存储为签名。例如,使用相应的像素计算 2 张图像之间的曼哈顿距离,可以对 2 张图像的相似程度进行评分。我没有关于他们如何执行调整大小的详细信息,因此您可能需要使用可用于该任务的各种算法才能找到合适的算法。

评论

7赞 Alix Axel 10/24/2009
将大小调整为 4x4 方法是一个很棒的主意(并不是说您的方法也不是很好),但第一个方法更简单。
0赞 Ambika 3/24/2016
@freespace,您能否解释一下“使用相应的像素计算 2 张图像之间的曼哈顿距离”
1赞 freespace 3/25/2016
@Ambika:将每个像素的颜色视为长度为 3 的向量,并计算被比较图像中相应像素之间的曼哈顿距离。这为您提供了 4 个曼哈顿距离。如何从中得出一个单一的度量取决于你。最明显的是将它们加在一起。
3赞 EPa 9/18/2008 #10

有使用Kohonen神经网络/自组织映射的相关研究

学术性较强的系统(Google for PicSOM)或学术
性较低的系统(http://www.generation5.org/content/2004/aiSomPic.asp,(可能不合适) 对于所有工作环境))演示文稿存在。

13赞 jilles de wit 9/18/2008 #11

我使用SIFT重新检测不同图像中的同一对象。它确实很强大,但相当复杂,而且可能有点矫枉过正。如果图像应该非常相似,那么基于两个图像之间差异的一些简单参数可以告诉你很多。一些提示:

  • 对图像进行归一化,即通过计算两者的平均亮度并根据比例缩小最亮的图像(以避免在最高级别剪切)来使两个图像的平均亮度相同,特别是如果您对形状比颜色更感兴趣。
  • 每个通道归一化图像的色差总和。
  • 查找图像中的边缘,并测量两个图像中边缘像素之间的距离。(形状)
  • 将图像划分为一组离散区域,并比较每个区域的平均颜色。
  • 在一个(或一组)级别上对图像设置阈值,并计算生成的黑白图像不同的像素数。

评论

0赞 mrgloom 8/3/2012
您能否指出使用类似 Sift 的特征来计算图像相似度的代码?
0赞 jilles de wit 8/6/2012
对不起,我确定有公开可用的代码,但我不知道。这个网站上有一些例子。例如:stackoverflow.com/questions/5461148/...
0赞 dynamichael 8/5/2018
Accord Framework for .Net (accord-framework.net) 有一些很棒的类,用于执行 SURF、BagOfVisualWords、Harris Corner Detection 等,其中包含大量各种内核和聚类算法。
48赞 Alvis 4/22/2009 #12

您可能对 pHash 感兴趣。

感知哈希 n. 音频、视频或图像文件的指纹,在数学上基于其中包含的音频或视频内容。与加密哈希函数不同,加密哈希函数依赖于输入的微小变化导致输出发生剧烈变化的雪崩效应,如果输入在视觉或听觉上相似,则感知哈希值彼此“接近”。

评论

11赞 rodrigo-silveira 5/21/2012
刚刚查看了pHash的网站。他们目前在他们的网站上有这个功能,允许你上传两张图片,它会告诉你它们是否相似。我尝试了大约 10 张相似的图像和 10 张不相似的图像。不幸的是,成功率并不那么令人印象深刻。
3赞 Rohit 4/27/2016
pHash 实际上非常严格,您可能希望使用“ahash”或平均哈希,这往往不那么严格。你可以在这里找到一个 python 实现 github.com/JohannesBuchner/imagehash/blob/master/...
3赞 chris 10/14/2011 #13

计算大幅缩小版本(例如:6x6 像素)的像素颜色值差异的平方和效果很好。相同的图像产生 0,相似的图像产生小数字,不同的图像产生大数字。

上面的其他人首先闯入 YUV 的想法听起来很有趣——虽然我的想法很好用,但我希望我的图像被计算为“不同”,以便它产生正确的结果——即使从色盲观察者的角度来看也是如此。

1赞 Vivek Srinivasan 10/17/2016 #14

很抱歉在讨论中加入较晚。

我们甚至可以使用 ORB 方法来检测两个图像之间的相似特征点。 以下链接给出了 python 中 ORB 的直接实现

http://scikit-image.org/docs/dev/auto_examples/plot_orb.html

甚至 openCV 也直接实现了 ORB。如果您了解更多信息,请关注下面给出的研究文章。

https://www.researchgate.net/publication/292157133_Image_Matching_Using_SIFT_SURF_BRIEF_and_ORB_Performance_Comparison_for_Distorted_Images

6赞 duhaime 3/28/2018 #15

我的实验室也需要解决这个问题,我们使用了 Tensorflow。下面是用于可视化图像相似度的完整应用实现。

有关矢量化图像以进行相似度计算的教程,请查看此页面。这是 Python(同样,请参阅帖子了解完整的工作流程):

from __future__ import absolute_import, division, print_function

"""

This is a modification of the classify_images.py
script in Tensorflow. The original script produces
string labels for input images (e.g. you input a picture
of a cat and the script returns the string "cat"); this
modification reads in a directory of images and 
generates a vector representation of the image using
the penultimate layer of neural network weights.

Usage: python classify_images.py "../image_dir/*.jpg"

"""

# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================

"""Simple image classification with Inception.

Run image classification with Inception trained on ImageNet 2012 Challenge data
set.

This program creates a graph from a saved GraphDef protocol buffer,
and runs inference on an input JPEG image. It outputs human readable
strings of the top 5 predictions along with their probabilities.

Change the --image_file argument to any jpg image to compute a
classification of that image.

Please see the tutorial and website for a detailed description of how
to use this script to perform image recognition.

https://tensorflow.org/tutorials/image_recognition/
"""

import os.path
import re
import sys
import tarfile
import glob
import json
import psutil
from collections import defaultdict
import numpy as np
from six.moves import urllib
import tensorflow as tf

FLAGS = tf.app.flags.FLAGS

# classify_image_graph_def.pb:
#   Binary representation of the GraphDef protocol buffer.
# imagenet_synset_to_human_label_map.txt:
#   Map from synset ID to a human readable string.
# imagenet_2012_challenge_label_map_proto.pbtxt:
#   Text representation of a protocol buffer mapping a label to synset ID.
tf.app.flags.DEFINE_string(
    'model_dir', '/tmp/imagenet',
    """Path to classify_image_graph_def.pb, """
    """imagenet_synset_to_human_label_map.txt, and """
    """imagenet_2012_challenge_label_map_proto.pbtxt.""")
tf.app.flags.DEFINE_string('image_file', '',
                           """Absolute path to image file.""")
tf.app.flags.DEFINE_integer('num_top_predictions', 5,
                            """Display this many predictions.""")

# pylint: disable=line-too-long
DATA_URL = 'http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz'
# pylint: enable=line-too-long


class NodeLookup(object):
  """Converts integer node ID's to human readable labels."""

  def __init__(self,
               label_lookup_path=None,
               uid_lookup_path=None):
    if not label_lookup_path:
      label_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_2012_challenge_label_map_proto.pbtxt')
    if not uid_lookup_path:
      uid_lookup_path = os.path.join(
          FLAGS.model_dir, 'imagenet_synset_to_human_label_map.txt')
    self.node_lookup = self.load(label_lookup_path, uid_lookup_path)

  def load(self, label_lookup_path, uid_lookup_path):
    """Loads a human readable English name for each softmax node.

    Args:
      label_lookup_path: string UID to integer node ID.
      uid_lookup_path: string UID to human-readable string.

    Returns:
      dict from integer node ID to human-readable string.
    """
    if not tf.gfile.Exists(uid_lookup_path):
      tf.logging.fatal('File does not exist %s', uid_lookup_path)
    if not tf.gfile.Exists(label_lookup_path):
      tf.logging.fatal('File does not exist %s', label_lookup_path)

    # Loads mapping from string UID to human-readable string
    proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
    uid_to_human = {}
    p = re.compile(r'[n\d]*[ \S,]*')
    for line in proto_as_ascii_lines:
      parsed_items = p.findall(line)
      uid = parsed_items[0]
      human_string = parsed_items[2]
      uid_to_human[uid] = human_string

    # Loads mapping from string UID to integer node ID.
    node_id_to_uid = {}
    proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
    for line in proto_as_ascii:
      if line.startswith('  target_class:'):
        target_class = int(line.split(': ')[1])
      if line.startswith('  target_class_string:'):
        target_class_string = line.split(': ')[1]
        node_id_to_uid[target_class] = target_class_string[1:-2]

    # Loads the final mapping of integer node ID to human-readable string
    node_id_to_name = {}
    for key, val in node_id_to_uid.items():
      if val not in uid_to_human:
        tf.logging.fatal('Failed to locate: %s', val)
      name = uid_to_human[val]
      node_id_to_name[key] = name

    return node_id_to_name

  def id_to_string(self, node_id):
    if node_id not in self.node_lookup:
      return ''
    return self.node_lookup[node_id]


def create_graph():
  """Creates a graph from saved GraphDef file and returns a saver."""
  # Creates graph from saved graph_def.pb.
  with tf.gfile.FastGFile(os.path.join(
      FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
    graph_def = tf.GraphDef()
    graph_def.ParseFromString(f.read())
    _ = tf.import_graph_def(graph_def, name='')


def run_inference_on_images(image_list, output_dir):
  """Runs inference on an image list.

  Args:
    image_list: a list of images.
    output_dir: the directory in which image vectors will be saved

  Returns:
    image_to_labels: a dictionary with image file keys and predicted
      text label values
  """
  image_to_labels = defaultdict(list)

  create_graph()

  with tf.Session() as sess:
    # Some useful tensors:
    # 'softmax:0': A tensor containing the normalized prediction across
    #   1000 labels.
    # 'pool_3:0': A tensor containing the next-to-last layer containing 2048
    #   float description of the image.
    # 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
    #   encoding of the image.
    # Runs the softmax tensor by feeding the image_data as input to the graph.
    softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')

    for image_index, image in enumerate(image_list):
      try:
        print("parsing", image_index, image, "\n")
        if not tf.gfile.Exists(image):
          tf.logging.fatal('File does not exist %s', image)

        with tf.gfile.FastGFile(image, 'rb') as f:
          image_data =  f.read()

          predictions = sess.run(softmax_tensor,
                          {'DecodeJpeg/contents:0': image_data})

          predictions = np.squeeze(predictions)

          ###
          # Get penultimate layer weights
          ###

          feature_tensor = sess.graph.get_tensor_by_name('pool_3:0')
          feature_set = sess.run(feature_tensor,
                          {'DecodeJpeg/contents:0': image_data})
          feature_vector = np.squeeze(feature_set)        
          outfile_name = os.path.basename(image) + ".npz"
          out_path = os.path.join(output_dir, outfile_name)
          np.savetxt(out_path, feature_vector, delimiter=',')

          # Creates node ID --> English string lookup.
          node_lookup = NodeLookup()

          top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
          for node_id in top_k:
            human_string = node_lookup.id_to_string(node_id)
            score = predictions[node_id]
            print("results for", image)
            print('%s (score = %.5f)' % (human_string, score))
            print("\n")

            image_to_labels[image].append(
              {
                "labels": human_string,
                "score": str(score)
              }
            )

        # close the open file handlers
        proc = psutil.Process()
        open_files = proc.open_files()

        for open_file in open_files:
          file_handler = getattr(open_file, "fd")
          os.close(file_handler)
      except:
        print('could not process image index',image_index,'image', image)

  return image_to_labels


def maybe_download_and_extract():
  """Download and extract model tar file."""
  dest_directory = FLAGS.model_dir
  if not os.path.exists(dest_directory):
    os.makedirs(dest_directory)
  filename = DATA_URL.split('/')[-1]
  filepath = os.path.join(dest_directory, filename)
  if not os.path.exists(filepath):
    def _progress(count, block_size, total_size):
      sys.stdout.write('\r>> Downloading %s %.1f%%' % (
          filename, float(count * block_size) / float(total_size) * 100.0))
      sys.stdout.flush()
    filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
    print()
    statinfo = os.stat(filepath)
    print('Succesfully downloaded', filename, statinfo.st_size, 'bytes.')
  tarfile.open(filepath, 'r:gz').extractall(dest_directory)


def main(_):
  maybe_download_and_extract()
  if len(sys.argv) < 2:
    print("please provide a glob path to one or more images, e.g.")
    print("python classify_image_modified.py '../cats/*.jpg'")
    sys.exit()

  else:
    output_dir = "image_vectors"
    if not os.path.exists(output_dir):
      os.makedirs(output_dir)

    images = glob.glob(sys.argv[1])
    image_to_labels = run_inference_on_images(images, output_dir)

    with open("image_to_labels.json", "w") as img_to_labels_out:
      json.dump(image_to_labels, img_to_labels_out)

    print("all done")
if __name__ == '__main__':
  tf.app.run()

评论

0赞 mostafa8026 9/25/2021
有没有办法改进这种技术?当我添加一个新文件时,我必须重做所有事情以找到相似之处。有没有办法加快添加新 Fiel 的过程?@duhaime
0赞 mostafa8026 9/25/2021
感谢您提供一些关键字或一些资源来阅读,如何加快新文件的分类过程。
0赞 duhaime 9/26/2021
随时@mostafa8026!如果您想尝试向 pixplot 存储库发送拉取请求,我们将不胜感激!