Skip to main content

What is per_image_whitening function in TENSORFLOW

 The per_image_whitening function in TensorFlow (Abadi et al., 2015) is used to normalize individual images by adjusting their mean and standard deviation independently. This technique ensures that each image has zero mean and a unit standard deviation, which helps improve the training stability of deep learning models.


How per_image_whitening Works

For a given image II, the function applies the following transformation:

I=IμσI' = \frac{I - \mu}{\sigma}

where:

  • II is the input image (tensor).

  • μ\mu is the mean pixel value of the image.

  • σ\sigma is the adjusted standard deviation (explained below).

  • II' is the whitened image.

Adjusted Standard Deviation Calculation:
Unlike a standard standard deviation calculation, TensorFlow adjusts it slightly to prevent division by zero. The formula used is:

σ=1Ni=1N(Iiμ)2+ϵ\sigma = \sqrt{\frac{1}{N} \sum_{i=1}^{N} (I_i - \mu)^2 + \epsilon}

where:

  • NN is the total number of pixels in the image.

  • ϵ\epsilon is a small constant (e.g., 1e101e^{-10}) added to avoid division by zero.


Key Properties of per_image_whitening

  1. Zero Mean: The mean pixel value of the image becomes 0.

  2. Unit Variance (with adjustment): The standard deviation is adjusted to avoid division by very small values.

  3. Applied Per Image: Unlike batch normalization, which normalizes across a batch of images, this method is applied independently to each image.

  4. Useful for CNNs: Helps improve convergence by ensuring uniform feature scaling.


TensorFlow Implementation

In TensorFlow (older versions), the function was available as:

import tensorflow as tf

# Load or define an image tensor (H, W, C)
image = tf.random.normal(shape=[128, 128, 3])  # Example image

# Apply per-image whitening
whitened_image = tf.image.per_image_standardization(image)

# This function performs per-image whitening as:
# I' = (I - mean) / adjusted_std

Modern TensorFlow (TF 2.x) Equivalent

The function tf.image.per_image_standardization performs the same operation:

import tensorflow as tf

def per_image_whitening(image):
    mean = tf.reduce_mean(image)
    stddev = tf.math.reduce_std(image)
    adjusted_stddev = tf.math.maximum(stddev, 1.0 / tf.sqrt(tf.cast(tf.size(image), tf.float32)))
    return (image - mean) / adjusted_stddev

# Example Image Tensor
image = tf.random.normal([128, 128, 3])

# Apply Whitening
whitened_image = per_image_whitening(image)

  • Let's break down per-image whitening step by step with a visualization approach. We'll generate a sample image, compute the mean and standard deviation, and apply whitening while displaying intermediate results.

Step 1: Generate a Sample Image

We'll create a random image (128 × 128 pixels with 3 color channels) to simulate an actual image.

Step 2: Compute the Mean and Standard Deviation

We calculate:

  • μ\mu = mean pixel value

  • σ\sigma = adjusted standard deviation

Step 3: Apply Whitening Transformation

Each pixel is transformed using:

I=IμσI' = \frac{I - \mu}{\sigma}

where σ\sigma is adjusted to avoid division by zero.

Step 4: Visualize the Changes

We'll show:

  1. The original image.

  2. The pixel intensity histogram before and after whitening.

  3. The whitened image.


Python Code for Visualization

We'll use TensorFlow for preprocessing and Matplotlib for visualization.

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

# Generate a random image (128x128 with 3 channels)
image = tf.random.uniform(shape=[128, 128, 3], minval=0, maxval=255, dtype=tf.float32)

# Function to perform per-image whitening
def per_image_whitening(image):
    mean = tf.reduce_mean(image)
    stddev = tf.math.reduce_std(image)
    adjusted_stddev = tf.maximum(stddev, 1.0 / tf.sqrt(tf.cast(tf.size(image), tf.float32)))
    whitened_image = (image - mean) / adjusted_stddev
    return whitened_image, mean, stddev, adjusted_stddev

# Apply Whitening
whitened_image, mean, stddev, adjusted_stddev = per_image_whitening(image)

# Convert to numpy for visualization
image_np = image.numpy() / 255.0  # Normalize for display
whitened_image_np = (whitened_image.numpy() - np.min(whitened_image.numpy())) / \
                    (np.max(whitened_image.numpy()) - np.min(whitened_image.numpy()))

# Plot original and whitened images
fig, ax = plt.subplots(1, 3, figsize=(15, 5))

ax[0].imshow(image_np)
ax[0].set_title(f"Original Image\nMean: {mean.numpy():.2f}, Std: {stddev.numpy():.2f}")
ax[0].axis("off")

ax[1].hist(image_np.ravel(), bins=50, color='blue', alpha=0.7)
ax[1].set_title("Pixel Intensity Histogram (Before Whitening)")

ax[2].hist(whitened_image_np.ravel(), bins=50, color='red', alpha=0.7)
ax[2].set_title("Pixel Intensity Histogram (After Whitening)")

plt.show()

Expected Results

  1. Original Image: Displays the raw image with its original color distribution.

  2. Histogram Before Whitening: Shows a spread of pixel values between 0 and 255.

  3. Histogram After Whitening: Now centered around zero mean with unit variance.


Conclusion

  • The adjusted standard deviation ensures numerical stability.

  • per_image_whitening is independent for each image, unlike batch normalization.

  • It is commonly used in preprocessing pipelines for image models.


 

Comments

Popular posts from this blog

Simple Linear Regression - and Related Regression Loss Functions

Today's Topics: a. Regression Algorithms  b. Outliers - Explained in Simple Terms c. Common Regression Metrics Explained d. Overfitting and Underfitting e. How are Linear and Non Linear Regression Algorithms used in Neural Networks [Future study topics] Regression Algorithms Regression algorithms are a category of machine learning methods used to predict a continuous numerical value. Linear regression is a simple, powerful, and interpretable algorithm for this type of problem. Quick Example: These are the scores of students vs. the hours they spent studying. Looking at this dataset of student scores and their corresponding study hours, can we determine what score someone might achieve after studying for a random number of hours? Example: From the graph, we can estimate that 4 hours of daily study would result in a score near 80. It is a simple example, but for more complex tasks the underlying concept will be similar. If you understand this graph, you will understand this blog. Sim...

What problems can AI Neural Networks solve

How does AI Neural Networks solve Problems? What problems can AI Neural Networks solve? Based on effectiveness and common usage, here's the ranking from best to least suitable for neural networks (Classification Problems, Regression Problems and Optimization Problems.) But first some Math, background and related topics as how the Neural Network Learn by training (Supervised Learning and Unsupervised Learning.)  Background Note - Mathematical Precision vs. Practical AI Solutions. Math can solve all these problems with very accurate results. While Math can theoretically solve classification, regression, and optimization problems with perfect accuracy, such calculations often require impractical amounts of time—hours, days, or even years for complex real-world scenarios. In practice, we rarely need absolute precision; instead, we need actionable results quickly enough to make timely decisions. Neural networks excel at this trade-off, providing "good enough" solutions in seco...

Activation Functions in Neural Networks

  A Guide to Activation Functions in Neural Networks 🧠 Question: Without activation function can a neural network with many layers be non-linear? Answer: Provided at the end of this document. Activation functions are a crucial component of neural networks. Their primary purpose is to introduce non-linearity , which allows the network to learn the complex, winding patterns found in real-world data. Without them, a neural network, no matter how deep, would just be a simple linear model. In the diagram below the f is the activation function that receives input and send output to next layers. Commonly used activation functions. 1. Sigmoid Function 2. Tanh (Hyperbolic Tangent) 3. ReLU (Rectified Linear Unit - Like an Electronic Diode) 4. Leaky ReLU & PReLU 5. ELU (Exponential Linear Unit) 6. Softmax 7. GELU, Swish, and SiLU 1. Sigmoid Function                       The classic "S-curve," Sigmoid squashes any input value t...