{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Crop points for Panda competition"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport cv2\nfrom skimage.io import MultiImage \nfrom PIL import Image\nimport openslide\n\nimport os\nfrom tqdm.notebook import tqdm","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Creating dataframe. Do not run this code to get dataframe. It is available in input data"},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nfirst def crop takes path to image and returns points to crop white background. \nPoints are relative to shape. i.e their values are between [0,1]\n\"\"\"\ndef crop(path):\n    result = []\n    imgs = openslide.OpenSlide(path)\n    img = np.asarray(imgs.read_region((0,0), imgs.level_count-1, imgs.level_dimensions[-1]))\n    mask = img[:,:].sum(axis=2)\n    mask = (mask<(mask.max()-10)).astype('uint8')\n    rect = cv2.boundingRect(mask)\n    x = rect[1]/img.shape[0]\n    x1 = (rect[1] + rect[3])/img.shape[0]\n    y = rect[0]/img.shape[1]\n    y1 = (rect[0] + rect[2])/img.shape[1]\n\n    return x, x1, y, y1\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\nThis part of code cretes dataframe of points.\nYou can find dataframe in input, so there is no need to execute this part of code\n\n\ntrain_dir = '/kaggle/input/prostate-cancer-grade-assessment/train_images/'\npathes = os.listdir(train_dir)\nx = []\nx1 = []\ny = []\ny1 = []\nfor i in tqdm(pathes):\n    points = crop(train_dir + i)\n    x.append(points[0])\n    x1.append(points[1])\n    y.append(points[2])\n    y1.append(points[3])\ndf = pd.DataFrame({\n    'id': pathes,\n    'x': x,\n    'x1': x1,\n    'y': y,\n    'y1': y1,\n})\ndf.to_csv('crop_points.csv')\n''';","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize Crops"},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/prostate-cancer-grade/crop_points.csv')\ndf","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\nFunction takes relative points and shape of the neede tiff frame and returns its points \n'''\ndef new_points(x,x1,y,y1, shape, pad = 15):\n    new_x = np.clip(int(x*shape[0]) - pad, 0, shape[0])\n    new_x1 = np.clip(int(x1*shape[0]) + pad, 0, shape[0])\n    new_y = np.clip(int(y*shape[1]) - pad, 0, shape[1])\n    new_y1= np.clip(int(y1*shape[1]) + pad, 0, shape[1])\n    return new_x, new_x1,new_y,new_y1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_id = df.id[39] # getting id of image\nimgs = openslide.OpenSlide(f'/kaggle/input/prostate-cancer-grade-assessment/train_images/{image_id}') # open image with openslide\nframe = imgs.level_count - 2 # get needed level. Here you can choose which frame to use\nimg = np.asarray(imgs.read_region((0,0), frame, imgs.level_dimensions[frame])) # get image from multi image\nx,x1,y,y1 = df.loc[df.id == image_id].values[0,1:] # get resize points\nnew_x, new_x1, new_y, new_y1 = new_points(x,x1,y,y1,img.shape) #scale points\nnew_img = img[new_x:new_x1,new_y:new_y1] # get cropped image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize = (30,20) )\nplt.subplot(1,2,1)\nplt.imshow(new_img)\nplt.title('cropped', fontsize=20)\nplt.subplot(1,2,2)\nplt.imshow(img)\nplt.title('original', fontsize=20);","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}