{"cells":[{"metadata":{},"cell_type":"markdown","source":"https://www.kaggle.com/vatsalparsaniya/melanoma-hair-remove\n\n\n\nhttps://www.kaggle.com/cdeotte/how-to-create-tfrecords/data?","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import os\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nimport pandas as pd\nBASE_PATH = '../input/siim-isic-melanoma-classification'\nhair_images =['ISIC_0078712','ISIC_0080817','ISIC_0082348','ISIC_0109869','ISIC_0155012','ISIC_0159568','ISIC_0164145','ISIC_0194550','ISIC_0194914','ISIC_0202023']\nwithout_hair_images = ['ISIC_0015719','ISIC_0074268','ISIC_0075914','ISIC_0084395','ISIC_0085718','ISIC_0081956']\nl = len(hair_images[:8])\n\nfig = plt.figure(figsize=(20,30))\n\nfor i,image_name in enumerate(hair_images[:8]):\n    \n    \n    image = cv2.imread(BASE_PATH + '/jpeg/train/' + image_name + '.jpg')\n    image_resize = cv2.resize(image,(1024,1024))\n    plt.subplot(l, 5, (i*5)+1)\n    # Convert the original image to grayscale\n    plt.imshow(cv2.cvtColor(image_resize, cv2.COLOR_BGR2RGB))\n    plt.axis('off')\n    plt.title('Original : '+ image_name)\n    \n    grayScale = cv2.cvtColor(image_resize, cv2.COLOR_RGB2GRAY)\n    plt.subplot(l, 5, (i*5)+2)\n    plt.imshow(grayScale)\n    plt.axis('off')\n    plt.title('GrayScale : '+ image_name)\n    \n    # Kernel for the morphological filtering\n    kernel = cv2.getStructuringElement(1,(17,17))\n    \n    # Perform the blackHat filtering on the grayscale image to find the hair countours\n    blackhat = cv2.morphologyEx(grayScale, cv2.MORPH_BLACKHAT, kernel)\n    plt.subplot(l, 5, (i*5)+3)\n    plt.imshow(blackhat)\n    plt.axis('off')\n    plt.title('blackhat : '+ image_name)\n    \n    # intensify the hair countours in preparation for the inpainting \n    ret,threshold = cv2.threshold(blackhat,10,255,cv2.THRESH_BINARY)\n    plt.subplot(l, 5, (i*5)+4)\n    plt.imshow(threshold)\n    plt.axis('off')\n    plt.title('threshold : '+ image_name)\n    \n    # inpaint the original image depending on the mask\n    final_image = cv2.inpaint(image_resize,threshold,1,cv2.INPAINT_TELEA)\n    plt.subplot(l, 5, (i*5)+5)\n    plt.imshow(cv2.cvtColor(final_image, cv2.COLOR_BGR2RGB))\n    plt.axis('off')\n    plt.title('final_image : '+ image_name)\n       \nplt.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def hair_remove(image):\n    # convert image to grayScale\n    grayScale = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n    \n    # kernel for morphologyEx\n    kernel = cv2.getStructuringElement(1,(17,17))\n    \n    # apply MORPH_BLACKHAT to grayScale image\n    blackhat = cv2.morphologyEx(grayScale, cv2.MORPH_BLACKHAT, kernel)\n    \n    # apply thresholding to blackhat\n    _,threshold = cv2.threshold(blackhat,10,255,cv2.THRESH_BINARY)\n    \n    # inpaint with original image and threshold image\n    final_image = cv2.inpaint(image,threshold,1,cv2.INPAINT_TELEA)\n    \n    return final_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i,image_name in enumerate(hair_images[:5]):\n    \n    fig = plt.figure(figsize=(5,5))\n    \n    image = cv2.imread(BASE_PATH + '/jpeg/train/' + image_name + '.jpg')\n    image_resize = cv2.resize(image,(512,512))\n    plt.subplot(1, 2, 1)\n    plt.imshow(cv2.cvtColor(image_resize, cv2.COLOR_BGR2RGB))\n    plt.axis('off')\n    plt.title('Original : '+ image_name)\n    \n    final_image = hair_remove(image_resize)\n    plt.subplot(1, 2, 2)\n    plt.imshow(cv2.cvtColor(final_image, cv2.COLOR_BGR2RGB))\n    plt.axis('off')\n    plt.title('Hair Removed : '+ image_name)\n    \n    plt.plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import numpy as np, pandas as pd, os\nimport matplotlib.pyplot as plt, cv2\nimport tensorflow as tf, re, math","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!ls /kaggle/input","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"PATH = '../input/melanoma-merged-external-data-512x512-jpeg/512x512-test/512x512-test/'\nIMGS = os.listdir(PATH)\nprint('There%i test images'%(len(IMGS)))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv('../input/melanoma-merged-external-data-512x512-jpeg/marking.csv')\ndf.rename({'image_id':'image_name'},axis=1,inplace=True)\ndf.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('../input/siim-isic-melanoma-classification/test.csv')\ntest.head(5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# COMBINE TRAIN AND TEST TO ENCODE TOGETHER\ncols = test.columns\ncomb = pd.concat([df[cols],test[cols]],ignore_index=True,axis=0).reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cats = ['patient_id','sex','anatom_site_general_challenge'] \nfor c in cats:\n    comb[c],mp = comb[c].factorize()\n    print(mp)\nprint('Imputing Age NaN count =',comb.age_approx.isnull().sum())\ncomb.age_approx.fillna(comb.age_approx.mean(),inplace=True)\ncomb['age_approx'] = comb.age_approx.astype('int')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# REWRITE DATA TO DATAFRAMES\ndf[cols] = comb.loc[:df.shape[0]-1,cols].values\ntest[cols] = comb.loc[df.shape[0]:,cols].values\n# LABEL ENCODE TRAIN SOURCE\ndf.source,mp = df.source.factorize()\nprint(mp)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.head(5)","execution_count":null,"outputs":[]},{"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]))\n\ndef serialize_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  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":"# Write TFRecords - Test\n\ndef serialize_example2(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  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":"SIZE = 687\nCT = len(IMGS)//SIZE + int(len(IMGS)%SIZE!=0)\nfor j in range(CT):\n    print(); print('Writing TFRecord %i of %i...'%(j,CT))\n    CT2 = min(SIZE,len(IMGS)-j*SIZE)\n    with tf.io.TFRecordWriter('test%.2i-%i.tfrec'%(j,CT2)) as writer:\n        for k in range(CT2):\n            img = cv2.imread(PATH+IMGS[SIZE*j+k])\n            img = hair_remove(img)\n            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) # Fix incorrect colors\n            img = cv2.imencode('.jpg', img, (cv2.IMWRITE_JPEG_QUALITY, 94))[1].tostring()\n            name = IMGS[SIZE*j+k].split('.')[0]\n            row = test.loc[test.image_name==name]\n            example = serialize_example2(\n                img, str.encode(name),\n                row.patient_id.values[0],\n                row.sex.values[0],\n                row.age_approx.values[0],                        \n                row.anatom_site_general_challenge.values[0])\n            writer.write(example)\n            if k%100==0: print(k,', ',end='')","execution_count":null,"outputs":[]},{"metadata":{"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, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    #if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n    #    numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\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":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\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    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = example['image_name']\n    return image, label # returns a dataset of (image, label) pairs\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef 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":"# INITIALIZE VARIABLES\nIMAGE_SIZE= [512,512]; BATCH_SIZE = 32\nAUTO = tf.data.experimental.AUTOTUNE\nTest_FILENAMES = tf.io.gfile.glob('test*.tfrec')\nprint('There are %i test images'%count_data_items(Test_FILENAMES))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_FILENAMES = Test_FILENAMES\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().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":"","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}