{"cells":[{"cell_type":"markdown","metadata":{"_cell_guid":"ccc128d6-b369-cfbc-8a83-d49a138cc912"},"source":"This kernels aims at segmenting the cervix using the technique presented in this paper: https://www.researchgate.net/publication/24041301_Automatic_Detection_of_Anatomical_Landmarks_in_Uterine_Cervix_Images"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"fb67719e-6367-0dac-9c81-85acc797b305"},"outputs":[],"source":"import matplotlib.pyplot as plt\n%matplotlib inline\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport math\nfrom sklearn import mixture\nfrom sklearn.utils import shuffle\nfrom skimage import measure\nfrom glob import glob\nimport os\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\nTRAIN_DATA = \"../input/train\"\ntype_1_files = glob(os.path.join(TRAIN_DATA, \"Type_1\", \"*.jpg\"))\ntype_1_ids = np.array([s[len(os.path.join(TRAIN_DATA, \"Type_1\"))+1:-4] for s in type_1_files])\ntype_2_files = glob(os.path.join(TRAIN_DATA, \"Type_2\", \"*.jpg\"))\ntype_2_ids = np.array([s[len(os.path.join(TRAIN_DATA, \"Type_2\"))+1:-4] for s in type_2_files])\ntype_3_files = glob(os.path.join(TRAIN_DATA, \"Type_3\", \"*.jpg\"))\ntype_3_ids = np.array([s[len(os.path.join(TRAIN_DATA, \"Type_3\"))+1:-4] for s in type_3_files])\n\ntype_1_ids = type_1_ids[:30]\n\ndef get_filename(image_id, image_type):\n    \"\"\"\n    Method to get image file path from its id and type   \n    \"\"\"\n    if image_type == \"Type_1\" or \\\n        image_type == \"Type_2\" or \\\n        image_type == \"Type_3\":\n        data_path = os.path.join(TRAIN_DATA, image_type)\n    elif image_type == \"Test\":\n        data_path = TEST_DATA\n    elif image_type == \"AType_1\" or \\\n          image_type == \"AType_2\" or \\\n          image_type == \"AType_3\":\n        data_path = os.path.join(ADDITIONAL_DATA, image_type)\n    else:\n        raise Exception(\"Image type '%s' is not recognized\" % image_type)\n\n    ext = 'jpg'\n    return os.path.join(data_path, \"{}.{}\".format(image_id, ext))\n\ndef get_image_data(image_id, image_type):\n    \"\"\"\n    Method to get image data as np.array specifying image id and type\n    \"\"\"\n    fname = get_filename(image_id, image_type)\n    img = cv2.imread(fname)\n    assert img is not None, \"Failed to read image : %s, %s\" % (image_id, image_type)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    return img"},{"cell_type":"markdown","metadata":{"_cell_guid":"d905eee8-7e3a-11f4-0ef6-8aa3f5e11395"},"source":"First, we crop the image in order to remove the circular frames that might be present. This is done by finding the largest inscribed rectangle to the thresholded image. The image is then cropped to this rectangle. (see these videos for an explanation of the algorithm: https://www.youtube.com/watch?v=g8bSdXCG-lA, https://www.youtube.com/watch?v=VNbkzsnllsU)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"b3f0968b-7f53-1646-b624-ad2c137a0e3f"},"outputs":[],"source":"def maxHist(hist):\n    maxArea = (0, 0, 0)\n    height = []\n    position = []\n    for i in range(len(hist)):\n        if (len(height) == 0):\n            if (hist[i] > 0):\n                height.append(hist[i])\n                position.append(i)\n        else: \n            if (hist[i] > height[-1]):\n                height.append(hist[i])\n                position.append(i)\n            elif (hist[i] < height[-1]):\n                while (height[-1] > hist[i]):\n                    maxHeight = height.pop()\n                    area = maxHeight * (i-position[-1])\n                    if (area > maxArea[0]):\n                        maxArea = (area, position[-1], i)\n                    last_position = position.pop()\n                    if (len(height) == 0):\n                        break\n                position.append(last_position)\n                if (len(height) == 0):\n                    height.append(hist[i])\n                elif(height[-1] < hist[i]):\n                    height.append(hist[i])\n                else:\n                    position.pop()    \n    while (len(height) > 0):\n        maxHeight = height.pop()\n        last_position = position.pop()\n        area =  maxHeight * (len(hist) - last_position)\n        if (area > maxArea[0]):\n            maxArea = (area, len(hist), last_position)\n    return maxArea\n            \n\ndef maxRect(img):\n    maxArea = (0, 0, 0)\n    addMat = np.zeros(img.shape)\n    for r in range(img.shape[0]):\n        if r == 0:\n            addMat[r] = img[r]\n            area = maxHist(addMat[r])\n            if area[0] > maxArea[0]:\n                maxArea = area + (r,)\n        else:\n            addMat[r] = img[r] + addMat[r-1]\n            addMat[r][img[r] == 0] *= 0\n            area = maxHist(addMat[r])\n            if area[0] > maxArea[0]:\n                maxArea = area + (r,)\n    return (int(maxArea[3]+1-maxArea[0]/abs(maxArea[1]-maxArea[2])), maxArea[2], maxArea[3], maxArea[1], maxArea[0])\n\ndef cropCircle(img):\n    if(img.shape[0] > img.shape[1]):\n        tile_size = (int(img.shape[1]*256/img.shape[0]),256)\n    else:\n        tile_size = (256, int(img.shape[0]*256/img.shape[1]))\n\n    img = cv2.resize(img, dsize=tile_size)\n            \n    gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY);\n    _, thresh = cv2.threshold(gray, 10, 255, cv2.THRESH_BINARY)\n\n    _, contours, _ = cv2.findContours(thresh.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n\n    main_contour = sorted(contours, key = cv2.contourArea, reverse = True)[0]\n            \n    ff = np.zeros((gray.shape[0],gray.shape[1]), 'uint8') \n    cv2.drawContours(ff, main_contour, -1, 1, 15)\n    ff_mask = np.zeros((gray.shape[0]+2,gray.shape[1]+2), 'uint8')\n    cv2.floodFill(ff, ff_mask, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 1)\n    #cv2.circle(ff, (int(gray.shape[1]/2), int(gray.shape[0]/2)), 3, 3, -1)\n    \n    rect = maxRect(ff)\n    img_crop = img[min(rect[0],rect[2]):max(rect[0],rect[2]), min(rect[1],rect[3]):max(rect[1],rect[3])]\n    cv2.rectangle(ff,(min(rect[1],rect[3]),min(rect[0],rect[2])),(max(rect[1],rect[3]),max(rect[0],rect[2])),3,2)\n\n    plt.subplot(131)\n    plt.imshow(img)\n    plt.subplot(132)\n    plt.imshow(thresh, cmap='gray', vmin=0, vmax=1)\n    plt.subplot(133)\n    plt.imshow(ff)\n    plt.show()\n    \n    return img_crop"},{"cell_type":"markdown","metadata":{"_cell_guid":"2b329aab-9144-3163-3033-fde55b737cc5"},"source":"“For an initial delineation of the cervix, we use two features: \n\n - the *a* color channel of the source image in Lab color space (the higher the value of *a* , the “redder” the pixel color)\n - *R*, the distance of a pixel from the image center. The *R* feature provides spatial information and supports the extraction of continuous regions within the image plane.\""},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"bd01c6dc-c40c-a9c4-5c0c-f93d44568553"},"outputs":[],"source":"def Ra_space(img, Ra_ratio, a_threshold):\n    imgLab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB);\n    w = img.shape[0]\n    h = img.shape[1]\n    Ra = np.zeros((w*h, 2))\n    for i in range(w):\n        for j in range(h):\n            R = math.sqrt((w/2-i)*(w/2-i) + (h/2-j)*(h/2-j))\n            Ra[i*h+j, 0] = R\n            Ra[i*h+j, 1] = min(imgLab[i][j][1], a_threshold)\n            \n    Ra[:,0] /= max(Ra[:,0])\n    Ra[:,0] *= Ra_ratio\n    Ra[:,1] /= max(Ra[:,1])\n\n    return Ra"},{"cell_type":"markdown","metadata":{"_cell_guid":"08069a8d-3546-64f4-74a8-514f5ecaff0d"},"source":"\"The image is separated next into two clusters in the 2-D (*a-R*) feature space; we use Gaussian mixture modeling, initialized by a K-means procedure.\""},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"62207bef-bfc7-b40f-a05e-7d82b300ba26"},"outputs":[],"source":"for k, type_ids in enumerate([type_1_ids]):\n    m = len(type_ids)\n    train_ids = sorted(type_ids)\n    counter = 0\n    \n    for i in range(m):                \n        image_id = train_ids[counter] \n        counter += 1\n\n        img = get_image_data(image_id, 'Type_%i' % (k+1))\n\n        img = cropCircle(img)"},{"cell_type":"code","execution_count":null,"metadata":{"_cell_guid":"f427b590-cfbc-a307-09ef-4ca41df3a8b1"},"outputs":[],"source":"for k, type_ids in enumerate([type_1_ids]):\n    m = len(type_ids)\n    train_ids = sorted(type_ids)\n    counter = 0\n    \n    for i in range(m):                \n        image_id = train_ids[counter] \n        counter += 1\n\n        img = get_image_data(image_id, 'Type_%i' % (k+1))\n\n        img = cropCircle(img)\n        w = img.shape[0]\n        h = img.shape[1]\n                        \n        imgLab = cv2.cvtColor(img, cv2.COLOR_RGB2LAB);\n        \n        # Saturating the a-channel at 150 helps avoiding wrong segmentation\n        # in the case of close-up cervix pictures where the bloody os is falsly segemented as the cervix.\n        Ra = Ra_space(img, 1.0, 150) \n        a_channel = np.reshape(Ra[:,1], (w,h))\n        plt.subplot(221)\n        plt.imshow(a_channel, cmap='cool') \n\n        g = mixture.GaussianMixture(n_components = 2, covariance_type = 'diag', random_state = 0, init_params = 'kmeans')\n        image_array_sample = shuffle(Ra, random_state=0)[:1000]\n        g.fit(image_array_sample)\n        labels = g.predict(Ra)\n        labels += 1 # Add 1 to avoid labeling as 0 since regionprops ignores the 0-label.\n    \n        # The cluster that has the highest a-mean is selected.\n        labels_2D = np.reshape(labels, (w,h))\n        gg_labels_regions = measure.regionprops(labels_2D, intensity_image = a_channel)\n        gg_intensity = [prop.mean_intensity for prop in gg_labels_regions]\n        cervix_cluster = gg_intensity.index(max(gg_intensity)) + 1\n\n        mask = np.zeros((w * h,1),'uint8')\n        mask[labels==cervix_cluster] = 255\n        mask_2D = np.reshape(mask, (w,h))\n        \n        plt.subplot(222)\n        plt.imshow(mask_2D, cmap='gray', vmin=0, vmax = 1) \n        \n        cc_labels = measure.label(mask_2D, background=0)\n        regions = measure.regionprops(cc_labels)\n        areas = [prop.area for prop in regions]\n\n        regions_label = [prop.label for prop in regions]\n        largestCC_label = regions_label[areas.index(max(areas))]\n        mask_largestCC = np.zeros((w,h),'uint8')\n        mask_largestCC[cc_labels==largestCC_label] = 255\n\n        img_masked = img.copy()\n        img_masked[mask_largestCC==0] = (0,0,0)\n        img_masked_gray = cv2.cvtColor(img_masked, cv2.COLOR_RGB2GRAY);\n            \n        _,thresh_mask = cv2.threshold(img_masked_gray,0,255,0)\n            \n        kernel = np.ones((11,11), np.uint8)\n        thresh_mask = cv2.dilate(thresh_mask, kernel, iterations = 1)\n        plt.subplot(223)\n        plt.imshow(thresh_mask, cmap='gray', vmin=0, vmax = 1) \n        \n        thresh_mask = cv2.erode(thresh_mask, kernel, iterations = 2)\n        \n        plt.subplot(224)\n        plt.imshow(thresh_mask, cmap='gray', vmin=0, vmax = 1) \n        plt.show()\n        \n        _, contours_mask, _ = cv2.findContours(thresh_mask.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n\n        main_contour = sorted(contours_mask, key = cv2.contourArea, reverse = True)[0]\n                    \n        x,y,w,h = cv2.boundingRect(main_contour)\n        cv2.rectangle(img,(x,y),(x+w,y+h),255,2)\n                        \n        plt.subplot(111)\n        plt.imshow(img)\n        plt.show()"},{"cell_type":"markdown","metadata":{"_cell_guid":"db79632d-8e7d-1289-2761-1f2b742750bb"},"source":"To do: \n\n - Incorrect segmentation in cervix close-up pictures. Identify those...\n - Feed cropped pictures to a CNN"}],"metadata":{"_change_revision":0,"_is_fork":false,"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.0"}},"nbformat":4,"nbformat_minor":0}