{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# Use Lopuhin's dataset for faster image loading.\n# https://www.kaggle.com/lopuhin/panda-2020-level-1-2\n\nimport glob\n\npaths = sorted(glob.glob('../input/panda-2020-level-1-2/train_images/train_images/*_2.jpeg'))\nprint(len(paths))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Use only 4000 images for demonstration.\n\npaths = paths[:4000]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Here comes imagehash\n# https://github.com/JohannesBuchner/imagehash\n\nimport cv2\nimport imagehash\nfrom tqdm import tqdm_notebook as tqdm\nfrom PIL import Image\n\nfuncs = [\n    imagehash.average_hash,\n    imagehash.phash,\n    imagehash.dhash,\n    imagehash.whash,\n    #lambda x: imagehash.whash(x, mode='db4'),\n]\n\nhashes = []\nfor path in tqdm(paths, total=len(paths)):\n\n    image = cv2.imread(path)\n    image = Image.fromarray(image)\n    hashes.append(np.array([f(image).hash for f in funcs]).reshape(256))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# use cuda to speed up\n\nimport torch\n\nhashes = torch.Tensor(np.array(hashes).astype(int)).cuda()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# calc similarity scores\n\nsims = np.array([(hashes[i] == hashes).sum(dim=1).cpu().numpy()/256 for i in range(hashes.shape[0])])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sims.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Let's check image pairs with similarity larget than threshold.\n# You can lower threshold to find more duplicates (and more false positives).\n\nimport matplotlib.pyplot as plt\n\nthreshold = 0.96\nduplicates = np.where(sims > threshold)\n\npairs = {}\nfor i,j in zip(*duplicates):\n    if i == j:\n        continue\n\n    path1 = paths[i]\n    path2 = paths[j]\n    print(path1)\n    print(path2)\n\n    image1 = cv2.imread(path1)\n    image2 = cv2.imread(path2)\n\n    if image1.shape[0] > image1.shape[1] / 2:\n        fig,ax = plt.subplots(figsize=(20,20), ncols=2)\n    elif image1.shape[1] > image1.shape[0] / 2:\n        fig,ax = plt.subplots(figsize=(20,20), nrows=2)\n    else:\n        fig,ax = plt.subplots(figsize=(20,30), nrows=2)\n    ax[0].imshow(image1)\n    ax[1].imshow(image2)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}