def search(args):
    '''Search the database for similar files'''
    # open the shelve database
    db = shelve.open(args["shelve"])

    query = Image.open(args["query"])

    if args['hash_name'] == 'grayscale':
        h = imagehash.grayscale_hash(query)
        db_hash = db['grayscale']
    elif args['hash_name'] == 'color':
        h = imagehash.color_hash(query)
        db_hash = db['color']

    print(collections.Counter(len(hex) for hex, image in db_hash.items()).most_common())
    l = [(h - imagehash.hex_to_hash(hex), hex)  for hex, image in db_hash.items()]

    c = collections.Counter(item[0] for item in l)
    print(sorted(c.most_common(), key=lambda item: item[0]))

    command = []
    for strength, item in sorted(l, key=lambda item: item[0]):
        if args['threshold'] < 0 or strength <= args['threshold']:
            print('{} count: {} stength: {}'.format(db_hash[item][0], len(db_hash[item]), strength))
            command.append(db_hash[item][0])
    if command:
        subprocess.call(['feh', '-t', '-F', '-y 150', '-E 150'] + command)
def match(args):
    '''Search the database for matching files'''
    # open the shelve database
    db = shelve.open(args["shelve"])

    # load the query image, compute the difference image hash, and
    # and grab the images from the database that have the same hash
    # value
    query = Image.open(args["query"])

    if args['hash_name'] == 'grayscale':
        h = imagehash.grayscale_hash(query)
        db_hash = db['grayscale']
    elif args['hash_name'] == 'color':
        h = imagehash.color_hash(query)
        db_hash = db['color']


    filenames = db_hash[str(h)]
    print("Found %d images" % (len(filenames)))

    # loop over the images
    for filename in filenames:
        print(filename)
        #image = Image.open(args["dataset"] + "/" + filename)
        #image.show()

    # close the shelve database
    db.close()
def index(args):
    '''Process and index a dataset for futher inspection'''
    # open the shelve database
    db = shelve.open(args["shelve"], writeback=True)
    db['grayscale'] = db.get('grayscale', {})
    db['color'] = db.get('color', {})

    # loop over the image dataset
    for imagePath in glob.iglob(os.path.join(args['dataset'], '*.JPG')):
        # load the image and compute the difference hash
        image = Image.open(imagePath)
        ghash = str(imagehash.grayscale_hash(image))
        chash = str(imagehash.color_hash(image))

        # extract the filename from the path and update the database
        # using the hash as the key and the filename append to the
        # list of values
        filename = os.path.abspath(imagePath)
        db['grayscale'][ghash] = db['grayscale'].get(ghash, []) + [filename]
        db['color'][chash] = db['color'].get(chash, []) + [filename]

    print('{} files indexed'.format(len(db['color'].items())))

    # close the shelf database
    db.close()