{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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 the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 1. Image Conversion"},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"from __future__ import absolute_import, division, print_function\n \nimport tensorflow as tf\nprint(tf.VERSION)\n  \ntf.enable_eager_execution()\n \nAUTOTUNE = tf.data.experimental.AUTOTUNE\n \nimport IPython.display as display\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#df = pd.read_csv('../input/iwildcam-2019-fgvc6/train.csv')\ndf = pd.read_csv('../input/train.csv')\n  \nf = df['file_name']\nid = df['category_id']\n \nall_image_paths = ['../input/train_images/' + fname for fname in f]\nall_image_labels = [i for i in id]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(all_image_paths[:10])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(all_image_labels[:10])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = open(all_image_paths[0], 'rb').read()\nprint(repr(img)[:100])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = open(all_image_paths[0], 'rb').read() #byte string \nprint(repr(img)[:100])\ndisplay.Image(img)\n# works perfectly.\n\n\n# another way to open the file\nimg2 = tf.io.read_file(all_image_paths[0])\nprint(repr(img2)[:100]+\"...\")\ndisplay.display(display.Image(img2.numpy()))\ndisplay.Image(img2.numpy())\n\n# loading image files in two different ways","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#import matplotlib.pyplot as plt\nimg = tf.io.read_file(all_image_paths[110735]) # smart tf.method, so that no need to spefify the type of each file \na = tf.io.decode_jpeg(img) # to run the plt.imshow, we need to decode the above one so that the function can read \nplt.imshow(a) # file showing function \nprint(a) # lets see how things were decoded","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img3 = tf.io.encode_jpeg(a)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"display.Image(img3.numpy()) # image encoding and decoding ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img = tf.io.read_file(all_image_paths[40252])\na = tf.io.decode_jpeg(img)\nprint(a.shape)\ntemp = tf.image.resize_images(a, [28,28])\ntemp = tf.dtypes.cast(temp, tf.uint8) #cast: transform one data type into another especially in \"dtypes.cast\"\n# unit8: unsinged integer, smallest ones all zeros, biggest ones are all ones \nb = tf.io.encode_jpeg(temp)\ndisplay.Image(b.numpy())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# 2. TFRecord"},{"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))):\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 _float_feature(value):\n  \"\"\"Returns a float_list from a float / double.\"\"\"\n  return tf.train.Feature(float_list=tf.train.FloatList(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":"img5 = tf.io.read_file(all_image_paths[40252])\n#_bytes_feature(img5) #smaller","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"paths_labels = dict(zip(all_image_paths[0:10], all_image_labels[0:10]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def image_example(image_string, label):\n    feature = {\n      'label': _int64_feature(label),\n      'image_raw': _bytes_feature(image_string),\n  }\n    return tf.train.Example(features=tf.train.Features(feature=feature))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"record_file = 'images.tfrecords'\nwith tf.io.TFRecordWriter(record_file) as writer:\n    for filename, label in paths_labels.items():\n        image_string = open(filename, 'rb').read()  \n        tf_example = image_example(image_string, label)\n        writer.write(tf_example.SerializeToString()) #evrying should be in a one sequence","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls -al","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#!ls ../input/train_images/ -al","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"paths_labels2 = dict(zip(all_image_paths[0:1000], all_image_labels[0:10]))\nrecord_file = 'images.tfrecords2'\nwith tf.io.TFRecordWriter(record_file) as writer:\n    for filename, label in paths_labels2.items():\n        #image_string = open(filename, 'rb').read() \n        image_string = tf.io.read_file(filename)\n        tf_example = image_example(image_string, label)\n        writer.write(tf_example.SerializeToString())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#!ls -al","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# How to read TFRecord files?\n* we can add and load our newly made tensor-tfrecords data into this kernel\n* Through 'Workspace' on our right side menu"},{"metadata":{"trusted":true},"cell_type":"code","source":"raw_image_dataset = tf.data.TFRecordDataset('images.tfrecords')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def parse(x):\n    feature = {'image_raw':tf.io.FixedLenFeature([],tf.string),\n             'label':tf.io.FixedLenFeature([],tf.int64)}\n    return tf.io.parse_single_example(x,feature)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = raw_image_dataset.map(parse)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# for i in ds.take(1):\n#     print(i['image_raw'].numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in ds:\n    print(i['label'].numpy())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Buffer, Repeat and Batch"},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = ds.shuffle(buffer_size=10) # take the specified number of buffer_size, and spits out randomly withing the batch\n#ds = ds.shuffle(buffer_size=1) #first one comes and that same thing goes out, so bascially same order \n\nfor i in ds:\n    print(i['label'].numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = ds.repeat(2) # if \"ds.repeat(), this will repeat forever\"\n\nfor i in ds:\n    print(i['label'].numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#ds = ds.batch(1)\nds = ds.batch(2) # take the specified number of units at once\nfor i in ds:\n    print(i['label'].numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds = ds.batch(2) \nfor i in ds:\n    print(i['label'].numpy())","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# for further understanding\nhttps://www.tensorflow.org/tutorials/load_data/tf_records"},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}