{"cells":[{"metadata":{},"cell_type":"markdown","source":"<center><h1>An important parameter of melanoma is the asymmetry and smoothness of the border transition</h1></center>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install imutils","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport cv2\nimport math\nfrom skimage import data, img_as_float\nfrom skimage import exposure\nfrom skimage.io import imsave\nfrom imutils import perspective\nfrom imutils import contours\nimport imutils\nfrom scipy.spatial import distance as dist\nfrom keras.layers import AveragePooling2D, MaxPooling2D, Input\nfrom keras.models import Model\nimport keras.backend as K\nfrom keras.preprocessing import image as ik\ndef midpoint(ptA, ptB):\n    return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)\nimport matplotlib.gridspec as gridspec","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<center><h2>\n2 functions for finding the melonoma contour</h2></center>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"COUNTLEN = 10 #how many sizes from the center of the mole to the edge to return","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def HAIR_SORRY_REMOVE(image, clip_hist_percent=1):\n    gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    kernel = cv2.getStructuringElement(1,(17,17))\n    blackhat = cv2.morphologyEx(gray, cv2.MORPH_BLACKHAT, kernel)\n    _,threshold = cv2.threshold(blackhat,10,255,cv2.THRESH_BINARY)\n    final_image = cv2.inpaint(image,threshold,1,cv2.INPAINT_TELEA)\n    return (final_image)\ndef step_assimetry(img):\n    img = HAIR_SORRY_REMOVE(img)\n#     img = cv2.bilateralFilter(img,50,15,15)\n    \n    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n    ret, thresh =     cv2.threshold(gray,100,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)\n    \n    kernel = np.ones((2,2),np.uint8)\n    opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)\n    kernel = np.ones((2,2),np.uint8)\n    dilate = cv2.erode(opening,kernel,iterations=3)\n#     dilate = cv2.dilate(opening,kernel,iterations=3)\n    blur = dilate\n   \n#     blur = cv2.blur(opening,(15,15))\n    ret, thresh =     cv2.threshold(blur,100,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)\n    \n    contours, hierarchy =     cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)\n#     images = cv2.drawContours( img, contours, -1, (255,0,0), 3, cv2.LINE_AA, hierarchy, 1 )\n#     plt.imshow(images)\n    \n    delta = 40\n    if len(contours)<3:\n        delta = 70\n    S = list()\n    for c in contours:\n        box = cv2.minAreaRect(c)\n        box = cv2.cv.BoxPoints(box)  if imutils.is_cv2() else cv2.boxPoints( box)\n        box = np.array(box, dtype=\"int\")\n        box = perspective.order_points( box)\n        center = img.shape[0]/2\n       \n        ( tl, tr, br, bl) = box\n        (centerX, centerY) = midpoint( tl, br)\n        (midlx, midly) = midpoint( tl, bl)\n#         print(midlx,\"---\")\n        if (tl[0]>0 and tr[0]<250 and br[1]<255) or (midlx>0 and br[0]<252 and centerX>center-delta and centerX<center+delta):\n#             if (centerX>center-delta and centerX<center+delta) and (centerY>center-delta and centerY<center+delta):\n                S.append(c)\n    \n    return S","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SHAPE = 256","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_Assimetry2(im):\n    example = [(105, 24), (78, 84), (93, 90), (105, 112), (110, 148), (93, 179), (76, 228), (44, 225), (112, 255), (184, 252), (217, 255), (255, 224), (255, 123), (207, 110), (209, 56), (153, 78)] \n    result = im.copy()\n    orig2 = im.copy()\n    img = im.copy()\n#     img = segmentation_color3(img.copy())\n   \n    S = step_assimetry(img)\n    shape_orig = orig2.shape[0]\n    if len(S)>0:        \n        cnt = max(S, key=cv2.contourArea)\n    else:\n        return \"err\", result, True,\"var1\"\n    box = cv2.minAreaRect(cnt)\n    box = cv2.cv.BoxPoints(box)  if imutils.is_cv2() else cv2.boxPoints( box)\n    box = np.array(box, dtype=\"int\")\n    box = perspective.order_points( box)\n    orig = cv2.drawContours(result, [box.astype(\"int\")] , -1 , ( 0 , 255 , 0 ) , 2)\n    for ( x, y)  in box:\n        cv2.circle(result, (int(x), int(y)) , 5 , ( 0 , 0 , 255 ) , -1)\n    ( tl, tr, br, bl) = box\n    ( centerXX, centerYY) = midpoint( tl, br)\n    (midlx, midly) = midpoint( tl, bl)\n#     print(int(midly),int(midlx))\n    cv2.circle(result,(int(midlx), int(midly)),15,(255,45,12),2)\n    start = (int(centerXX), int( centerYY))\n    count_len = COUNTLEN\n    shape = cnt.shape[0]\n    run = int(shape/count_len)\n    if shape<count_len:\n        run = 1\n    LENGTH = list()\n    sss = []\n    previos = start\n    \n    for i,r in enumerate(range(0,shape,run)):\n        if i<count_len:\n            end = (int(cnt[r][0][0]),int(cnt[r][0][1]))\n            dA = dist.euclidean(start, end)\n            \n            cv2.line(result, start, end,(0, 0, 0), 2)\n            previos = end\n            \n            \n            \n            LENGTH.append(dA)\n        else:\n            break\n    max_LENGTN = max(LENGTH)\n    if len(LENGTH)<count_len:\n        razn = count_len - len(LENGTH)\n        for i in range(razn):\n            LENGTH.append(0)\n    if max_LENGTN<25:\n        cv2.circle(result,(int(midlx), int(midly)),40,(255,45,12),2)\n        return LENGTH, result, True,\"var2\"\n#         max_LENGTN=55#80\n#     max_LENGTN+=10#15\n    top_crop = centerYY-max_LENGTN\n    bottom_crop = centerYY+max_LENGTN\n    left_crop = centerXX-max_LENGTN\n    right_crop = centerXX+max_LENGTN\n    if top_crop<0:\n        top_crop=0\n    if bottom_crop>256:\n        bottom_crop=256\n    if left_crop<0:\n        left_crop=0\n    if right_crop>256:\n        right_crop=256\n#     result = result[int(top_crop):int(bottom_crop),int(left_crop):int(right_crop),:]\n#     result = cv2.bilateralFilter(result,9,100,100)\n#     result = segmentation_color3(result)\n#     print (sss)\n    return LENGTH, result, False, \"var0\" #return length border\nimg = cv2.imread(train_dir+test_image_name_arr[0]+\".jpg\")\n_,im,_,_ = get_Assimetry2(img)\n\nplt.imshow(im)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nplt.imshow(im)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir = \"../input/jpeg-melanoma-256x256/train/\"\ntrain = pd.read_csv(\"../input/jpeg-melanoma-256x256/train.csv\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<center><H2>RESULT</h2></center>","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"col = [\"length_\"+str(i) for i in range(COUNTLEN)]\ndata = pd.DataFrame(columns = col)\ntest_image_name_arr = train[train.target==1][\"image_name\"].values\n# fig, ax = plt.subplots(nrows=1, ncols=4, figsize=(15,15), gridspec_kw={'wspace':0.1, 'hspace':0})\nj=0\nran = 240\nplt.figure(figsize = (15,15))\ngs1 = gridspec.GridSpec(6, 6)\ngs1.update(wspace=0.00, hspace=0.0)\nsetka = 0\nfor i in range(36):\n    img = cv2.imread(train_dir+test_image_name_arr[ran+i]+\".jpg\")\n    length,image_result,_,_ = get_Assimetry2(img)\n    img = cv2.cvtColor(image_result,cv2.COLOR_BGR2RGB)\n    data.loc[i,col] = length\n    ax1 = plt.subplot(gs1[setka])\n    setka+=1\n    plt.axis('on')\n    ax1.set_xticklabels([])\n    ax1.set_yticklabels([])\n    ax1.set_aspect('equal')\n    ax1.imshow(img)\n   \n#     ax[j].imshow(img)\n#     ax[j].axis(\"off\")\n    j+=1\ndisplay(data)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}