{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Create Various Sizes of External Data\n\nThis notebook creates various image sizes of TFRecords with external data from the original dataset [512x512 Melanoma TFRecords 70k Images][1] made by [Chris Deotte][2].\n\nThe code below is used to resize the image. `interpolation=cv2.INTER_AREA` is from the description of [Melanoma TFRecords 512x512][3].\n\n```python\n    cv2.resize(image, RESIZE_TO, interpolation=cv2.INTER_AREA)\n```\n\nAnd the code below is for encoding to JPEG. These lines are taken from the notebook [How To Create TFRecords][4].\n\n```python\n    cv2.cvtColor(image, cv2.COLOR_RGB2BGR) # Fix incorrect colors\n    cv2.imencode('.jpg', image, (cv2.IMWRITE_JPEG_QUALITY, JPEG_QUALITY))[1].tostring()\n```\n\nThe table below shows the image size and JPEG quality. JPEG quality is selected to fit the total created file size into the Kaggle run time limitation 5GB.\n\n|Image Size|JPG quality|\n|:-:|:-:|\n|768x768|85%|\n|384x384|98%|\n|256x256|100%|\n\n<br><br>\nThe majority part of the code in this notebook is taken from [How To Create TFRecords][4]. \nThe starting point of this notebook is the discussion [CNN Input Size Explained][5].\n\n[1]: https://www.kaggle.com/cdeotte/512x512-melanoma-tfrecords-70k-images\n[2]: https://www.kaggle.com/cdeotte\n[3]: https://www.kaggle.com/cdeotte/melanoma-512x512\n[4]: https://www.kaggle.com/cdeotte/how-to-create-tfrecords\n[5]: https://www.kaggle.com/c/siim-isic-melanoma-classification/discussion/160147","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"## Preparation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# RESIZE_TO = (768, 768)\nRESIZE_TO = (384, 384)\n# RESIZE_TO = (256, 256)\n\nif RESIZE_TO == (768, 768):\n    JPEG_QUALITY = 85\nelif  RESIZE_TO == (384, 384):\n    JPEG_QUALITY = 98\nelse:\n    JPEG_QUALITY = 100\n    \nprint(\"RESIZE_TO: {0}\".format(RESIZE_TO))\nprint(\"JPEG_QUALITY: {0}%\".format(JPEG_QUALITY))","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 cv2\nimport os\nimport tensorflow as tf\nimport re\nimport math\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('../input'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(tf.__version__)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\n# you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('512x512-melanoma-tfrecords-70k-images')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/train*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/test*.tfrec')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Datasets","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        \"patient_id\": tf.io.FixedLenFeature([], tf.int64),\n        \"sex\": tf.io.FixedLenFeature([], tf.int64),\n        \"age_approx\": tf.io.FixedLenFeature([], tf.int64),\n        \"anatom_site_general_challenge\": tf.io.FixedLenFeature([], tf.int64),\n        \"source\": tf.io.FixedLenFeature([], tf.int64),\n        \"target\": tf.io.FixedLenFeature([], tf.int64),\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    image_name = example['image_name']\n    patient_id = example['patient_id']\n    sex = example['sex']\n    age_approx = example['age_approx']\n    anatom_site_general_challenge = example['anatom_site_general_challenge']\n    source = example['source']\n    target = example['target']\n    # returns an image and features\n    return image, (image_name, patient_id, sex, age_approx, \\\n            anatom_site_general_challenge, source, target)\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"image_name\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        \"patient_id\": tf.io.FixedLenFeature([], tf.int64),\n        \"sex\": tf.io.FixedLenFeature([], tf.int64),\n        \"age_approx\": tf.io.FixedLenFeature([], tf.int64),\n        \"anatom_site_general_challenge\": tf.io.FixedLenFeature([], tf.int64),\n        # no 'source' and 'target' for the test data.\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    image_name = example['image_name']\n    patient_id = example['patient_id']\n    sex = example['sex']\n    age_approx = example['age_approx']\n    anatom_site_general_challenge = example['anatom_site_general_challenge']\n    # returns an image and features\n    return image, (image_name, patient_id, sex, age_approx, \\\n            anatom_site_general_challenge)\n\ndef load_dataset(filenames, labeled=True):\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=None)\n    read_tfrecord = read_labeled_tfrecord if labeled else read_unlabeled_tfrecord\n    dataset = dataset.map(read_tfrecord, num_parallel_calls=None)\n    # returns a dataset of (image, features) pairs\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Write TFRecords","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def _bytes_feature(value):\n    \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n    if isinstance(value, type(tf.constant(0.0))):\n        value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\ndef _int64_feature(value):\n    \"\"\"Returns an int64_list from a bool / enum / int / uint.\"\"\"\n    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def serialize_train_example(feature0, feature1, feature2, feature3, feature4, feature5, feature6, feature7):\n    feature = {\n        'image': _bytes_feature(feature0),\n        'image_name': _bytes_feature(feature1),\n        'patient_id': _int64_feature(feature2),\n        'sex': _int64_feature(feature3),\n        'age_approx': _int64_feature(feature4),\n        'anatom_site_general_challenge': _int64_feature(feature5),\n        'source': _int64_feature(feature6),\n        'target': _int64_feature(feature7)\n    }\n    \n    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n    return example_proto.SerializeToString()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def serialize_test_example(feature0, feature1, feature2, feature3, feature4, feature5): \n    feature = {\n        'image': _bytes_feature(feature0),\n        'image_name': _bytes_feature(feature1),\n        'patient_id': _int64_feature(feature2),\n        'sex': _int64_feature(feature3),\n        'age_approx': _int64_feature(feature4),\n        'anatom_site_general_challenge': _int64_feature(feature5),\n    }\n    \n    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))\n    return example_proto.SerializeToString()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def write_tf_records(file_paths, labeled, serialize_example):\n    for file_index, file_path in enumerate(file_paths):\n        print()\n        print('Writing TFRecord %i of %i...' % (file_index + 1, len(file_paths)))\n        file_name = os.path.basename(file_path)\n        with tf.io.TFRecordWriter(file_name) as writer:\n            dataset = load_dataset(file_path, labeled)\n            for data_index, (image_tensor, features) in enumerate(iter(dataset)):\n                image_np = image_tensor.numpy()\n                resized_image = cv2.resize(image_np, RESIZE_TO, interpolation=cv2.INTER_AREA)\n                fixed_image = cv2.cvtColor(resized_image, cv2.COLOR_RGB2BGR) # Fix incorrect colors\n                jpg_image = cv2.imencode('.jpg', fixed_image, (cv2.IMWRITE_JPEG_QUALITY, JPEG_QUALITY))[1].tostring()\n                example = serialize_example(jpg_image, *features)\n                writer.write(example)\n                if data_index % 100 == 0:\n                    print(data_index, ', ', end='')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"write_tf_records(TRAINING_FILENAMES, True, serialize_train_example)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"write_tf_records(TEST_FILENAMES, False, serialize_test_example)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"! ls -l","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Verify TFRecords","execution_count":null},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\nCLASSES = [0,1]\n\ndef batch_to_numpy_images_and_labels(data):\n    images, features = data\n    numpy_images = images.numpy()\n    numpy_labels = features[0].numpy()\n    if 7 <= len(features):\n        numpy_targets = features[6].numpy()\n        numpy_labels = [ \"{0}: {1}\".format(lbl, tgt) for lbl, tgt in zip(numpy_labels, numpy_targets) ]\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        title = label\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"RESIZED_TRAINING_FILENAMES = tf.io.gfile.glob('train*.tfrec')\nprint('There are %i train images' % count_data_items(RESIZED_TRAINING_FILENAMES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# DISPLAY TRAIN IMAGES\ntraining_dataset = load_dataset(RESIZED_TRAINING_FILENAMES, labeled=True)\ntraining_dataset = training_dataset.batch(20)\ntrain_batch = iter(training_dataset)\n\ndisplay_batch_of_images(next(train_batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"RESIZED_TEST_FILENAMES = tf.io.gfile.glob('test*.tfrec')\nprint('There are %i test images' % count_data_items(RESIZED_TEST_FILENAMES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# DISPLAY TEST IMAGES\ntest_dataset = load_dataset(RESIZED_TEST_FILENAMES, labeled=False)\ntest_dataset = test_dataset.batch(20)\ntest_batch = iter(test_dataset)\n\ndisplay_batch_of_images(next(test_batch))","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}