{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Image Orientation\n\nThank you to [@xhlulu](https://www.kaggle.com/xhlulu/rsna-generate-metadata-csvs) for extracting all the image metadata\n\nThis notebook ranks and identifies anomolous image orientations, and visualizes some of these orientations.  It does not provide insight into what the orientation vector means ... I am hoping to figure that out, but am wondering if anyone in the community knows how to decode the 6D orientation vector\n\nI think there are 2 possible approaches to deal with this variable:\n - randomize the orientation with some augmnetaiton at training time\n - standardize the orientation during a preprocessing stage\n\nMy goal is to explore option 2"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\n\nimport numpy as np \nimport pandas as pd \nimport skimage\nimport cv2 as cv\nimport pydicom\nimport json\n\nfrom scipy.spatial.distance import euclidean\n\n\nfrom matplotlib import pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/rsna-generate-metadata-csvs/train_metadata.csv')\ntrain['image_dir'] = '../input/rsna-intracranial-hemorrhage-detection/stage_1_train_images/'\n\ntest = pd.read_csv('../input/rsna-generate-metadata-csvs/test_metadata.csv')\ntest['image_dir'] = '../input/rsna-intracranial-hemorrhage-detection/stage_1_test_images/'\n\nmetadata = pd.concat([train, test])\ntrain, test = None, None\nmetadata['image_orientation'] = metadata['ImageOrientationPatient'].apply(lambda x: np.array(eval(x)).astype(np.float32))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Types of Image orientation\n\nWe will find all the unique image orientations and sort them from maximum distance to the mean.  Then take top-k = 50 to find our anomoulous orientations"},{"metadata":{"trusted":true},"cell_type":"code","source":"orientations = metadata['ImageOrientationPatient'].unique()\norientations = np.array([eval(o) for o in orientations]).astype(np.float32)\n\nmean_orientation = orientations.mean(axis=0)\nprint('Mean Orientation: {}'.format(mean_orientation))\norientations = orientations[np.argsort([euclidean(o, mean_orientation) for o in orientations])[::-1]]\norientations = pd.DataFrame(orientations)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Common of Orientations:\")\norientations.tail(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Orientations of Intrest:\")\norientations.head(30)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# finds other orientations with similar euclidean distance\ndef match_orientation(target, tol=1e-6):\n    metadata['dist'] = metadata['image_orientation'].apply(lambda x: euclidean(x, target))\n    return metadata[metadata['dist'] < tol]\n\ndef show(dcm, ax, rot=0):\n    dcm = pydicom.dcmread(dcm.image_dir + dcm.SOPInstanceUID + '.dcm')\n    img = dcm.pixel_array  * dcm.RescaleSlope + dcm.RescaleIntercept\n    img = np.clip(img, 0, 100)\n    img = skimage.transform.rotate(img, rot)\n    return ax.imshow(img, cmap='bone')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visualize Orientations\nWe will sample every 10th orientation sorted form most to least anomolous"},{"metadata":{"trusted":true},"cell_type":"code","source":"o =orientations.values[0]\nprtinnp.degrees(np.arctan2(o[0], ))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"N_SAMPLES = 4\n\nfor o in orientations.values[::10]:\n    x = match_orientation(o)\n    f, ax = plt.subplots(1, N_SAMPLES, figsize=(20, 5))\n    for i in range(N_SAMPLES):\n        show(x.iloc[i*3], ax[i], rot=0)\n\n    f.suptitle('ORIENTATION: {}'.format(o))\n    plt.show()","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":1}