{"nbformat": 4, "cells": [{"cell_type": "code", "outputs": [], "metadata": {"_uuid": "3135e74935a3d9a74682b370d3b4f4af96d05d8f", "_cell_guid": "77f2883b-fad7-435a-8358-f5369dab8c9a"}, "execution_count": null, "source": ["import numpy as np\n", "import matplotlib.pyplot as plt\n", "\n", "import bson\n", "import cv2 \n", "\n", "from skimage.data import imread\n", "from io import BytesIO"]}, {"cell_type": "code", "outputs": [], "metadata": {"_uuid": "f6c7d07241b428aa1452d80dbb72fe37ee4d2a61", "collapsed": true, "_cell_guid": "f5c6ed7c-bf74-4745-88fc-758c2284fe42"}, "execution_count": null, "source": ["def squeeze_image(img):\n", "    greyscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n", "    \n", "    all_white = 255 * img.shape[0]\n", "    \n", "    proj_x = np.where(greyscale_img.sum(axis=0) != all_white)[0] \n", "    proj_y = np.where(greyscale_img.sum(axis=1) != all_white)[0] \n", "    \n", "    squeezed_image = img[proj_y[0]:proj_y[-1]+1, proj_x[0]:proj_x[-1]+1]\n", "    \n", "    return squeezed_image"]}, {"cell_type": "code", "outputs": [], "metadata": {"_uuid": "d2cb5846ba52f1a267b24b97d5765185ad2789f5", "_cell_guid": "3475d1ce-2a31-416f-bfb1-42ac34af5477"}, "execution_count": null, "source": ["data = bson.decode_file_iter(open('../input/train_example.bson', 'rb'))\n", "small_data = [next(data) for _ in range(10)]\n", "for d in small_data:\n", "    for i, pic in enumerate(d['imgs']):\n", "        img_bytes = BytesIO(pic['picture'])\n", "        img = imread(img_bytes)\n", "        \n", "        plt.subplots()\n", "        plt.subplot(1, 2, 1)\n", "        plt.imshow(img)\n", "        plt.subplot(1, 2, 2)\n", "        plt.imshow(squeeze_image(img))"]}], "metadata": {"kernelspec": {"language": "python", "name": "python3", "display_name": "Python 3"}, "language_info": {"file_extension": ".py", "codemirror_mode": {"name": "ipython", "version": 3}, "pygments_lexer": "ipython3", "version": "3.6.1", "name": "python", "nbconvert_exporter": "python", "mimetype": "text/x-python"}}, "nbformat_minor": 1}