TensorFlow
TFRecord
JPEG encoding
data serialization
machine learning

How do I write an encoded jpeg as bytes to Tensorflow tfrecord and then read it?

ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design

Introduction

A TFRecord can store a JPEG exactly as a byte string, which is often the simplest and fastest way to keep image data in a training pipeline. The usual pattern is to serialize the encoded JPEG bytes into a tf.train.Example, then parse that example later and decode the bytes back into an image tensor.

Why Store Encoded Bytes Instead Of Raw Pixels

Storing encoded JPEG bytes keeps the record smaller than writing uncompressed pixel arrays. It also matches how many image datasets are distributed on disk, which means you can read the file once and store the bytes directly.

A TFRecord example usually includes:

  • one bytes feature for the JPEG payload
  • optional numeric or string features such as label, height, or filename

Write A JPEG To TFRecord

This example reads an existing JPEG file from disk and stores its bytes along with a label.

python
1import tensorflow as tf
2
3
4def bytes_feature(value):
5    return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
6
7
8def int64_feature(value):
9    return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
10
11
12image_path = "sample.jpg"
13label = 3
14
15jpeg_bytes = tf.io.read_file(image_path).numpy()
16
17example = tf.train.Example(
18    features=tf.train.Features(
19        feature={
20            "image_jpeg": bytes_feature(jpeg_bytes),
21            "label": int64_feature(label),
22        }
23    )
24)
25
26with tf.io.TFRecordWriter("images.tfrecord") as writer:
27    writer.write(example.SerializeToString())

The important part is that tf.io.read_file returns the encoded file contents, not decoded pixels. That is exactly what you want for a bytes feature.

Encode An In-Memory Image First

If your image starts as a tensor or NumPy array, encode it before writing.

python
1import tensorflow as tf
2
3image = tf.ones([64, 64, 3], dtype=tf.uint8) * 127
4jpeg_bytes = tf.io.encode_jpeg(image).numpy()
5
6example = tf.train.Example(
7    features=tf.train.Features(
8        feature={
9            "image_jpeg": tf.train.Feature(
10                bytes_list=tf.train.BytesList(value=[jpeg_bytes])
11            )
12        }
13    )
14)
15
16with tf.io.TFRecordWriter("generated.tfrecord") as writer:
17    writer.write(example.SerializeToString())

This is useful when images are generated or transformed in memory before serialization.

Read The TFRecord Back

To read the file, define a feature description, parse each serialized example, and decode the JPEG bytes.

python
1import tensorflow as tf
2
3feature_description = {
4    "image_jpeg": tf.io.FixedLenFeature([], tf.string),
5    "label": tf.io.FixedLenFeature([], tf.int64),
6}
7
8
9def parse_example(serialized_example):
10    parsed = tf.io.parse_single_example(serialized_example, feature_description)
11    image = tf.io.decode_jpeg(parsed["image_jpeg"], channels=3)
12    label = parsed["label"]
13    return image, label
14
15
16dataset = tf.data.TFRecordDataset(["images.tfrecord"])
17dataset = dataset.map(parse_example)
18
19for image, label in dataset.take(1):
20    print(image.shape)
21    print(label.numpy())

The JPEG stays compressed in storage and is decoded only when the pipeline reads it. That is one reason TFRecord works well with tf.data input pipelines.

Add More Metadata When Needed

If you need filename, height, width, or split information, add extra features to the same example. For example, storing the original filename can be helpful for debugging misclassified images later.

Use bytes features for strings and int64 features for integer metadata. Keep the schema consistent across all records in the file.

Common Pitfalls

The most common mistake is decoding the JPEG to pixels and then trying to store that tensor in a bytes feature without re-encoding it. Raw pixel bytes and encoded JPEG bytes are not the same thing.

Another mistake is forgetting .numpy() in eager mode when building the BytesList. The feature writer expects ordinary Python bytes, not a symbolic tensor object.

A third issue is using the wrong parser type on read. If the stored feature is a byte string, parse it as tf.string and then call tf.io.decode_jpeg after parsing.

Summary

  • Store JPEGs in TFRecord as encoded byte strings, not as decoded pixel arrays.
  • Use tf.io.read_file for existing JPEG files or tf.io.encode_jpeg for in-memory tensors.
  • Serialize with tf.train.Example and TFRecordWriter.
  • Parse the bytes as tf.string, then decode with tf.io.decode_jpeg.
  • Keep the feature schema consistent across every record.

Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
ML System Design practice on Codemia

Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.

Practice ML system design