{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":45867,"databundleVersionId":6924515,"sourceType":"competition"},{"sourceId":6661702,"sourceType":"datasetVersion","datasetId":3844162}],"dockerImageVersionId":30579,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\n# Use Lopuhin's dataset for faster image loading.\n# https://www.kaggle.com/lopuhin/panda-2020-level-1-2\n\nimport glob\nfrom pathlib import Path\n\npaths = sorted(glob.glob('/kaggle/input/ubc-reduced-png-2964x2964/*.png'))\nprint(len(paths))\n\nimgids = [Path(p).stem.split('_')[0] for p in paths]\n\nprint(len(imgids))\nprint(len(set(imgids)))\n\nimport torch","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-10T13:35:35.25455Z","iopub.execute_input":"2023-11-10T13:35:35.254944Z","iopub.status.idle":"2023-11-10T13:35:35.295951Z","shell.execute_reply.started":"2023-11-10T13:35:35.254914Z","shell.execute_reply":"2023-11-10T13:35:35.294882Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 類似画像検索\n### 結論\nPANDAコンペののような類似画像はなし。","metadata":{}},{"cell_type":"code","source":"import 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 = []\n\nfor path in tqdm(paths, total=len(paths)):\n    image = cv2.imread(path)\n    image = Image.fromarray(image)\n    hashes.append(np.array([f(image).hash for f in funcs]).reshape(256))","metadata":{"execution":{"iopub.status.busy":"2023-11-10T13:35:35.298221Z","iopub.execute_input":"2023-11-10T13:35:35.298598Z","iopub.status.idle":"2023-11-10T13:45:16.66933Z","shell.execute_reply.started":"2023-11-10T13:35:35.298567Z","shell.execute_reply":"2023-11-10T13:45:16.668292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# use cuda to speed up\nhashes = torch.Tensor(np.array(hashes).astype(int))\n\n# calc similarity scores\nsims = np.array([(hashes[i] == hashes).sum(dim=1).cpu().numpy()/256 for i in range(hashes.shape[0])])\n\nsims2 = sims.copy()\nnp.fill_diagonal(sims2, 0)\n\nthreshold = 0.90\nduplicates = np.where(sims2 > threshold)\n# duplicates = np.where((sims2 > threshold))  (sims2 < (threshold + 0.1))\nprint(len(duplicates[0]))\nprint(sims2)","metadata":{"execution":{"iopub.status.busy":"2023-11-10T13:47:43.845029Z","iopub.execute_input":"2023-11-10T13:47:43.845446Z","iopub.status.idle":"2023-11-10T13:47:43.950782Z","shell.execute_reply.started":"2023-11-10T13:47:43.845417Z","shell.execute_reply":"2023-11-10T13:47:43.949671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\ncount = 20\ntmp = 0\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    print(sims2[i, j])\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()\n    \n    tmp += 1\n    if tmp > count:\n        break","metadata":{"execution":{"iopub.status.busy":"2023-11-10T13:50:50.109316Z","iopub.execute_input":"2023-11-10T13:50:50.109819Z","iopub.status.idle":"2023-11-10T13:51:57.752737Z","shell.execute_reply.started":"2023-11-10T13:50:50.109784Z","shell.execute_reply":"2023-11-10T13:51:57.751548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}