寻找相似图像的算法

时间:2008-09-16 19:15:18

标签: algorithm math image-comparison

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

我看过基于hausdorff的匹配,但主要是为了匹配变换对象和形状模式。

16 个答案:

答案 0 :(得分:55)

通过使用wavelet transform将图像分解为签名,我做了类似的事情。

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

我发现最好将图像转换为YUV格式,这有效地允许您在形状(Y通道)和颜色(UV通道)中加权相似。

你可以在mactorii中找到我对上述内容的实现,遗憾的是我没有像我应该那样开展工作: - )

另一种方法,我的一些朋友使用了惊人的好结果,只需简单地调整你的图像大小,说4x4像素和存储,这是你的签名。可以通过使用相应的像素计算2个图像之间的Manhattan distance来评分2个图像的相似程度。我没有详细说明他们如何执行调整大小,因此您可能必须使用可用于该任务的各种算法来找到合适的算法。

答案 1 :(得分:42)

pHash可能会让您感兴趣。

  

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

答案 2 :(得分:12)

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

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

答案 3 :(得分:5)

您可以使用Perceptual Image Diff

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

答案 4 :(得分:4)

这是一个难题!这取决于您需要的准确程度,这取决于您使用的图像类型。您可以使用直方图来比较颜色,但这显然没有考虑图像中这些颜色的空间分布(即形状)。边缘检测之后进行某种分割(即挑出形状)可以提供用于与另一图像匹配的图案。您可以使用coocurence矩阵来比较纹理,将图像视为像素值的矩阵,并比较这些矩阵。有一些关于图像匹配和机器视觉的好书 - 在亚马逊上的搜索会找到一些。

希望这有帮助!

答案 5 :(得分:4)

我的实验室也需要解决这个问题,我们使用了Tensorflow。这是一个用于可视化图像相似性的full app实现。

有关为相似度计算矢量化图像的教程,请查看this page。这是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()

答案 6 :(得分:3)

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

答案 7 :(得分:3)

使用Kohonen神经网络/自组织地图进行相关研究

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

答案 8 :(得分:3)

计算显着缩小版本(例如:6x6像素)的像素颜色值的差异的平方和可以很好地工作。相同的图像产生0,相似的图像产生小的数字,不同的图像产生大的图像。

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

答案 9 :(得分:2)

这听起来像一个视力问题。您可能希望了解Adaptive Boosting以及Burns Line Extraction算法。这两个中的概念应该有助于解决这个问题。如果您是视觉算法的新手,边缘检测是一个更简单的起点,因为它解释了基础知识。

就分类参数而言:

  • 调色板&amp;位置(梯度计算,颜色直方图)
  • 包含形状(Ada。提升/训练以检测形状)

答案 10 :(得分:2)

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

为了分析方块,您可以获得颜色值的总和。

答案 11 :(得分:1)

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

答案 12 :(得分:1)

作为第一遍,您可以尝试使用颜色直方图。但是,您确实需要缩小问题范围。通用图像匹配是一个非常难的问题。

答案 13 :(得分:1)

我发现这篇文章非常有用,可以解释它是如何工作的:

http://www.hackerfactor.com/blog/index.php?/archives/432-Looks-Like-It.html

答案 14 :(得分:1)

在讨论的后期加入道歉。

我们甚至可以使用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

答案 15 :(得分:0)

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