Algorithm for finding similar images

I need an algorithm that can determine whether two images are 'similar' and recognizes similar patterns of color, brightness, shape etc.. I might need some pointers as to what parameters the human brain uses to 'categorize' images. ..

I have looked at hausdorff based matching but that seems mainly for matching transformed objects and patterns of shape.

60771 次浏览

You could perform some sort of block-matching motion estimation between the two images and measure the overall sum of residuals and motion vector costs (much like one would do in a video encoder). This would compensate for motion; for bonus points, do affine-transformation motion estimation (compensates for zooms and stretching and similar). You could also do overlapped blocks or optical flow.

You could use Perceptual Image Diff

It's a command line utility that compares two images using a perceptual metric. That is, it uses a computational model of the human visual system to determine if two images are visually different, so minor changes in pixels are ignored. Plus, it drastically reduces the number of false positives caused by differences in random number generation, OS or machine architecture differences.

As a first pass, you can try using color histograms. However, you really need to narrow down your problem domain. Generic image matching is a very hard problem.

It's a difficult problem! It depends on how accurate you need to be, and it depends on what kind of images you are working with. You can use histograms to compare colours, but that obviously doesn't take into account the spatial distribution of those colours within the images (i.e. the shapes). Edge detection followed by some kind of segmentation (i.e. picking out the shapes) can provide a pattern for matching against another image. You can use coocurence matrices to compare textures, by considering the images as matrices of pixel values, and comparing those matrices. There are some good books out there on image matching and machine vision -- A search on Amazon will find some.

Hope this helps!

There are some good answers in the other thread on this, but I wonder if something involving a spectral analysis would work? I.e., break the image down to it's phase and amplitude information and compare those. This may avoid some of the issues with cropping, transformation and intensity differences. Anyway, that's just me speculating since this seems like an interesting problem. If you searched http://scholar.google.com I'm sure you could come up with several papers on this.

This sounds like a vision problem. You might want to look into Adaptive Boosting as well as the Burns Line Extraction algorithm. The concepts in these two should help with approaching this problem. Edge detection is an even simpler place to start if you're new to vision algorithms, as it explains the basics.

As far as parameters for categorization:

  • Color Palette & Location (Gradient calculation, histogram of colors)
  • Contained Shapes (Ada. Boosting/Training to detect shapes)

Depending on how much accurate results you need, you can simply break the images in n x n pixels blocks and analyze them. If you get different results in the first block you can't stop processing, resulting in some performance improvements.

For analyzing the squares you can for example get the sum of the color values.

Some image recognition software solutions are actually not purely algorithm-based, but make use of the neural network concept instead. Check out http://en.wikipedia.org/wiki/Artificial_neural_network and namely NeuronDotNet which also includes interesting samples: http://neurondotnet.freehostia.com/index.html

I have done something similar, by decomposing images into signatures using wavelet transform.

My approach was to pick the most significant n coefficients from each transformed channel, and recording their location. This was done by sorting the list of (power,location) tuples according to abs(power). Similar images will share similarities in that they will have significant coefficients in the same places.

I found it was best to transform in the image into YUV format, which effectively allows you weight similarity in shape (Y channel) and colour (UV channels).

You can in find my implementation of the above in mactorii, which unfortunately I haven't been working on as much as I should have :-)

Another method, which some friends of mine have used with surprisingly good results, is to simply resize your image down to say, a 4x4 pixel and store that as your signature. How similar 2 images are can be scored by say, computing the Manhattan distance between the 2 images, using corresponding pixels. I don't have the details of how they performed the resizing, so you may have to play with the various algorithms available for that task to find one which is suitable.

There is related research using Kohonen neural networks/self organizing maps

Both more academic systems (Google for PicSOM ) or less academic
( http://www.generation5.org/content/2004/aiSomPic.asp , (possibly not suitable for all work enviroments)) presentations exist.

I've used SIFT to re-detect te same object in different images. It is really powerfull but rather complex, and might be overkill. If the images are supposed to be pretty similar some simple parameters based on the difference between the two images can tell you quite a bit. Some pointers:

  • Normalize the images i.e. make the average brightness of both images the same by calculating the average brightness of both and scaling the brightest down according to the ration (to avoid clipping at the highest level)) especially if you're more interested in shape than in colour.
  • Sum of colour difference over normalized image per channel.
  • find edges in the images and measure the distance betwee edge pixels in both images. (for shape)
  • Divide the images in a set of discrete regions and compare the average colour of each region.
  • Threshold the images at one (or a set of) level(s) and count the number of pixels where the resulting black/white images differ.

pHash might interest you.

perceptual hash n. a fingerprint of an audio, video or image file that is mathematically based on the audio or visual content contained within. Unlike cryptographic hash functions which rely on the avalanche effect of small changes in input leading to drastic changes in the output, perceptual hashes are "close" to one another if the inputs are visually or auditorily similar.

I found this article very helpful explaining how it works:

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

Calculating the sum of the squares of the differences of the pixel colour values of a drastically scaled-down version (eg: 6x6 pixels) works nicely. Identical images yield 0, similar images yield small numbers, different images yield big ones.

The other guys above's idea to break into YUV first sounds intriguing - while my idea works great, I want my images to be calculated as "different" so that it yields a correct result - even from the perspective of a colourblind observer.

Apologies for joining late in the discussion.

We can even use ORB methodology to detect similar features points between two images. Following link gives direct implementation of ORB in python

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

Even openCV has got direct implementation of ORB. If you more info follow the research article given below.

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

My lab needed to solve this problem as well, and we used Tensorflow. Here's a full app implementation for visualizing image similarity.

For a tutorial on vectorizing images for similarity computation, check out this page. Here's the Python (again, see the post for full workflow):

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()