{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"collapsed":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import scipy.misc\nimport pydicom \nimport glob\nimport sys\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.interpolation import zoom\nimport pylab","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"#!git clone https://github.com/i-pan/rsna18-retinanet-starter.git\n!git clone https://github.com/fizyr/keras-retinanet\nos.chdir(\"keras-retinanet\") \n!python setup.py build_ext --inplace    ","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"_kg_hide-input":false,"trusted":true,"collapsed":true},"cell_type":"code","source":"!pip install . --user","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DATA_DIR = \"/kaggle/input/\"\nROOT_DIR = \"/kaggle/working/\"\n# converted training set DICOMs to PNGs, it should be part of the data environment\ntrain_pngs_dir = os.path.join(DATA_DIR, \"rsna-pneu-train-png/orig/\")\ntest_dicoms_dir  = os.path.join(DATA_DIR, \"rsna-pneumonia-detection-challenge/stage_2_test_images/\") ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"s = glob.glob('/kaggle/input/rsna-pneu-train-png/orig/*.png')\nprint((s[0])[39:-4])   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = pd.read_csv(os.path.join(DATA_DIR, \"rsna-pneumonia-detection-challenge/stage_2_detailed_class_info.csv\"))\n#data = data.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#data","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ss = []\nfor i in s:\n    ss.append(i[39:-4])\n\nl_rm = []\nfor i in range(len(data['patientId'])):\n    if data['patientId'][i] not in ss:\n        l_rm.append(i)\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data = data.drop(l_rm, axis = 0) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data2 = data.drop_duplicates()\n#data2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data1 =  pd.read_csv(os.path.join(DATA_DIR, \"rsna-pneumonia-detection-challenge/stage_2_train_labels.csv\")) \n# dropping passed values \ndata1 = data1.drop(l_rm, axis = 0) \n#data1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#bbox_info = pd.read_csv(os.path.join(DATA_DIR, \"rsna-pneumonia-detection-challenge/stage_2_train_labels.csv\"))\n#detailed_class_info = pd.read_csv(os.path.join(DATA_DIR, \"rsna-pneumonia-detection-challenge/stage_2_detailed_class_info.csv\"))\n#detailed_class_info = detailed_class_info.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# To get started, we'll train on positives only\npositives = data2[data2[\"class\"] == \"Lung Opacity\"]\n\n# Annotations file should have no header and columns in the following order:\n# filename, x1, y1, x2, y2, class \npositives = positives.merge(data1, on=\"patientId\")\npositives = positives[[\"patientId\", \"x\", \"y\", \"width\", \"height\", \"Target\"]]\npositives[\"patientId\"] = [os.path.join(train_pngs_dir, \"{}.png\".format(_)) for _ in positives.patientId]\npositives[\"x1\"] = positives[\"x\"] \npositives[\"y1\"] = positives[\"y\"] \npositives[\"x2\"] = positives[\"x\"] + positives[\"width\"]\npositives[\"y2\"] = positives[\"y\"] + positives[\"height\"]\npositives[\"Target\"] = \"opacity\"\ndel positives[\"x\"], positives[\"y\"], positives[\"width\"], positives[\"height\"]\n\nnegatives = data2[data2[\"class\"] == \"Normal\"]\n\nnegatives = negatives.merge(data1, on=\"patientId\")\nnegatives = negatives[[\"patientId\", \"x\", \"y\", \"width\", \"height\", \"Target\"]]\nnegatives[\"patientId\"] = [os.path.join(train_pngs_dir, \"{}.png\".format(_)) for _ in negatives.patientId]\nnegatives[\"x1\"] = negatives[\"x\"] \nnegatives[\"y1\"] = negatives[\"x\"]  \nnegatives[\"x2\"] = negatives[\"x\"]  \nnegatives[\"y2\"] = negatives[\"x\"]  \nnegatives[\"Target\"] = \"normal\"\ndel negatives[\"x\"], negatives[\"y\"], negatives[\"width\"], negatives[\"height\"]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annotations = positives\n#annotations = annotations.append(negatives)\n\n# Before we save to CSV, we have to do some manipulating to make sure\n# bounding box coordinates are saved as integers and not floats \n# Note: This is only necessary if you include negatives in your annotations\nannotations = annotations.fillna(88888)\nannotations[\"x1\"] = annotations.x1.astype(\"int32\").astype(\"str\") \nannotations[\"y1\"] = annotations.y1.astype(\"int32\").astype(\"str\") \nannotations[\"x2\"] = annotations.x2.astype(\"int32\").astype(\"str\") \nannotations[\"y2\"] = annotations.y2.astype(\"int32\").astype(\"str\")\nannotations = annotations.replace({\"88888\": None}) \n\nannotations = annotations[[\"patientId\", \"x1\", \"y1\", \"x2\", \"y2\", \"Target\"]]\nannotations.to_csv(os.path.join(ROOT_DIR, \"annotations.csv\"), index=False, header=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"annotations","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes_file = pd.DataFrame({\"class\": [\"opacity\"], \"label\": [0]}) \nclasses_file.to_csv(os.path.join(ROOT_DIR, \"classes.csv\"), index=False, header=False)\n#classes_file = pd.DataFrame({\"class\": [\"normal\",\"opacity\"], \"label\": [0,1]}) \n#classes_file.to_csv(os.path.join(ROOT_DIR, \"classes.csv\"), index=False, header=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes_file","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install progressbar2","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":false,"trusted":true},"cell_type":"code","source":"%%writefile /kaggle/working/keras-retinanet/keras_retinanet/utils/eval.py\n\"\"\"\nCopyright 2017-2018 Fizyr (https://fizyr.com)\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n    http://www.apache.org/licenses/LICENSE-2.0\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom .anchors import compute_overlap\nfrom .visualization import draw_detections, draw_annotations\n\nimport keras\nimport numpy as np\nimport os\nimport time\n\nimport cv2\n#pip install progressbar2\nimport progressbar\n#assert(callable(progressbar.progressbar)), \"Using wrong progressbar module, install 'progressbar2' instead.\"\n\n\ndef _compute_ap(recall, precision):\n    \"\"\" Compute the average precision, given the recall and precision curves.\n    Code originally from https://github.com/rbgirshick/py-faster-rcnn.\n    # Arguments\n        recall:    The recall curve (list).\n        precision: The precision curve (list).\n    # Returns\n        The average precision as computed in py-faster-rcnn.\n    \"\"\"\n    # correct AP calculation\n    # first append sentinel values at the end\n    mrec = np.concatenate(([0.], recall, [1.]))\n    mpre = np.concatenate(([0.], precision, [0.]))\n\n    # compute the precision envelope\n    for i in range(mpre.size - 1, 0, -1):\n        mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])\n\n    # to calculate area under PR curve, look for points\n    # where X axis (recall) changes value\n    i = np.where(mrec[1:] != mrec[:-1])[0]\n\n    # and sum (\\Delta recall) * prec\n    ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n    return ap\n\n\ndef _get_detections(generator, model, score_threshold=0.05, max_detections=100, save_path=None):\n    \"\"\" Get the detections from the model using the generator.\n    The result is a list of lists such that the size is:\n        all_detections[num_images][num_classes] = detections[num_detections, 4 + num_classes]\n    # Arguments\n        generator       : The generator used to run images through the model.\n        model           : The model to run on the images.\n        score_threshold : The score confidence threshold to use.\n        max_detections  : The maximum number of detections to use per image.\n        save_path       : The path to save the images with visualized detections to.\n    # Returns\n        A list of lists containing the detections for each image in the generator.\n    \"\"\"\n    all_detections = [[None for i in range(generator.num_classes()) if generator.has_label(i)] for j in range(generator.size())]\n    all_inferences = [None for i in range(generator.size())]\n\n    for i in progressbar.progressbar(range(generator.size()), prefix='Running network: '):\n        raw_image    = generator.load_image(i)\n        image        = generator.preprocess_image(raw_image.copy())\n        image, scale = generator.resize_image(image)\n\n        if keras.backend.image_data_format() == 'channels_first':\n            image = image.transpose((2, 0, 1))\n\n        # run network\n        start = time.time()\n        boxes, scores, labels = model.predict_on_batch(np.expand_dims(image, axis=0))[:3]\n        inference_time = time.time() - start\n\n        # correct boxes for image scale\n        boxes /= scale\n\n        # select indices which have a score above the threshold\n        indices = np.where(scores[0, :] > score_threshold)[0]\n\n        # select those scores\n        scores = scores[0][indices]\n\n        # find the order with which to sort the scores\n        scores_sort = np.argsort(-scores)[:max_detections]\n\n        # select detections\n        image_boxes      = boxes[0, indices[scores_sort], :]\n        image_scores     = scores[scores_sort]\n        image_labels     = labels[0, indices[scores_sort]]\n        image_detections = np.concatenate([image_boxes, np.expand_dims(image_scores, axis=1), np.expand_dims(image_labels, axis=1)], axis=1)\n\n        if save_path is not None:\n            draw_annotations(raw_image, generator.load_annotations(i), label_to_name=generator.label_to_name)\n            draw_detections(raw_image, image_boxes, image_scores, image_labels, label_to_name=generator.label_to_name, score_threshold=score_threshold)\n\n            cv2.imwrite(os.path.join(save_path, '{}.png'.format(i)), raw_image)\n\n        # copy detections to all_detections\n        for label in range(generator.num_classes()):\n            if not generator.has_label(label):\n                continue\n\n            all_detections[i][label] = image_detections[image_detections[:, -1] == label, :-1]\n\n        all_inferences[i] = inference_time\n\n    return all_detections, all_inferences\n\n\ndef _get_annotations(generator):\n    \"\"\" Get the ground truth annotations from the generator.\n    The result is a list of lists such that the size is:\n        all_detections[num_images][num_classes] = annotations[num_detections, 5]\n    # Arguments\n        generator : The generator used to retrieve ground truth annotations.\n    # Returns\n        A list of lists containing the annotations for each image in the generator.\n    \"\"\"\n    all_annotations = [[None for i in range(generator.num_classes())] for j in range(generator.size())]\n\n    for i in progressbar.progressbar(range(generator.size()), prefix='Parsing annotations: '):\n        # load the annotations\n        annotations = generator.load_annotations(i)\n\n        # copy detections to all_annotations\n        for label in range(generator.num_classes()):\n            if not generator.has_label(label):\n                continue\n\n            all_annotations[i][label] = annotations['bboxes'][annotations['labels'] == label, :].copy()\n\n    return all_annotations\n\n\ndef evaluate(\n    generator,\n    model,\n    iou_threshold=0.5,\n    score_threshold=0.05,\n    max_detections=100,\n    save_path=None\n):\n    \"\"\" Evaluate a given dataset using a given model.\n    # Arguments\n        generator       : The generator that represents the dataset to evaluate.\n        model           : The model to evaluate.\n        iou_threshold   : The threshold used to consider when a detection is positive or negative.\n        score_threshold : The score confidence threshold to use for detections.\n        max_detections  : The maximum number of detections to use per image.\n        save_path       : The path to save images with visualized detections to.\n    # Returns\n        A dict mapping class names to mAP scores.\n    \"\"\"\n    # gather all detections and annotations\n    all_detections, all_inferences = _get_detections(generator, model, score_threshold=score_threshold, max_detections=max_detections, save_path=save_path)\n    all_annotations    = _get_annotations(generator)\n    average_precisions = {}\n\n    # all_detections = pickle.load(open('all_detections.pkl', 'rb'))\n    # all_annotations = pickle.load(open('all_annotations.pkl', 'rb'))\n    # pickle.dump(all_detections, open('all_detections.pkl', 'wb'))\n    # pickle.dump(all_annotations, open('all_annotations.pkl', 'wb'))\n\n    # process detections and annotations\n    for label in range(generator.num_classes()):\n        if not generator.has_label(label):\n            continue\n\n        false_positives = np.zeros((0,))\n        true_positives  = np.zeros((0,))\n        scores          = np.zeros((0,))\n        num_annotations = 0.0\n\n        for i in range(generator.size()):\n            detections           = all_detections[i][label]\n            annotations          = all_annotations[i][label]\n            num_annotations     += annotations.shape[0]\n            detected_annotations = []\n\n            for d in detections:\n                scores = np.append(scores, d[4])\n\n                if annotations.shape[0] == 0:\n                    false_positives = np.append(false_positives, 1)\n                    true_positives  = np.append(true_positives, 0)\n                    continue\n\n                overlaps            = compute_overlap(np.expand_dims(d, axis=0), annotations)\n                assigned_annotation = np.argmax(overlaps, axis=1)\n                max_overlap         = overlaps[0, assigned_annotation]\n\n                if max_overlap >= iou_threshold and assigned_annotation not in detected_annotations:\n                    false_positives = np.append(false_positives, 0)\n                    true_positives  = np.append(true_positives, 1)\n                    detected_annotations.append(assigned_annotation)\n                else:\n                    false_positives = np.append(false_positives, 1)\n                    true_positives  = np.append(true_positives, 0)\n\n        # no annotations -> AP for this class is 0 (is this correct?)\n        if num_annotations == 0:\n            average_precisions[label] = 0, 0\n            continue\n\n        # sort by score\n        indices         = np.argsort(-scores)\n        false_positives = false_positives[indices]\n        true_positives  = true_positives[indices]\n\n        # compute false positives and true positives\n        false_positives = np.cumsum(false_positives)\n        true_positives  = np.cumsum(true_positives)\n\n        # compute recall and precision\n        recall    = true_positives / num_annotations\n        precision = true_positives / np.maximum(true_positives + false_positives, np.finfo(np.float64).eps)\n\n        # compute average precision\n        average_precision  = _compute_ap(recall, precision)\n        average_precisions[label] = average_precision, num_annotations\n\n    # inference time\n    inference_time = np.sum(all_inferences) / generator.size()\n\n    return average_precisions, inference_time","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"!python /kaggle/working/keras-retinanet/keras_retinanet/bin/train.py --backbone \"resnet50\" --image-min-side 256 --image-max-side 256 --batch-size 32 --random-transform --epochs 50 --steps 100 csv /kaggle/working/annotations.csv /kaggle/working/classes.csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_01.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_02.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_03.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_04.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_05.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_06.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_07.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_08.h5\n!rm /kaggle/working/keras-retinanet/snapshots/resnet50_csv_09.h5","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!python /kaggle/working/keras-retinanet/keras_retinanet/bin/convert_model.py /kaggle/working/keras-retinanet/snapshots/resnet50_csv_11.h5 /kaggle/working/keras-retinanet/converted_model.h5 ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras_retinanet.models import load_model \n\nretinanet = load_model(os.path.join(ROOT_DIR, \"keras-retinanet/converted_model.h5\"), \n                       backbone_name=\"resnet50\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"retinanet.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def preprocess_input(x):\n    x = x.astype(\"float32\")\n    x[..., 0] -= 103.939\n    x[..., 1] -= 116.779\n    x[..., 2] -= 123.680\n    return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dicoms = glob.glob(os.path.join(test_dicoms_dir, \"*.dcm\"))\ntest_patient_ids = [_.split(\"/\")[-1].split(\".\")[0] for _ in test_dicoms]\ntest_predictions = [] \nfor i, dcm_file in enumerate(test_dicoms): \n    sys.stdout.write(\"Predicting images: {}/{} ...\\r\".format(i+1, len(test_dicoms)))\n    sys.stdout.flush() \n    # Load DICOM and extract pixel array \n    dcm = pydicom.read_file(dcm_file)\n    arr = dcm.pixel_array\n    # Make 3-channel image\n    img = np.zeros((arr.shape[0], arr.shape[1], 3))\n    for channel in range(img.shape[-1]):\n        img[..., channel] = arr \n    # Resize \n    # Change image size if necessary!\n    scale_factor = 256. / img.shape[0]\n    img = zoom(img, [scale_factor, scale_factor, 1], order=1, prefilter=False)\n    # Preprocess with ImageNet mean subtraction\n    img = preprocess_input(img) \n    prediction = retinanet.predict_on_batch(np.expand_dims(img, axis=0))\n    test_predictions.append(prediction)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_pred_df = pd.DataFrame() \nfor i, pred in enumerate(test_predictions):\n    # Take top 5 \n    # Should already be sorted in descending order by score\n    bboxes = pred[0][0][:5]\n    scores = pred[1][0][:5]\n    # -1 will be predicted if nothing is detected\n    detected = scores > -1 \n    if np.sum(detected) == 0: \n        continue\n    else:\n        bboxes = bboxes[detected]\n        bboxes = [box / scale_factor for box in bboxes]\n        scores = scores[detected]\n    individual_pred_df = pd.DataFrame() \n    for j, each_box in enumerate(bboxes): \n        # RetinaNet output is [x1, y1, x2, y2] \n        tmp_df = pd.DataFrame({\"patientId\": [test_patient_ids[i]], \n                               \"x\": [each_box[0]],  \n                               \"y\": [each_box[1]], \n                               \"w\": [each_box[2]-each_box[0]],\n                               \"h\": [each_box[3]-each_box[1]],\n                               \"score\": [scores[j]]})\n        individual_pred_df = individual_pred_df.append(tmp_df) \n    test_pred_df = test_pred_df.append(individual_pred_df) \n\ntest_pred_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true},"cell_type":"code","source":"test_pred_df.head(20)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"threshold = 0.35\n\nlist_of_pids = [] \nlist_of_preds = [] \nfor pid in np.unique(test_pred_df.patientId): \n    tmp_df = test_pred_df[test_pred_df.patientId == pid]\n    tmp_df = tmp_df[tmp_df.score >= threshold]\n    # Skip if empty\n    if len(tmp_df) == 0:\n        continue\n    predictionString = \" \".join([\"{} {} {} {} {}\".format(row.score, row.x, row.y, row.w, row.h) for rownum, row in tmp_df.iterrows()])\n    list_of_preds.append(predictionString)\n    list_of_pids.append(pid) \n\npositives = pd.DataFrame({\"patientId\": list_of_pids, \n                          \"PredictionString\": list_of_preds}) \n\nnegatives = pd.DataFrame({\"patientId\": list(set(test_patient_ids) - set(list_of_pids)), \n                          \"PredictionString\": [\"\"] * (len(test_patient_ids)-len(list_of_pids))})\n\nsubmission = positives.append(negatives)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#positives['PredictionString'][2]\npositives","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def pd_2dict(pd):\n    a = {'patientId':pd['patientId'][1], 'PredictionString':pd['PredictionString'][1]}\n    return a","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def post_process(df):\n    lst = []\n    box_lst = df[\"PredictionString\"].split()\n    for i in range(0,len(box_lst),5):\n        temp_lst = box_lst[i+1:i+5]\n        lst.append(temp_lst)\n    output = {'patientId': df[\"patientId\"], 'boxes': lst}    \n    return output","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def draw(data):\n    \"\"\"\n    Method to draw single patient with bounding box(es) if present \n\n    \"\"\"\n    # --- Open DICOM file\n    img_loc = os.path.join(DATA_DIR, \"rsna-pneumonia-detection-challenge/stage_2_test_images/%s.dcm\"%(data['patientId']))\n    d = pydicom.read_file(img_loc)\n    im = d.pixel_array\n\n    # --- Convert from single-channel grayscale to 3-channel RGB\n    im = np.stack([im] * 3, axis=2)\n\n    # --- Add boxes with random color if present\n    for box in data['boxes']:\n        box = [float(b) for b in box]\n        rgb = np.floor(np.random.rand(3) * 256).astype('int')\n        im = overlay_box(im=im, box=box, rgb=rgb, stroke=6)\n\n    pylab.imshow(im, cmap=pylab.cm.gist_gray)\n    pylab.axis('off')\n    \ndef overlay_box(im, box, rgb, stroke=1):\n    \"\"\"\n    Method to overlay single box on image\n\n    \"\"\"\n    # --- Convert coordinates to integers\n    box = [int(b) for b in box]\n    \n    # --- Extract coordinates\n    y1, x1, height, width = box\n    y2 = y1 + height\n    x2 = x1 + width\n\n    im[y1:y1 + stroke, x1:x2] = rgb\n    im[y2:y2 + stroke, x1:x2] = rgb\n    im[y1:y2, x1:x1 + stroke] = rgb\n    im[y1:y2, x2:x2 + stroke] = rgb\n\n    return im","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"b = pd_2dict(positives)\nb = post_process(b)\nb","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"draw(b)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"retinanet.save('retinanet_1.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"weights = retinanet.save_weights(os.path.join(ROOT_DIR, \"weights_retinanet\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#change dcm to png\n\nimport cv2\nimport os\nimport pydicom\n\ninputdir = os.path.join(\"/kaggle/input/\", 'rsna-pneumonia-detection-challenge/stage_2_train_images/')\noutdir = '../outputs/rsna-pneumonia-detection-challenge/stage_2_train_png_images/'\n#os.mkdir(outdir)\n\ntrain_list = [ f for f in  os.listdir(inputdir)]\n\nfor f in train_list:   # remove \"[:10]\" to convert all images \n    ds = pydicom.read_file(inputdir + f) # read dicom image\n    img = ds.pixel_array # get image array\n    cv2.imwrite(outdir + f.replace('.dcm','.png'),img) # write png image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2 \n  \n# Save image in set directory \n# Read RGB image \nimg = cv2.imread('/kaggle/input/rsna-pneu-train-png/orig/01027bc3-dc40-4165-a6c3-d6be2cb7ca34.png')\nimg2 = cv2.imread('/kaggle/input/rsna-pneu-train-png/orig/000db696-cf54-4385-b10b-6b16fbb3f985.png')\nprint(img2)","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}