Если вы заинтересованы в поиске рядом с дубликатами, которые включают в себя изображения, которые были изменены, вы можете применить разницу хэширования. Подробнее о хешировании here. Код ниже отредактирован из сообщения Real Python блога, чтобы заставить его работать на python 3. Он использует связанную выше хэш-библиотеку, которая имеет информацию о разных типах хэширования. Вы должны иметь возможность просто копировать и вставлять скрипты и запускать их непосредственно из командной строки без редактирования сценариев.
Этот первый скрипт (index.py
) создает хеш разницы для каждого изображения, а затем помещает хеш в полку или постоянный словарь, к которому вы можете получить доступ позже, как к базе данных, вместе с именами файлов изображений, которые имеют хэш:
from PIL import Image
import imagehash
import argparse
import shelve
import glob
# This is just so you can run it from the command line
ap = argparse.ArgumentParser()
ap.add_argument('-d', '--dataset', required = True,
help = 'path to imput dataset of images')
ap.add_argument('-s', '--shelve', required = True,
help = 'output shelve database')
args = ap.parse_args()
# open the shelve database
db = shelve.open(args.shelve, writeback = True)
# loop over the image dataset
for imagePath in glob.glob(args.dataset + '/*.jpg'):
# load the image and compute the difference in hash
image = Image.open(imagePath)
h = str(imagehash.dhash(image))
print(h)
# 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 = imagePath[imagePath.rfind('/') + 1:]
db[h] = db.get(h, []) + [filename]
db.close()
Выполнить в командной строке:
python index.py --dataset ./image_directory --shelve db.shelve
Run в Jupyter ноутбук
%run index.py --dataset ./image_directory --shelve db.shelve
Теперь все хранится на полке, вы можете запросить полку с именем файла изображения, которое вы хотите проверить, и распечатает имена файлов изображений, которые соответствуют, а также откройте соответствующие изображения (search.py
):
from PIL import Image
import imagehash
import argparse
import shelve
# arguments for command line
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help="path to dataset of images")
ap.add_argument("-s", "--shelve", required=True,
help="output the shelve database")
ap.add_argument("-q", "--query", required=True,
help="path to the query image")
args = ap.parse_args()
# open the shelve database
db = shelve.open(args.shelve)
# Load the query image, compute the difference image hash, and grab the images
# from the database that have the same hash value
query = Image.open(args.query)
h = str(imagehash.dhash(query))
filenames = db[h]
print("found {} images".format(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()
Выполнить в командной строке, чтобы просмотреть image_directory
для изображений с той же хэш, как ./directory/someimage.jpg
python search.py —dataset ./image_directory —shelve db.shelve —query ./directory/someimage.jpg
Опять же, это модифицированный из Real Python
блоге связанного выше, которая написана для python2.7, и должны выработайте коробку! Просто измените командную строку так, как вам нужно. Если я правильно помню, проблема с python 2/3 была только с argparse
, а не с библиотеками изображений.