{"cells":[{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install python-polylabel","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport tifffile\nimport matplotlib.pyplot as plt\nfrom tqdm.auto import tqdm\nfrom PIL import Image\nimport cv2\nimport json\nimport struct\nfrom polylabel import polylabel\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fx = 0.1  # Percent used to resize to thumbnail","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"input_path = Path('../input/hubmap-kidney-segmentation/')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"images_path = list(input_path.rglob('*.tiff'))\nlen(images_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_color(color):\n    return list(map(ord, struct.unpack('cccc', struct.pack('i', color))))[:3][::-1]\n\n\ndef draw_contors(im, fx, annotations, color, thickness):\n    for annotation in annotations:\n        # Get coordinates\n        coords = annotation['geometry']['coordinates']\n\n        # Add a level when geometry is Polygon\n        if annotation['geometry']['type'] == 'Polygon':\n            coords = [coords]\n\n        # Apply fx, convert to int and transpose to cv2 format\n        coords = [np.int32(np.array(c) * fx).transpose(1, 0, 2) for c in coords]\n\n        # Draw contours\n        cv2.drawContours(im, coords, -1, color, thickness, lineType=cv2.LINE_AA)\n        \n        # Text to plot\n        text = annotation['properties']['classification']['name']\n        \n        # Ignore glomerulus\n        if text != 'glomerulus':\n            # Font face\n            font = cv2.FONT_HERSHEY_SIMPLEX\n\n            # Contour area and sqrt(sqrt) of it. Used to find font size\n            total_area = sum(map(cv2.contourArea, coords))\n            sqrt_area = np.sqrt(np.sqrt(total_area))\n\n            # Font scale, proportional to area of countour\n            fontScale = 0.5 * sqrt_area / 6 * fx / 0.1\n\n            # Find center within polygon (https://blog.mapbox.com/a-new-algorithm-for-finding-a-visual-center-of-a-polygon-7c77e6492fbc)\n            cX, cY = polylabel(coords[0].transpose(1, 0, 2))\n\n            # Text size, used to center in cX, cY\n            textsize = cv2.getTextSize(text, font, fontScale, 2)[0]\n\n            # Draw text\n            cv2.putText(im, text, (int(cX-textsize[0]/2), int(cY+textsize[1]/2)), font, fontScale, color, 2)\n        \n\ndef read_annotations(fname):\n    if fname.exists():\n        with open(fname) as f:\n            return json.load(f)\n    else:\n        # File not found. E.g., test annotation\n        return None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for fname in tqdm(images_path):\n    # Read image\n    im = tifffile.imread(fname)\n    print(fname, im.shape)\n    \n    if im.ndim == 5:\n        # Fiz crazy shape (1, 1, c, h, w)!\n        im = np.rollaxis(im[0, 0], 0, 3)\n\n    # Convert to BGR format to be used in cv2\n    im = cv2.cvtColor(im, cv2.COLOR_RGB2BGR)\n    \n    # Resize to fx\n    im = cv2.resize(im, None, fx=fx, fy=fx, interpolation=cv2.INTER_AREA)\n    \n    # Read annotations\n    anatomical_data = read_annotations(fname.parent / f'{fname.stem}-anatomical-structure.json')\n    annotation_data = read_annotations(fname.parent / f'{fname.stem}.json')\n    \n    # Draw annotations (color in BGR format)\n    if annotation_data is not None:\n        draw_contors(im, fx, annotation_data, [0, 255, 0], 1)\n\n    draw_contors(im, fx, anatomical_data, [0, 0, 255], 2)\n    \n    # Write output file\n    fname_jpeg = f'{fname.parent.name}_{fname.stem}.jpg'\n    cv2.imwrite(str(fname_jpeg), im, [int(cv2.IMWRITE_JPEG_QUALITY), 95])","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}