{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"from PIL import Image\nimport cv2\nimport numpy as np\nfrom tqdm import tqdm\nfrom skimage.morphology import skeletonize\nimport os\n\ndef get_data(n):\n    image_id = train[n][0]\n    image, raw_labels = Image.open(image_path(image_id)), train[n][1]\n    image = image.convert('L')\n    image = np.array(image, dtype=np.uint8)\n    return image_id, image, parse_labels(raw_labels)\n\ndef threshold(image, thinning=False, soft=False):\n    ret,im = cv2.threshold(image,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n    im = 255 - im\n    iters = 2 if soft else 4\n    kernel = np.ones((2,2),np.uint8)\n    im = cv2.dilate(im,kernel,iterations = iters)\n    im = cv2.erode(im,kernel,iterations = iters)\n    if thinning:\n        im = skeletonize(im/255)\n        im = np.asarray(im*255, dtype=np.uint8)\n        im = cv2.dilate(im,kernel,iterations = 2)\n    return im\n\ndef parse_labels(labels):\n    label_parts = labels.split()\n    res = []\n    for r1, r2 in zip(range(0, len(label_parts), 5), range(5, len(label_parts), 5)):\n        codepoint, x, y, w, h = label_parts[r1:r2]\n        x,y,w,h = map(int, [x,y,w,h])\n        res.append((codepoint, x,y,w,h))\n    return res\n\ndef get_crop(image, label):\n    c,x,y,w,h = label\n    crop = image[y:y+h,x:x+w]\n    return crop\n\ndef clean(image, labels):\n    tmp_image = threshold(image, True, True)\n    zeros = np.zeros(tmp_image.shape, dtype=np.uint8)\n    for label in labels:\n        c,x,y,w,h = label\n        crop = get_crop(tmp_image, label)\n        zeros[y:y+h, x:x+w] = crop\n    return 255 - zeros\n\ndef get_codepoint(label):\n    return label[0]\n\ndef show(*images, size=400):\n    prev = np.hstack(images)\n    timg = Image.fromarray(prev)\n    timg.thumbnail((size*len(images),size), Image.ANTIALIAS)\n    return timg\n\ntrain = [x.split(\",\") for x in open(\"../input/train.csv\").read().strip().split(\"\\n\")[1:]]\nimage_path = lambda image_id : \"../input/train_images/\" + image_id + \".jpg\"\n\nindex = 10\nimage_id, image, labels = get_data(index)\ncleaned_image = 255 - threshold(image, labels)\nshow(cleaned_image, size=800)","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":false},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}