<jupyter_start><jupyter_text>Image Hashing & Similarity The following notebook finds, displays and saves the images from *sample_images* matched in *all_images*. The matched images are saved in **data/results** directory- **data/all_images** consists of a huge collection of images from 101 different categories. - **data/sample_images** contains the images we want to search from the above collection.- Add images to *data/sample_images* from *data/all_images* to test it outdataset - http://www.vision.caltech.edu/Image_Datasets/Caltech101/101_ObjectCategories.tar.gz<jupyter_code>import os
from imutils import paths
import time
import cv2
import shutil
import os
import imagewizard as iw
import numpy as np
from matplotlib.pyplot import imshow
import numpy as np
import matplotlib.pyplot as plt
def display_image(image, title="Title"):
    if not isinstance(image, np.ndarray):
        data = np.asarray(image)
    else:
        data = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    plt.title(title)
    ax = plt.subplot(1, 1, 1)
    
    plt.imshow(data)
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    
    return plt.show()
def display_single_subplot(img, n_row, n_col, cell_num, title, sim_score = None):
    if not isinstance(img, np.ndarray):
        img = np.asarray(img)
    else:
        img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        
    ax = plt.subplot(n_row, n_col, cell_num)
    
    if sim_score is not None:
        plt.title(str(title) + "\nHamming Distance : " + str(sim_score))
    else:
        plt.title(str(title))
        
    plt.imshow(img)
    plt.tight_layout()
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
ALL_IMAGES_PATH = "data\\all_images"
SAMPLE_IMAGES_PATH = "data\\sample_images"
print("[INFO] computing hashes for all images in dataset")

all_images_paths = list(paths.list_images(ALL_IMAGES_PATH))
sample_images_paths = list(paths.list_images(SAMPLE_IMAGES_PATH))
len(all_images_paths)
all_hashes = {}
start = time.time()
hashing = iw.Hashing()
sim = iw.Similarity()
# loop over all images paths
for p in all_images_paths:
    # load the image from disk
    image = cv2.imread(p)

    # if the image is None then we could not load it from disk (so
    # skip it)
    if image is None:
        continue
    
    # compute the hash
    src_hash = hashing.dhash(image=image, order='bgr')

    # update the all_hashes dictionary
    l = all_hashes.get(src_hash, [])
    l.append(p)
    all_hashes[src_hash] = l
# show timing for hashing "all" images, then start computing the
# hashes for "sample" images
print("[INFO] processed {} images in {:.2f} seconds".format(len(all_hashes), time.time() - start))
print("[INFO] computing hashes for sample images...")
# loop over the sample image paths
for p in sample_images_paths:
    # load the image from disk
    image = cv2.imread(p)

    # if the image is None then we could not load it from disk (so
    # skip it)
    if image is None:
        continue

    # compute the hash
    query_hash = hashing.dhash(image=image, order='bgr')

    for src_hash in all_hashes:
        score = sim.similarity(metric='hamming', value_src=src_hash, value_query=query_hash)
        matched_images_paths = []
        
        # if the score is 0, then the src image and query image are the same
        if score == 0:
            
            ###################################################################################
            # Save the Query image & Matched Image
            ##################################################################################
            
            # get the path of matched image from all_images directory
            matched_images_paths = all_hashes.get(src_hash, [])
            
            for matched_images_path in matched_images_paths:
                
                # base directory tells the category the image belongs to
                base_dir = matched_images_path.split(os.path.sep)[-2]

                # destination folder + file name for storing the results
                dst_dir = os.path.join("data", "results", base_dir)

                if not os.path.exists(dst_dir):
                    os.makedirs(dst_dir)

                # name of the matched image
                img_name = matched_images_path.split(os.path.sep)[-1]   

                # add score to the image name
                result_file_name = os.path.join(dst_dir, str(score)+"_"+img_name)

                # original query image from sample_images
                query_image_file = os.path.join(dst_dir, "~query.jpg")

                # save results of matched images
                shutil.copy(matched_images_path, result_file_name)
                # save original query image in the results folder to compare the matched image
                shutil.copy(p, query_image_file)

                ##################################################################################
                # Display the Query image & Matched Image
                ##################################################################################

                # create a copy of matched images path
                src_paths = [matched_images_path]

                # we will display the query image too. Insert the original query image to the list 
                src_paths.insert(0, p)
                n = len(src_paths)
                
                # display every matched result
                for idx, i in enumerate(src_paths):
                    image_data = cv2.imread(i)
                    if idx == 0:
                        title = "Query Image"
                        sim_score = None
                    else:
                        title = str("Image found: \n"+str(i))
                        sim_score = score
                    display_single_subplot(image_data, 1, n, idx+1, title , sim_score)
                plt.tight_layout()
                plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13514868025392582, 'fraction_numerical': 0.005178750417641162, 'mean_word_length': 2.4113960113960116, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '398299', 'license': 'MIT', 'n_tokens_mistral': 1738, 'n_tokens_neox': 1660, 'n_words': 490, 'path': 'demo/.ipynb_checkpoints/exact_matching_images-checkpoint.ipynb', 'repo_name': 'PriceSpider-NeuIntel/imagewizard', 'size': '5986'}