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.
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.
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.
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.
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_filefor existing JPEG files ortf.io.encode_jpegfor in-memory tensors. - Serialize with
tf.train.ExampleandTFRecordWriter. - Parse the bytes as
tf.string, then decode withtf.io.decode_jpeg. - Keep the feature schema consistent across every record.
Related reading
- How do tf.gradients work?
- How do the loss weights work in Tensorflow?
- How do we deploy a trained tensorflow model on a mobile device?
- How do you add new categories and training to a pretrained Inception v3 model in TensorFlow?
- How do loss functions know for which model to compute gradients in PyTorch?
- How do recommendation systems work?
- How do you compute accuracy in a regression model, after rounding predictions to classes, in keras?
- How do you create a boolean mask for a tensor in Keras?
System design interview problems on this topic
- Design an E-commerce Recommendation System: solution and walkthrough
- Design an LLM Inference Service: solution and walkthrough
- Design a GPU Cluster Scheduler for ML Training: solution and walkthrough
- Design ChatGPT: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.