application_vnd.jupyter.stderr_output_2.png text_plain_output_3.png text_plain_output_1.png
import cv2

import tensorflow as tf

PATH = '../input/rsna-bone-age/boneage-training-dataset/boneage-training-dataset/'
IMGS = os.listdir(PATH)

df = pd.read_csv('../input/rsna-bone-age/boneage-training-dataset.csv')

def _bytes_feature(value):
    """Returns a bytes_list from a string / byte."""
    if isinstance(value, type(tf.constant(0))):
        value = value.numpy()
    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _int64_feature(value):
    """Returns an int64_list from a bool / enum / int / uint."""
    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

def serialize_example(feature0, feature1, feature2, feature3):
    feature = {'image': _bytes_feature(feature0), 'id': _bytes_feature(feature1), 'boneage': _int64_feature(feature2), 'male': _int64_feature(feature3)}
    example_proto = tf.train.Example(features=tf.train.Features(feature=feature))
    return example_proto.SerializeToString()

SIZE = 841
CT = len(IMGS) // SIZE + int(len(IMGS) % SIZE != 0)
for j in range(CT):
    print()
    print('Writing TFRecord %i of %i...' % (j, CT))
    CT2 = min(SIZE, len(IMGS) - j * SIZE)
    with tf.io.TFRecordWriter('bone_age_tfrecords/train%.2i-%i.tfrec' % (j, CT2)) as writer:
        for k in range(CT2):
            img = cv2.imread(PATH + IMGS[SIZE * j + k])
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
            img = cv2.imencode('.jpg', img, (cv2.IMWRITE_JPEG_QUALITY, 94))[1].tobytes()
            name = IMGS[SIZE * j + k].split('.')[0]
            row = df.loc[df['id'] == int(name)]
            example = serialize_example(img, str.encode(name), row.boneage.values[0], row.male.values[0])
            writer.write(example)
            if k % 100 == 0:
                print(k, ', ', end='')