{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def rle2mask(mask_rle, shape=(1600,256)):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (width,height) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n\n    '''\n    s = mask_rle.split()\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape(shape).T\n\n\n#https://www.kaggle.com/bguberfain/memory-aware-rle-encoding\ndef rle_encode_less_memory(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    This simplified method requires first and last pixel to be zero\n    '''\n    pixels = img.T.flatten()\n    \n    # This simplified method requires first and last pixel to be zero\n    pixels[0] = 0\n    pixels[-1] = 0\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 2\n    runs[1::2] -= runs[::2]\n    \n    return ' '.join(str(x) for x in runs)\n\ndef image_size_dict(img_id, x, y):\n    image_id = [thing[:-5] for thing in img_id]\n    x_y = [(x[i], y[i]) for i in range(0, len(x))]    \n    return dict(zip(image_id, x_y))\n\n\ndef global_shift_mask(maskpred1, y_shift, x_shift):\n    \"\"\"\n    applies a global shift to a mask by padding one side and cropping from the other\n    \"\"\"\n    if y_shift <0 and x_shift >=0:\n        maskpred2 = np.pad(maskpred1, [(0,abs(y_shift)), (abs(x_shift), 0)], mode='constant', constant_values=0)\n        maskpred3 = maskpred2[abs(y_shift):, :maskpred1.shape[1]]\n    elif y_shift >=0 and x_shift <0:\n        maskpred2 = np.pad(maskpred1, [(abs(y_shift),0), (0, abs(x_shift))], mode='constant', constant_values=0)\n        maskpred3 = maskpred2[:maskpred1.shape[0], abs(x_shift):]\n    elif y_shift >=0 and x_shift >=0:\n        maskpred2 = np.pad(maskpred1, [(abs(y_shift),0), (abs(x_shift), 0)], mode='constant', constant_values=0)\n        maskpred3 = maskpred2[:maskpred1.shape[0], :maskpred1.shape[1]]\n    elif y_shift < 0 and x_shift < 0:\n        maskpred2 = np.pad(maskpred1, [(0, abs(y_shift)), (0, abs(x_shift))], mode='constant', constant_values=0)\n        maskpred3 = maskpred2[abs(y_shift):, abs(x_shift):]\n    return maskpred3","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Set as inputs your prediction file, target_id to shift, and the x and y shift values"},{"metadata":{"trusted":true},"cell_type":"code","source":"dfpred = pd.read_csv('../input/best-public-hubmap/submission_public_TPU.csv')\nTARGET_ID = 'afa5e8098'\ny_shift = -40\nx_shift = -24","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#get image sizes \n\ndfinfo = pd.read_csv('../input/hubmap-kidney-segmentation/HuBMAP-20-dataset_information.csv')\n\nsize_dict = image_size_dict(dfinfo.image_file, dfinfo.width_pixels, dfinfo.height_pixels)  #dict which contains image sizes mapped to id's\nmask_shape = size_dict.get(TARGET_ID)\n\ntaridx = dfpred[dfpred['id']==TARGET_ID].index.values[0]  #row of TARGET_ID in dfpred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"maskpred = rle2mask(dfpred.iloc[taridx]['predicted'], mask_shape)\n\nmaskpred1 = maskpred.copy()\nmaskpred1[maskpred1>0]=1","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Apply global shift to mask"},{"metadata":{"trusted":true},"cell_type":"code","source":"mask_shifted = global_shift_mask(maskpred1, y_shift, x_shift)  #apply specified shift to mask","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"newrle = rle_encode_less_memory(mask_shifted)  #rle encode shifted mask\n\ndfpred.at[taridx, 'predicted'] = newrle\n\ndfsample = pd.read_csv('../input/hubmap-kidney-segmentation/sample_submission.csv')\n\nmydict = dict(zip(dfpred['id'], dfpred['predicted']))\n\ndfsample['predicted'] = dfsample['id'].map(mydict).fillna(dfsample['predicted'])\n\ndfsample = dfsample.replace(np.nan, '', regex=True)\n\ndfsample.to_csv('submission.csv',index=False)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dfsample.head()","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}