{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage import io\nfrom sympy.solvers import solve\nfrom sympy import Symbol\nimport math\nimport cv2\n\nmarks = pd.read_csv('../input/train_ship_segmentations.csv') # Markers for ships\nimages = os.listdir('../input/train') # Images for training\nos.chdir(\"../input/train\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d9d89705dd864b815220a8aa28b1827227f5693d"},"cell_type":"code","source":"def mask_part(pic):\n    '''\n    Function that encodes mask for single ship from .csv entry into numpy matrix\n    '''\n    back = np.zeros(768**2)\n    starts = pic.split()[0::2]\n    lens = pic.split()[1::2]\n    for i in range(len(lens)):\n        back[(int(starts[i])-1):(int(starts[i])-1+int(lens[i]))] = 1\n    return np.reshape(back, (768, 768, 1))\n\ndef is_empty(key):\n    '''\n    Function that checks if there is a ship in image\n    '''\n    df = marks[marks['ImageId'] == key].iloc[:,1]\n    if len(df) == 1 and type(df.iloc[0]) != str and np.isnan(df.iloc[0]):\n        return True\n    else:\n        return False\n    \ndef masks_all(key):\n    '''\n    Merges together all the ship markers corresponding to a single image\n    '''\n    df = marks[marks['ImageId'] == key].iloc[:,1]\n    masks= np.zeros((768,768,1))\n    if is_empty(key):\n        return masks\n    else:\n        for i in range(len(df)):\n            masks += mask_part(df.iloc[i])\n        return np.transpose(masks, (1,0,2))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"edd2bc4410784e4f847c9a2dddd0fa644184d507"},"cell_type":"code","source":"def image_contrast(image):\n    shape=np.shape(image)\n    im=image.flatten()\n    vide=0\n    for i in range(shape[0]*shape[1]):\n        if im[i]>200:\n            im[i]=255\n            vide=1\n        else:\n            im[i]=0\n    if vide==0:\n        print(-1)\n        return [-1]\n    \n    return np.reshape(im,shape)\n\ndef corner_box(image):\n    if np.shape(image_contrast(image))[0]>2:\n        image=image_contrast(image).flatten()\n        list_coord=[]\n        for i in range(768*768):\n            if image[i]==255:\n                x=np.array([(i%768),int((i/768))])\n                list_coord.append(x)\n        image=np.array(list_coord)\n        ca = np.cov(image,y = None,rowvar = 0,bias = 1)\n\n        v, vect = np.linalg.eig(ca)\n        tvect = np.transpose(vect)\n\n        ar = np.dot(image,np.linalg.inv(tvect))\n\n        mina = np.min(ar,axis=0)\n        maxa = np.max(ar,axis=0)\n        diff = (maxa - mina)*0.5\n\n        center = mina + diff\n        corners = np.array([center+[-diff[0],-diff[1]],center+[diff[0],-diff[1]],center+[diff[0],diff[1]],center+[-diff[0],diff[1]],center+[-diff[0],-diff[1]]])\n\n        corners = np.dot(corners,tvect)\n        corner_swne=[0]*4\n        l_n=1000\n        l_s=0\n        l_w=10000\n        l_e=0\n        for i in corners:\n            if i[1]<l_n:\n                l_n=i[1]\n                corner_swne[2]=i\n            if i[1]>=l_s:\n                l_s=i[1]\n                corner_swne[0]=i\n            if i[0]>=l_e:\n                l_e=i[0]\n                corner_swne[3]=i\n            if i[0]<l_w:\n                l_w=i[0]\n                corner_swne[1]=i\n\n        return corner_swne\n    else:\n        return -1\n\ndef coeff_direct_box(image):\n    if np.shape(image_contrast(image))[0]>2:\n        coord=corner_box(image)\n        s=coord[0]\n        w=coord[1]\n        n=coord[2]\n        e=coord[3]\n\n        v_ne=[e[0]-n[0],e[1]-n[1]]\n        v_es=[s[0]-e[0],s[1]-e[1]]\n        v_sw=[w[0]-s[0],w[1]-s[1]]\n        v_wn=[n[0]-w[0],n[1]-w[1]]\n\n        vect = [v_ne,v_es,v_sw,v_wn]\n\n        if vect[0][0]!=0:\n            c_ne=vect[0][1]/vect[0][0]\n        else:\n            c_ne=0\n        if vect[1][0]!=0:\n            c_es=vect[1][1]/vect[1][0]\n        else:\n            c_es=0\n        if vect[2][0]!=0:\n            c_sw=vect[2][1]/vect[2][0]\n        else:\n            c_sw=0\n        if vect[3][0]!=0:\n            c_wn=vect[3][1]/vect[3][0]\n        else:\n            c_wn=0\n\n        return c_ne,c_es,c_sw,c_wn\n    else:\n        return -1\n\ndef bounding_box_channel(image):\n    if np.shape(image_contrast(image))[0]>2:\n        coord=corner_box(image)\n        coeff = coeff_direct_box(image)\n        image=[0]*768*768\n\n        for i in range(768*768):  \n                    if  int(i/768)>coord[2][1] and int(i/768)<coord[0][1] and i%768>coord[1][0]and i%768<coord[3][0]:\n                         image[i]=255\n                    if (i%768-coord[2][0])!=0 and (int(i/768)-int(coord[2][1]))/(i%768-coord[2][0])<coeff[0] and i%768>coord[2][0]:\n                            image[i]=0\n                    if (i%768-coord[3][0])!=0 and (int(i/768)-int(coord[3][1]))/(i%768-coord[3][0])<coeff[1] and int(i/768)>coord[3][1]:\n                            image[i]=0\n                    if (i%768-coord[0][0])!=0 and (int(i/768)-int(coord[0][1]))/(i%768-coord[0][0])<coeff[2] and i%768<coord[0][0]:\n                            image[i]=0\n                    if (i%768-coord[1][0])!=0 and (int(i/768)-int(coord[1][1]))/(i%768-coord[1][0])<coeff[3] and int(i/768)<coord[1][1]:\n                            image[i]=0\n\n        return np.reshape(image,[768,768])\n    else:\n        return np.reshape([0]*768*768,[768,768])\n\n    \ndef bounding_box(image,mask):\n    image_1=plt.imread(image)[:,:,2]-plt.imread(image)[:,:,1]\n    image_2=plt.imread(image)[:,:,1]-plt.imread(image)[:,:,0]\n    image_3=plt.imread(image)[:,:,2]-plt.imread(image)[:,:,0]\n    bb_1=bounding_box_channel(image_1).flatten()\n    bb_2=bounding_box_channel(image_2).flatten()\n    bb_3=bounding_box_channel(image_3).flatten()\n    bb_4=bb_1+bb_2+bb_3\n    bon=0\n    mask_f=mask.flatten()\n    for i in range(768*768):\n        if bb_4[i]>600:\n            bb_4[i]=255\n        else:\n            bb_4[i]=0\n        if bb_4[i]==mask_f[i]:\n            bon+=1\n    \n    bb_1=np.reshape(bb_1,[768,768])\n    bb_2=np.reshape(bb_2,[768,768])\n    bb_3=np.reshape(bb_3,[768,768])\n    \n    bb_4=np.reshape(bb_4,[768,768])\n    plt.subplot(1,3,1)\n    plt.imshow(bb_4)\n    plt.subplot(1,3,2)\n    plt.imshow(mask)\n    plt.subplot(1,3,3)\n    plt.imshow(plt.imread(image))\n    plt.show()\n    print(\"Result {} %\".format((bon/(768*768))*100))","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"7c84e4061e037a0829fa51f034ac0e0ddf546705"},"cell_type":"markdown","source":"And the predictor for one image:"},{"metadata":{"trusted":true,"_uuid":"270e5a70b148a8cd911f245435c01c2fb73836d4","scrolled":true},"cell_type":"code","source":"sel=26 #the image's number\nbounding_box(images[sel],masks_all(images[sel])[:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"67469d9eb307905d97f48a24525a7226cbab0bc4","collapsed":true},"cell_type":"markdown","source":"The problem is that only one bounding box is detected per image and in this bounding box there is everything. Moreover if we want to submit it is not fast enough"},{"metadata":{"trusted":true,"_uuid":"d5a8d48b263bfbeba2f423a266029916a0493fa8"},"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.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}