{"cells":[
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "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\n\nsample_sub = pd.read_csv('../input/sample_submission.csv')\ntrain_files = pd.DataFrame([[f,f.split(\"/\")[3].split(\".\")[0].split(\"_\")[0],f.split(\"/\")[3].split(\".\")[0].split(\"_\")[1]] for f in glob.glob(\"../input/train_sm/*.jpeg\")])\ntrain_files.columns = ['path', 'group', 'pic_no']\ntest_files = pd.DataFrame([[f,f.split(\"/\")[3].split(\".\")[0].split(\"_\")[0],f.split(\"/\")[3].split(\".\")[0].split(\"_\")[1]] for f in glob.glob(\"../input/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)\n\n"
 },
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "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, pcntDownsize = 1.0, withTransparency=False):\n    \n    #Read image1\n    image1 = cv2.imread(imp1)\n    \n    # perform the resizing of the image by pcntDownsize and create a Grayscale version\n    dim1 = (int(image1.shape[1] * pcntDownsize), int(image1.shape[0] * pcntDownsize))\n    img1 = cv2.resize(image1, dim1, interpolation = cv2.INTER_AREA)\n    img1Gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)\n    \n    #Read image2\n    image2 = cv2.imread(imp2)\n    \n    # perform the resizing of the image by pcntDownsize and create a Grayscale version\n    dim2 = (int(image2.shape[1] * pcntDownsize), int(image2.shape[0] * pcntDownsize))\n    img2 = cv2.resize(image2, dim2, interpolation = cv2.INTER_AREA)\n    img2Gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)\n    \n    #use BRISK to create keypoints in each image\n    brisk = cv2.BRISK_create()\n    kp1, des1 = brisk.detectAndCompute(img1Gray,None)\n    kp2, des2 = brisk.detectAndCompute(img2Gray,None)\n    \n    # use BruteForce algorithm to detect matches among image keypoints \n    dm = cv2.DescriptorMatcher_create(\"BruteForce\")\n    \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    \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    \n    \n    H, mask = cv2.findHomography(kp2_,kp1_, cv2.RANSAC, 4.0)\n    h1,w1 = img1.shape[:2]\n    h2,w2 = img2.shape[:2]\n    \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    \n    pts2_ = cv2.perspectiveTransform(pts2, H)\n    pts = np.concatenate((pts1, pts2_), axis=0)\n    \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    \n    t = [-xmin,-ymin]\n    \n    Ht = np.array([[1,0,t[0]],[0,1,t[1]],[0,0,1]])\n    \n    #warp the colour version of image2\n    im = cv2.warpPerspective(img2, Ht.dot(H), (xmax-xmin, ymax-ymin))\n    \n    #overlay colur version of image1 to warped image2\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        \n        #imGray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n        #imColor = cv2.applyColorMap(imGray, cv2.COLORMAP_JET)\n        \n        im =(im[:,:,2] - bim[:,:,2])\n        #im = cv2.addWeighted(im,0.6,bim,0.6,0)\n    else:\n        im[t[1]:h1+t[1],t[0]:w1+t[0]] = img1\n    return(im)"
 },
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "source": "img = im_stitcher(train_images.path[0], train_images.path[4], 0.4, True)\nplt.rcParams['figure.figsize'] = (12.0, 12.0)\nplt.imshow(img); plt.axis('off')"
 },
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "source": "plt.rcParams['figure.figsize'] = (20, 20)\n\nfor j in range(1,5):\n    for i in range(j+1,6):\n        img = im_stitcher(train_images.path[j-1], train_images.path[i-1], 0.4, True)\n        plt.subplot(4,4,i-1+(j-1)*4)\n        plt.imshow(img);plt.axis('off')\n"
 }
],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"}}, "nbformat": 4, "nbformat_minor": 0}