{"cells":[{"metadata":{"_uuid":"9ef02227722a1655a1ddcccc19f136d89dbdbdf9"},"cell_type":"markdown","source":"Just a quick script to convert the DICOM training set into 9 training TFRecord files and one validation TFRecord file.\nFeel free to use this as an input to your own kernels.\nBounding boxes from the training data file are encoded as class ID=1, text='pneumonia'."},{"metadata":{"trusted":true,"_uuid":"4fcdc47c2d9cffbb32c86af5fbc3c8254123726e"},"cell_type":"code","source":"!git clone https://github.com/tensorflow/models.git\n\nimport sys\nsys.path.append('/kaggle/working/models/research/object_detection/utils')\nsys.path.append('/kaggle/working/models/research/object_detection/dataset_tools')","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\nimport dataset_util\n\nimport pandas as pd\nimport pydicom\n\nfrom io import BytesIO\n\nimport numpy as np\n\nflags = tf.app.flags\nFLAGS = flags.FLAGS\n\ndebug = False\n\ndef create_tf_example(patientId, boxes):\n    height = 1024 # Image height\n    width = 1024 # Image width\n\n    path = \"../input/stage_1_train_images/\" + patientId + \".dcm\"\n\n    ds = pydicom.dcmread(path)\n\n    filename = bytes(patientId + '.jpg', 'utf-8') # Filename of the image. Empty if image is not from file\n    image_format = b'jpeg' # b'jpeg' or b'png'\n\n    encoded_image_data = ds.PixelData[16:]\n    if (debug):\n        print(encoded_image_data[:3])\n\n    xmins = [] # List of normalized left x coordinates in bounding box (1 per box)\n    xmaxs = [] # List of normalized right x coordinates in bounding box\n                # (1 per box)\n    ymins = [] # List of normalized top y coordinates in bounding box (1 per box)\n    ymaxs = [] # List of normalized bottom y coordinates in bounding box\n                # (1 per box)\n\n    classes_text = [] # List of string class name of bounding box (1 per box)\n    classes = [] # List of integer class id of bounding box (1 per box)\n\n    for box in boxes:\n        if not np.isnan(box[0]):\n            if (debug):\n                print(box)\n            classes_text.append(b'pneumonia')\n            classes.append(1)\n            \n            # x-min y-min width height\n            xmins.append(box[0] / width)   # store normalized values for bbox\n            xmaxs.append((box[0] + box[2]) / width)\n            ymins.append(box[1] / height)\n            ymaxs.append((box[1] + box[3]) / height)\n\n    if (debug):\n        print(xmins)\n        print(xmaxs)\n        print(ymins)\n        print(ymaxs)\n\n    tf_example = tf.train.Example(features=tf.train.Features(feature={\n        'image/height': dataset_util.int64_feature(height),\n        'image/width': dataset_util.int64_feature(width),\n        'image/filename': dataset_util.bytes_feature(filename),\n        'image/source_id': dataset_util.bytes_feature(filename),\n        'image/encoded': dataset_util.bytes_feature(encoded_image_data),\n        'image/format': dataset_util.bytes_feature(image_format),\n        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),\n        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),\n        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),\n        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),\n        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),\n        'image/object/class/label': dataset_util.int64_list_feature(classes),\n    }))\n    return tf_example\n\nimport contextlib2\nimport tf_record_creation_util\n\nnum_shards=10\noutput_filebase='train'\n\nwith contextlib2.ExitStack() as tf_record_close_stack:\n    output_tfrecords = tf_record_creation_util.open_sharded_output_tfrecords(tf_record_close_stack, output_filebase, num_shards)\n\n\n    train = pd.read_csv(\"../input/stage_1_train_labels.csv\")\n    groups = train.groupby('patientId')\n\n    count = 0\n\n    for patientId in train.drop_duplicates('patientId')['patientId']:\n        print('[{c}]processing patientId={p}'.format(c=count,p=patientId))\n\n        boxes = groups.get_group(patientId).drop(columns=['patientId']).as_matrix()\n        tf_example = create_tf_example(patientId, boxes)\n\n        output_shard_index = count % num_shards\n        output_tfrecords[output_shard_index].write(tf_example.SerializeToString())\n\n        count += 1\n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","collapsed":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"# clean up names a bit and take the first as validation\n!mkdir train\n!mkdir val\n\n# TODO: use train_test_split to do validation rows\n!mv train-00000-of-00010 val/val-00001-of-00001\n\n!mv train-00001-of-00010 train/train-00001-of-00009\n!mv train-00002-of-00010 train/train-00002-of-00009\n!mv train-00003-of-00010 train/train-00003-of-00009\n!mv train-00004-of-00010 train/train-00004-of-00009\n!mv train-00005-of-00010 train/train-00005-of-00009\n!mv train-00006-of-00010 train/train-00006-of-00009\n!mv train-00007-of-00010 train/train-00007-of-00009\n!mv train-00008-of-00010 train/train-00008-of-00009\n!mv train-00009-of-00010 train/train-00009-of-00009","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"bbe2b8d6609e5decbc703a5f2dcf74dcd8983e0b"},"cell_type":"code","source":"# remove the models git repo\n!rm -rf models","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}