{
  "cells": [
    {
      "outputs": [],
      "metadata": {
        "_uuid": "283aba18971f179ff089f71b06c5779c7d960fb0",
        "_cell_guid": "f7e61b0f-5793-4000-985a-f161381774f2",
        "trusted": true,
        "collapsed": true
      },
      "cell_type": "code",
      "source": "%matplotlib inline\n\nimport numpy as np\nimport cv2\nfrom skimage.measure import compare_ssim\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle",
      "execution_count": 23
    },
    {
      "outputs": [],
      "metadata": {
        "trusted": true,
        "_uuid": "9a5bcbd72fe992c9a90ad9298b28eb4bd713cb46"
      },
      "cell_type": "code",
      "source": "def bboxes_car(path, img_id, debug=False):\n    # You need to input the path (train or test) and the car_id (img_id)\n    bboxes = []\n    # Let's iterate over all the angles\n    for num in range(1, 17):\n        # Here we read images i and i+1. \n        # If i==16, we will read the first image\n        # To speed up the things, we can scale the images 5 times\n        fname1 = os.path.join(path, img_id+ '_{:0>2}.jpg'.format(num))\n        fname2 = os.path.join(path, img_id+ '_{:0>2}.jpg'.format((num) % 16+1))\n        img_1_orig = cv2.imread(fname1)\n        h, w = img_1_orig.shape[0],img_1_orig.shape[1],\n        img_1_scaled = cv2.resize(img_1_orig, (w//5, h//5))\n\n        img_2_orig = cv2.imread(fname2)\n        h, w = img_2_orig.shape[0],img_2_orig.shape[1],\n        img_2_scaled = cv2.resize(img_2_orig, (w//5, h//5))\n\n        if debug:\n            plt.figure()\n            plt.subplot(121)\n            plt.title('Current image [{}]'.format(num))\n            plt.imshow(img_1_scaled)\n            plt.subplot(122)\n            plt.title('Next image [{}]'.format((num) % 16+1))\n            plt.imshow(img_2_scaled)\n            plt.show()\n        \n        # As the images differ from each other just a by a small angle of rotation,\n        # We can find their difference and draw a boundign box around the obtained image\n        img1 = cv2.cvtColor(img_1_scaled, cv2.COLOR_BGR2GRAY)\n        img2 = cv2.cvtColor(img_2_scaled, cv2.COLOR_BGR2GRAY)\n\n        # Instead of plain difference, we look for structural similarity\n        score, dimg = compare_ssim(img1, img2, full=True)\n        dimg = (dimg * 255).astype(\"uint8\")\n\n\n        thresh = cv2.threshold(dimg, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]\n        if debug:\n            plt.figure()\n            plt.title('Difference image')\n            plt.imshow(dimg>thresh)\n            plt.show()        \n        \n        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n        \n        ROIS = []\n        for c in cnts[1]:\n            (x, y, w, h) = cv2.boundingRect(c)\n            # We dont want to use too small bounding boxes\n            if w*h > img1.shape[0]*img1.shape[1]//9:\n                ROIS.append([x, y, x+w, y+h])\n\n        ROIS = np.array(ROIS)\n\n        # Now we will draw a boundig box \n        # around all the bounding boxes (there are outliers)\n        x1 = ROIS[:,0].min()\n        y1 = ROIS[:,1].min()\n\n        x2 = ROIS[:,2].max()\n        y2 = ROIS[:,3].max()\n\n        if debug:\n            plt.figure()\n            plt.imshow(img_1_orig)\n            rect = Rectangle((x1*5, y1*5), (x2-x1)*5, (y2-y1)*5, fill=False, color='red')\n            plt.axes().add_patch(rect)\n            plt.show()      \n        bboxes.append([fname1, x1*5, y1*5, x2*5, y2*5])\n    return bboxes\n",
      "execution_count": 33
    },
    {
      "outputs": [],
      "metadata": {
        "trusted": true,
        "_uuid": "365a62db1fe2aa7af0fc73a3a59443372064825d",
        "scrolled": false
      },
      "cell_type": "code",
      "source": "car_id = '0cdf5b5d0ce1'\npath = '../input/train/'\n\nbboxes_car = bboxes_car(path, car_id, debug=True)",
      "execution_count": 36
    },
    {
      "outputs": [],
      "metadata": {
        "collapsed": true,
        "trusted": true,
        "_uuid": "f99cdbb39aef9fcac12628eaab98b873b22797f5"
      },
      "cell_type": "code",
      "source": "",
      "execution_count": null
    }
  ],
  "nbformat": 4,
  "metadata": {
    "language_info": {
      "version": "3.6.1",
      "mimetype": "text/x-python",
      "file_extension": ".py",
      "nbconvert_exporter": "python",
      "codemirror_mode": {
        "version": 3,
        "name": "ipython"
      },
      "pygments_lexer": "ipython3",
      "name": "python"
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3",
      "language": "python"
    }
  },
  "nbformat_minor": 1
}