{"cells":[{"metadata":{},"cell_type":"markdown","source":"![](https://www.usnews.com/dims4/USNEWS/cf1a1c4/2147483647/resize/1200x%3E/quality/85/?url=http%3A%2F%2Fmedia.beam.usnews.com%2F9d%2F9b%2Fd8dc8f3747b9b147d5c0a7fa1888%2F2-angkor-wat-getty.jpg)\nAngkor: Siem Reap, Cambodia","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Exploration of the Dataset","execution_count":null},{"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 in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport glob\nimport cv2\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_data = pd.read_csv('../input/landmark-recognition-2020/train.csv')\n\nprint(\"Training data size:\",train_data.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_list = glob.glob('../input/landmark-recognition-2020/test/*/*/*/*')\ntrain_list= glob.glob('../input/landmark-recognition-2020/train/*/*/*/*')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print( 'Query', len(test_list), ' test images & ', len(train_list), 'train images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\nplt.title('Training set: number of images per class(line plot)')\nlandmarks_fold = pd.DataFrame(train_data['landmark_id'].value_counts())\nlandmarks_fold.reset_index(inplace=True)\nlandmarks_fold.columns = ['landmark_id','count']\nax = landmarks_fold['count'].plot(logy=True, grid=True)\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=30)\nax.set(xlabel=\"Landmarks\", ylabel=\"Number of images\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\nlandmarks_fold_sorted = pd.DataFrame(train_data['landmark_id'].value_counts())\nlandmarks_fold_sorted.reset_index(inplace=True)\nlandmarks_fold_sorted.columns = ['landmark_id','count']\nlandmarks_fold_sorted = landmarks_fold_sorted.sort_values('landmark_id')\nax = landmarks_fold_sorted.plot.scatter(\\\n     x='landmark_id',y='count',\n     title='Training set: number of images per class(statter plot)')\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=30)\nax.set(xlabel=\"Landmarks\", ylabel=\"Number of images\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (8, 2))\nplt.title('Landmark id density plot')\nsns.kdeplot(train_data['landmark_id'], color=\"tomato\", shade=True)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Test Images Display","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.rcParams[\"axes.grid\"] = True\nf, axarr = plt.subplots(6, 5, figsize=(24, 22))\n\ncurr_row = 0\nfor i in range(30):\n    example = cv2.imread(test_list[i])\n    example = example[:,:,::-1]\n    \n    col = i%6\n    axarr[col, curr_row].imshow(example)\n    if col == 5:\n        curr_row += 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train Images Display","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.rcParams[\"axes.grid\"] = True\nf, axarr = plt.subplots(6, 5, figsize=(24, 22))\n\ncurr_row = 0\nfor i in range(30):\n    example = cv2.imread(train_list[i])\n    example = example[:,:,::-1]\n    \n    col = i%6\n    axarr[col, curr_row].imshow(example)\n    if col == 5:\n        curr_row += 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train Images Display","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.rcParams[\"axes.grid\"] = True\nf, axarr = plt.subplots(6, 5, figsize=(24, 22))\n\ncurr_row = 0\nfor i in range(30):\n    example = cv2.imread(train_list[i])\n    example = example[:,:,::-1]\n    \n    col = i%6\n    axarr[col, curr_row].imshow(example)\n    if col == 5:\n        curr_row += 1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train data","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_data['landmark_id'].describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\nprint(train_data.nunique())\ntrain_data['landmark_id'].value_counts().hist()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from scipy import stats\nsns.set()\nres = stats.probplot(train_data['landmark_id'], plot=plt)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Most frequent landmark ID","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"temp = pd.DataFrame(train_data.landmark_id.value_counts().head(10))\ntemp.reset_index(inplace=True)\ntemp.columns = ['landmark_id', 'count']\ntemp","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\n# plt.figure(figsize=(9, 8))\nplt.title('Most frequent landmarks')\nsns.set_color_codes(\"pastel\")\nsns.barplot(x=\"landmark_id\", y=\"count\", data=temp,\n            label=\"Count\")\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=45)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Least frequent landmark ID","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"temp = pd.DataFrame(train_data.landmark_id.value_counts().tail(10))\ntemp.reset_index(inplace=True)\ntemp.columns = ['landmark_id', 'count']\ntemp","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sns.set()\n# plt.figure(figsize=(9, 8))\nplt.title('Least frequent landmarks')\nsns.set_color_codes(\"pastel\")\nsns.barplot(x=\"landmark_id\", y=\"count\", data=temp,\n            label=\"Count\")\nlocs, labels = plt.xticks()\nplt.setp(labels, rotation=45)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Feature Extraction","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset_path = '../input/google-image-recognition-tutorial'\nimg_building = cv2.imread(os.path.join(dataset_path, 'building_1.jpg'))\nimg_building = cv2.cvtColor(img_building, cv2.COLOR_BGR2RGB)  # Convert from cv's BRG default color order to RGB\n\norb = cv2.ORB_create()  # OpenCV 3 backward incompatibility: Do not create a detector with `cv2.ORB()`.\nkey_points, description = orb.detectAndCompute(img_building, None)\nimg_building_keypoints = cv2.drawKeypoints(img_building, \n                                           key_points, \n                                           img_building, \n                                           flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS) # Draw circles.\nplt.figure(figsize=(16, 16))\nplt.title('ORB Interest Points')\nplt.imshow(img_building_keypoints); plt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"The found interest points/features are circled in the image above. As we can see, some of these points are unique to this scene/building like the points near the top of the two towers. However, others like the ones at the top of the tree may not be distinctive.","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def image_detect_and_compute(detector, img_name):\n    \"\"\"Detect and compute interest points and their descriptors.\"\"\"\n    img = cv2.imread(os.path.join(dataset_path, img_name))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    kp, des = detector.detectAndCompute(img, None)\n    return img, kp, des\n    \n\ndef draw_image_matches(detector, img1_name, img2_name, nmatches=50):\n    \"\"\"Draw ORB feature matches of the given two images.\"\"\"\n    img1, kp1, des1 = image_detect_and_compute(detector, img1_name)\n    img2, kp2, des2 = image_detect_and_compute(detector, img2_name)\n    \n    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\n    matches = bf.match(des1, des2)\n    matches = sorted(matches, key = lambda x: x.distance) # Sort matches by distance.  Best come first.\n    \n    img_matches = cv2.drawMatches(img1, kp1, img2, kp2, matches[:nmatches], img2, flags=2) # Show top 50 matches\n    plt.figure(figsize=(16, 16))\n    plt.title(type(detector))\n    plt.imshow(img_matches); plt.show()\n    \n\norb = cv2.ORB_create()\ndraw_image_matches(orb, 'building_1.jpg', 'building_2.jpg')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"REFERANCES: \n* https://www.kaggle.com/seriousran/google-landmark-retrieval-2020-eda\n* https://www.kaggle.com/codename007/a-very-extensive-landmark-exploratory-analysis\n* https://www.kaggle.com/wesamelshamy/image-feature-extraction-and-matching-for-newbies","execution_count":null}],"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}