TensorFlow Image Data Processing
What is image data
Image data is a 2D matrix composed of pixels (grayscale images) or a 3D tensor (color images). In TensorFlow, images are typically represented as:
- Grayscale image: [height, width] or [height, width, 1]
- Color image: [height, width, 3] (RGB channels)
Why image processing is needed
- Data standardization: unify image size and value range
- Data augmentation: increase training sample diversity through transformations
- Feature extraction: highlight key information in images
- Preprocessing: prepare appropriate data formats for model input
TensorFlow image processing core APIs
tf.image module
A collection of APIs provided by TensorFlow specifically for image processing:
Example
import
tensorflow
as
tf
from
tensorflow
import
image
as
tf_image
Common function categories:
| Function category | Main method examples |
|---|---|
| Color adjustment | adjust_brightness, adjust_contrast |
| Geometric transformation | flip, rotate, crop_to_bounding_box |
| Image composition | blend, draw_bounding_boxes |
| Format conversion | encode_jpeg, decode_image |
| Statistical operations | total_variation, per_image_standardization |
Detailed image preprocessing techniques
Standardization
Normalize pixel values to a fixed range (usually [0,1] or [-1,1]):
Example
def
normalize
(
image
)
:
"""Normalize a uint8 image to the [0,1] range"""
image
=
tf.
cast
(
image
,
tf.
float32
)
Convert to float32
return
image /
255.0
Divide by the maximum value
Usage examples
image
=
tf.
random
.
uniform
(
[
256
,
256
,
3
]
,
0
,
255
,
dtype
=
tf.
uint8
)
normalized_image
=
normalize
(
image
)
Data augmentation techniques
Increase data diversity through random transformations:
Example
def
augment_image
(
image
,
label
)
:
"""An image processing pipeline applying random augmentation"""
Random horizontal flip
image
=
tf_image.
random_flip_left_right
(
image
)
Random brightness adjustment
image
=
tf_image.
random_brightness
(
image
,
max_delta
=
0.2
)
Random contrast adjustment
image
=
tf_image.
random_contrast
(
image
,
lower
=
0.8
,
upper
=
1.2
)
Random rotation (-15° to +15°)
angle
=
tf.
random
.
uniform
(
[
]
,
15
,
15
)
(
3.1415
/
180
)
image
=
tf_image.
rotate
(
image
,
angle
)
return
image
,
label
Image loading and batch processing workflow
Complete processing workflow

Actual code implementation
Example
def
preprocess_dataset
(
dataset
,
batch_size
=
32
,
is_training
=
False
)
:
"""Build an image preprocessing pipeline"""
Define the preprocessing function
def
_preprocess
(
image
,
label
)
:
Decode the JPEG image
image
=
tf_image.
decode_jpeg
(
image
,
channels
=
3
)
Resize to a uniform size
image
=
tf_image.
resize
(
image
,
[
224
,
224
]
)
Apply data augmentation during training
if
is_training:
image
=
augment_image
(
image
)
Standardization
image
=
normalize
(
image
)
return
image
,
label
Apply preprocessing and create batches
dataset
=
dataset.
map
(
_preprocess
,
num_parallel_calls
=
tf.
data
.
AUTOTUNE
)
dataset
=
dataset.
batch
(
batch_size
)
dataset
=
dataset.
prefetch
(
tf.
data
.
AUTOTUNE
)
return
dataset
Advanced image processing techniques
Use Keras preprocessing layers
TensorFlow 2.x provides more advanced preprocessing APIs:
Example
from
tensorflow.
keras
.
layers
.
experimental
import
preprocessing
Create a preprocessing model
augmenter
=
tf.
keras
.
Sequential
(
[
preprocessing.
RandomFlip
(
"horizontal"
)
,
preprocessing.
RandomRotation
(
0.1
)
,
preprocessing.
RandomZoom
(
0.1
)
,
preprocessing.
Rescaling
(
1
./
255
)
Standardization
]
)
Use in a model
model
=
tf.
keras
.
Sequential
(
[
augmenter
,
Data augmentation layers
tf.
keras
.
layers
.
Conv2D
(
32
,
3
,
activation
=
'relu'
)
,
Other layers...
]
)
Custom image processing layers
Implement custom preprocessing operations:
Example
class
RandomColorDistortion
(
tf.
keras
.
layers
.
Layer
)
:
def
init
(
self
,
contrast_range
=
[
0.5
,
1.5
]
,
**kwargs
)
:
super
(
)
.
init
(
**kwargs
)
self
.
contrast_range
=
contrast_range
def
call
(
self
,
images
,
training
=
None
)
:
if
not
training:
return
images
Random contrast adjustment
contrast_factor
=
tf.
random
.
uniform
(
[
]
,
self
.
contrast_range
[
0
]
,
self
.
contrast_range
[
1
]
)
images
=
tf.
image
.
adjust_contrast
(
images
,
contrast_factor
)
Random saturation adjustment
images
=
tf.
image
.
random_saturation
(
images
,
0.5
,
1.5
)
return
images
Practical Exercise
Exercise 1: Image standardization comparison
Load a test image, apply the following standardization methods respectively, and visualize the results:
- Divide by 255 ([0,1] range)
- ImageNet mean-standard deviation standardization (mean=[0.485,0.456,0.406], std=[0.229,0.224,0.225])
- Custom standardization (e.g., scale to [-1,1] range)
Exercise 2: Observing data augmentation effects
Select an image, apply different combinations of augmentation techniques (flip + rotation + color adjustment), generate 10 augmented versions and display them in an arrangement to observe the augmentation effects.
Exercise 3: Complete preprocessing pipeline
Build a complete image preprocessing pipeline with the following steps:
- Load images from TFRecord
- Decode images
- Randomly crop to 256x256
- Random horizontal flip
- Standardize to [-1,1] range
- Create a dataset with batch size 32
Frequently Asked Questions
Q1: How to handle images of different sizes?
A: Usetf.image.resizeto unify sizes, or usetf.image.resize_with_crop_or_padto crop/pad while maintaining the aspect ratio.
Q2: Should image processing be done on CPU or GPU?
A: It is generally recommended to perform image preprocessing on CPU, usingtf.data.Dataset.map'snum_parallel_callsparameter for parallel processing.
Q3: How to avoid information loss caused by data augmentation?
A: Set augmentation parameter ranges reasonably; for critical tasks (such as medical images), use geometric transformations cautiously and prioritize color space transformations.
Q4: Best practices for handling extremely large images?
A: Consider usingtf.image.extract_patchesto split large images into small blocks, or use progressive loading techniques.