{"cells":[{"metadata":{"trusted":true},"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":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport dataset_util\nimport pandas as pd\nimport pydicom\nfrom io import BytesIO\nimport numpy as np\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/vinbigdata-chest-xray-abnormalities-detection/train.csv\")\ntrain = train.dropna()\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.isna().sum()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.image_id.value_counts()","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 pydicom\nfrom pydicom.pixel_data_handlers.util import apply_voi_lut\nimport cv2\nimport contextlib2\nimport tf_record_creation_util\n\n\ndebug=False\ndef create_tf_example(imageId, boxes, class_name, class_id,  voi_lut = True, fix_monochrome = True):\n    height = 1024 # Image height\n    width = 1024 # Image width\n\n    path = \"../input/vinbigdata-chest-xray-abnormalities-detection/train/\" + imageId + \".dicom\"\n    ds = pydicom.dcmread(path)\n#from https://www.kaggle.com/raddar/convert-dicom-to-np-array-the-correct-way/\n    if voi_lut:\n        data = apply_voi_lut(ds.pixel_array, ds)\n    else:\n        data = ds.pixel_array\n    if fix_monochrome and ds.PhotometricInterpretation == \"MONOCHROME1\":\n        data = np.amax(data) - data\n    data = data - np.min(data)\n    data = data / np.max(data)\n    data = (data * 255).astype(np.uint8)\n    ori_width, ori_height = data.shape\n    data = cv2.resize(data, (width, height), interpolation = cv2.INTER_AREA)\n    filename = bytes(imageId + '.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    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 idx, box in enumerate(boxes):\n        if not np.isnan(box[0]):\n            if (debug):\n                print(box)\n            classes_text.append(str(class_name[idx]).encode())\n            classes.append(int(class_id[idx]))\n            \n            # x-min y-min width height\n            xmins.append(box[0] *width/ori_width)   # store normalized values for bbox\n            xmaxs.append(box[2] * width/ori_width)\n            ymins.append(box[1] * height/ori_height)\n            ymaxs.append(box[3] * height/ori_height)\n\n    if (debug):\n        print(xmins)\n        print(xmaxs)\n        print(ymins)\n        print(ymaxs)\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.float_list_feature(data.tostring()),\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\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    groups = train.groupby('image_id')\n\n    count = 0\n\n    for image_id in train.drop_duplicates('image_id')['image_id']:\n        print('[{c}]processing patientId = {p}'.format(c=count,p=image_id))\n\n        boxes = groups.get_group(image_id)[['x_min','y_min','x_max','y_max']].values\n        class_name = groups.get_group(image_id)[['class_name']].values\n        class_id = groups.get_group(image_id)[['class_id']].values\n        tf_example = create_tf_example(image_id, boxes, class_name, class_id)\n\n        output_shard_index = count % num_shards\n        output_tfrecords[output_shard_index].write(tf_example.SerializeToString())\n        if debug:\n            if count>10:\n                break\n        count += 1","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}