{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"scrolled":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)\n\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":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true,"scrolled":true},"cell_type":"code","source":"import time\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\nfrom PIL import Image\nfrom PIL import ImageFilter\nimport multiprocessing\nimport random; random.seed(2016);\nimport cv2\nimport re\nimport os, glob\nsample_sub = pd.read_csv('../input/draper-satellite-image-chronology/sample_submission.csv')\ntrain_files = pd.DataFrame([[f,f.split(\"/\")[4].split(\".\")[0].split(\"_\")[0],f.split(\"/\")[4].split(\".\")[0].split(\"_\")[1]] for f in glob.glob(\"../input/draper-satellite-image-chronology/train_sm/*.jpeg\")])\ntrain_files.columns = ['path', 'group', 'pic_no']\ntest_files = pd.DataFrame([[f,f.split(\"/\")[4].split(\".\")[0].split(\"_\")[0],f.split(\"/\")[4].split(\".\")[0].split(\"_\")[1]] for f in glob.glob(\"../input/draper-satellite-image-chronology/test_sm/*.jpeg\")])\ntest_files.columns = ['path', 'group', 'pic_no']\nprint(len(train_files),len(test_files),len(sample_sub))\ntrain_images = train_files[train_files[\"group\"]=='set107']\ntrain_images = train_images.sort_values(by=[\"pic_no\"], ascending=[1]).reset_index(drop=True)\nplt.rcParams['figure.figsize'] = (12.0, 12.0)\nplt.subplots_adjust(wspace=0, hspace=0)\ni_ = 0\na = []\nfor l in train_images.path:\n    im = cv2.imread(l)\n    plt.subplot(5, 2, i_+1).set_title(l)\n    plt.hist(im.ravel(),256,[0,256]); plt.axis('off')\n    a.append([im.mean(),im.max(),im.min()])\n    plt.subplot(5, 2, i_+2).set_title(l)\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i_ += 2\nprint(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"564b5def0e455e079b2a808b3d0ba1b4bd60c958"},"cell_type":"code","source":"kaze = cv2.KAZE_create()\nakaze = cv2.AKAZE_create()\nbrisk = cv2.BRISK_create()\n\nplt.rcParams['figure.figsize'] = (7.0, 18.0)\nplt.subplots_adjust(wspace=0, hspace=0)\ni = 0\nfor detector in [kaze, akaze, brisk]:\n    start_time = time.time()\n    im = cv2.imread(train_images.path[1])\n    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n    (kps, descs) = detector.detectAndCompute(gray, None)       \n    cv2.drawKeypoints(im, kps, im, (0, 255, 0))\n    plt.subplot(3, 1, i+1).set_title(list(['kaze','akaze','brisk'])[i] + \" \" + str(round(((time.time() - start_time)/60),5)))\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a4272ffe6d3fc673ce8eeb9066d8cddf2bd75861","scrolled":false},"cell_type":"code","source":"print(cv2.__version__)\n\nimg1 = cv2.imread(train_images.path[1], 0)\nimg2 = cv2.imread(train_images.path[2], 0)\nbrisk = cv2.BRISK_create()\nkp1, des1 = brisk.detectAndCompute(img1,None)\nkp2, des2 = brisk.detectAndCompute(img2,None)\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\nmatches = bf.match(des1,des2)\nmatches = sorted(matches, key = lambda x:x.distance)\nimg1 = cv2.imread(train_images.path[1])\nimg2 = cv2.imread(train_images.path[2])\nimg3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:100], flags=2, outImg=img2, matchColor = (0,255,0))\nplt.rcParams['figure.figsize'] = (14.0, 8.0)\nplt.imshow(cv2.cvtColor(img3, cv2.COLOR_BGR2RGB)); plt.axis('off')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bc6c1658e2e9b652d5587c2ffe9f896fe156153a"},"cell_type":"code","source":"brisk = cv2.BRISK_create()\ndm = cv2.DescriptorMatcher_create(\"BruteForce\")\n\ndef c_resize(img, ratio):\n    wh = (int(img.shape[1] * ratio), int(img.shape[0] * ratio))\n    img = cv2.resize(img, wh, interpolation = cv2.INTER_AREA)\n    return img\n    \ndef im_stitcher(imp1, imp2, imsr = 1.0, withTransparency=False):\n    img1 = cv2.imread(imp1, 0)\n    img2 = cv2.imread(imp2, 0)\n    if imsr < 1.0:\n        img1 = c_resize(img1,imsr); img2 = c_resize(img2,imsr)\n    h1,w1 = img1.shape[:2]\n    h2,w2 = img2.shape[:2]\n    kp1, des1 = brisk.detectAndCompute(img1,None)\n    kp2, des2 = brisk.detectAndCompute(img2,None)\n    matches = dm.knnMatch(des1,des2, 2)\n    matches_ = []\n    for m in matches:\n        if len(m) == 2 and m[0].distance < m[1].distance * 0.75:\n            matches_.append((m[0].trainIdx, m[0].queryIdx))\n    kp1_ = np.float32([kp1[m[1]].pt for m in matches_]).reshape(-1,1,2)\n    kp2_ = np.float32([kp2[m[0]].pt for m in matches_]).reshape(-1,1,2)\n    H, mask = cv2.findHomography(kp2_,kp1_, cv2.RANSAC, 4.0)\n    pts1 = np.float32([[0,0],[0,h1],[w1,h1],[w1,0]]).reshape(-1,1,2)\n    pts2 = np.float32([[0,0],[0,h2],[w2,h2],[w2,0]]).reshape(-1,1,2)\n    pts2_ = cv2.perspectiveTransform(pts2, H)\n    pts = np.concatenate((pts1, pts2_), axis=0)\n    [xmin, ymin] = np.int32(pts.min(axis=0).ravel() - 0.5)\n    [xmax, ymax] = np.int32(pts.max(axis=0).ravel() + 0.5)\n    t = [-xmin,-ymin]\n    Ht = np.array([[1,0,t[0]],[0,1,t[1]],[0,0,1]])\n    img1 = cv2.imread(imp1)\n    img2 = cv2.imread(imp2)\n    if imsr < 1.0:\n        img1 = c_resize(img1,imsr); img2 = c_resize(img2,imsr)\n    im = cv2.warpPerspective(img2, Ht.dot(H), (xmax-xmin, ymax-ymin))\n    if withTransparency == True:\n        h3,w3 = im.shape[:2]\n        bim = np.zeros((h3,w3,3), np.uint8)\n        bim[t[1]:h1+t[1],t[0]:w1+t[0]] = img1\n        im = cv2.addWeighted(im,1.0,bim,0.9,0)\n    else:\n        im[t[1]:h1+t[1],t[0]:w1+t[0]] = img1\n    return im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2c0e84ace1b22ad83a7635bf678ce760721f3bce"},"cell_type":"code","source":"img = im_stitcher(train_images.path[1], train_images.path[4], 0.5, True)\nplt.rcParams['figure.figsize'] = (12.0, 12.0)\nimg[np.where((img < [20,20,20]).all(axis = 2))] = [255,255,255]\nplt.imshow(img); plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f99639b2714b1ef12b85f5bb1a3ce189efdd62a7"},"cell_type":"code","source":"img = cv2.imread(train_images.path[1])\ncv2.imwrite('panoramic.jpeg',img)\nplt.rcParams['figure.figsize'] = (12.0, 12.0)\nfor i in range(1,5):\n    img = im_stitcher(train_images.path[i], 'panoramic.jpeg', 0.5, False)\n    cv2.imwrite('panoramic.jpeg',img)\nimg[np.where((img < [20,20,20]).all(axis = 2))] = [255,255,255]\nplt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"c27c00331622d8efa7a3fc7f0ae9e270cdd71c53"},"cell_type":"code","source":"files = pd.DataFrame([[f,int(f.split(\"/\")[6][3:-5])] for f in glob.glob(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img*.jpeg\")])\nfiles.columns = ['path', 'pic_no']\nfiles = files.sort_values(by=[\"pic_no\"], ascending=[1]).reset_index(drop=True)\nplt.rcParams['figure.figsize'] = (12.0, 12.0)\nplt.subplots_adjust(wspace=0, hspace=0)\ni_ = 0\na = []\nfor l in files.path[0:10]:\n    im = cv2.imread(l)\n    plt.subplot(10, 2, i_+1)\n    plt.hist(im.ravel(),256,[0,256]); plt.axis('off')\n    a.append([im.mean(),im.max(),im.min()])\n    plt.subplot(10, 2, i_+2)\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i_ += 2\nprint(a)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"9fbe74aede68ca070e8e51d54b92a9901f4e3742"},"cell_type":"code","source":"i_ = 0\na = []\nfor l in files.path[10:20]:\n    im = cv2.imread(l)\n    plt.subplot(10, 2, i_+1)\n    plt.hist(im.ravel(),256,[0,256]); plt.axis('off')\n    a.append([im.mean(),im.max(),im.min()])\n    plt.subplot(10, 2, i_+2)\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i_ += 2\nprint(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"41f5f910a65309b45412fd470d6dc567aab30f33"},"cell_type":"code","source":"i_ = 0\na = []\nfor l in files.path[20:30]:\n    im = cv2.imread(l)\n    plt.subplot(10, 2, i_+1)\n    plt.hist(im.ravel(),256,[0,256]); plt.axis('off')\n    a.append([im.mean(),im.max(),im.min()])\n    plt.subplot(10, 2, i_+2)\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i_ += 2\nprint(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1c41dcaf09fadf8c25467b5f4c0ec37bae75a18d"},"cell_type":"code","source":"i_ = 0\na = []\nfor l in files.path[30:40]:\n    im = cv2.imread(l)\n    plt.subplot(10, 2, i_+1)\n    plt.hist(im.ravel(),256,[0,256]); plt.axis('off')\n    a.append([im.mean(),im.max(),im.min()])\n    plt.subplot(10, 2, i_+2)\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i_ += 2\nprint(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"545d0e3f9e31a9a1c280ec9c6e6455a37a8980ce"},"cell_type":"code","source":"i_ = 0\na = []\nfor l in files.path[40:50]:\n    im = cv2.imread(l)\n    plt.subplot(10, 2, i_+1)\n    plt.hist(im.ravel(),256,[0,256]); plt.axis('off')\n    a.append([im.mean(),im.max(),im.min()])\n    plt.subplot(10, 2, i_+2)\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i_ += 2\nprint(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"72caabbf8ba93e5d26ccf8c4e386bed546a617e6"},"cell_type":"code","source":"kaze = cv2.KAZE_create()\nakaze = cv2.AKAZE_create()\nbrisk = cv2.BRISK_create()\n\nplt.rcParams['figure.figsize'] = (7.0, 18.0)\nplt.subplots_adjust(wspace=0, hspace=0)\ni = 0\nfor detector in [kaze, akaze, brisk]:\n    start_time = time.time()\n    im = cv2.imread(files.path[20])\n    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n    (kps, descs) = detector.detectAndCompute(gray, None)       \n    cv2.drawKeypoints(im, kps, im, (0, 255, 0))\n    plt.subplot(3, 1, i+1).set_title(list(['kaze','akaze','brisk'])[i] + \" \" + str(round(((time.time() - start_time)/60),5)))\n    plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB)); plt.axis('off')\n    i+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3a81d9d7e8cb9eb8fc95cf167fdb3d560d628e07"},"cell_type":"code","source":"img1 = cv2.imread(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img10.jpeg\", 0)\nimg2 = cv2.imread(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img11.jpeg\", 0)\nbrisk = cv2.BRISK_create()\nkp1, des1 = brisk.detectAndCompute(img1,None)\nkp2, des2 = brisk.detectAndCompute(img2,None)\nbf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)\nmatches = bf.match(des1,des2)\nmatches = sorted(matches, key = lambda x:x.distance)\nimg1 = cv2.imread(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img20.jpeg\")\nimg2 = cv2.imread(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img21.jpeg\")\nimg3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:100], flags=2, outImg=img2, matchColor = (0,255,0))\nplt.rcParams['figure.figsize'] = (14.0, 8.0)\nplt.imshow(cv2.cvtColor(img3, cv2.COLOR_BGR2RGB)); plt.axis('off')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a5dd2e3d9f94467a7582626a6b185777e7996bf"},"cell_type":"code","source":"files = pd.DataFrame([[f,f.split(\"/\")[6]] for f in glob.glob(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img*.jpeg\")])\nimg = cv2.imread(\"../input/under-vachle/images/IMAGES/IMAGE SET 1/img9.jpeg\")\ncv2.imwrite('panoramic.jpeg',img)\nplt.rcParams['figure.figsize'] = (12.0, 12.0)\nfor i in range(10,11):\n    img = im_stitcher( '../input/under-vachle/images/IMAGES/IMAGE SET 1/img%d.jpeg' % i , 'panoramic.jpeg', 0.5, False)\n    cv2.imwrite('panoramic.jpeg',img)\nimg[np.where((img < [20,20,20]).all(axis = 2))] = [255,255,255]\nplt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)); plt.axis('off')","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}