Sling Academy
Home/Tensorflow/TensorFlow Image: Applying Filters and Transformations

TensorFlow Image: Applying Filters and Transformations

Last updated: December 17, 2024

With the vast data growth in the modern era, images have become one of the most common types of data. Hence, performing manipulations, transformations, and processing on them has never been more critical. In this article, we will delve into how you can apply filters and transformations to images using TensorFlow, one of the most popular machine learning frameworks. TensorFlow provides several tools that make it easy to process and transform images.

Setting up TensorFlow

To get started, ensure you have TensorFlow installed in your environment. If not, you can install it using pip:

pip install tensorflow

Now, let’s move into some image processing tasks with TensorFlow.

Loading an Image

Before applying any transformations, we first need to load the image. TensorFlow’s tf.image module offers a range of functions to manipulate images effectively. Let’s begin by reading an image from disk:

import tensorflow as tf
import matplotlib.pyplot as plt

image_path = "/path/to/your/image.jpg"
# Read the image file
image = tf.io.read_file(image_path)
# Decode it into a formatted tensor
image = tf.image.decode_jpeg(image, channels=3)

# Display the image
plt.imshow(image.numpy())
plt.axis('off')
plt.show()

Applying Filters to Images

Filters in image processing can enhance certain features or even reduce noise. TensorFlow offers several built-in operations you can use.

1. Converting to Grayscale

Transforming an image to grayscale is simple:

grayscale_image = tf.image.rgb_to_grayscale(image)
plt.imshow(grayscale_image.numpy().squeeze(), cmap='gray')
plt.axis('off')
plt.show()

2. Adjusting Brightness

You can easily increase or decrease the brightness of an image:

brighter_image = tf.image.adjust_brightness(image, delta=0.2)
plt.imshow(brighter_image.numpy())
plt.axis('off')
plt.show()

3. Applying Gaussian Blur

To apply more complex filters like Gaussian blur, TensorFlow’s operations will need to be a bit customized using convolution filters:

def gaussian_blur(image, kernel_size=5, sigma=1.0):
    # Gaussian Kernel Creation
    x = tf.range(-kernel_size // 2 + 1, kernel_size // 2 + 1)
    x = tf.exp(-tf.pow(x, 2) / (2.0 * tf.pow(sigma, 2)))
    x = x / tf.reduce_sum(x)
    kernel = tf.matmul(tf.expand_dims(x, 1), tf.expand_dims(x, 0))
    kernel = tf.expand_dims(tf.expand_dims(kernel, -1), -1)
    image = tf.pad(tf.expand_dims(image, 0), paddings=[[0, 0], [kernel_size // 2, kernel_size // 2], [kernel_size // 2, kernel_size // 2], [0, 0]], mode='REFLECT')
    blurred_image = tf.nn.depthwise_conv2d(image, tf.tile(kernel, [1, 1, tf.shape(image)[-1], 1]), [1, 1, 1, 1], padding='VALID')
    return tf.squeeze(blurred_image, axis=0)

blurred_image = gaussian_blur(image)
plt.imshow(blurred_image.numpy())
plt.axis('off')
plt.show()

Transforming Images

In addition to applying filters, you can also perform transformations, such as rotating, flipping, and scaling images.

1. Rotating an Image

Rotate images with the tf.image.rot90 function:

rotated_image = tf.image.rot90(image, k=1)  # Rotate 90 degrees counterclockwise
plt.imshow(rotated_image.numpy())
plt.axis('off')
plt.show()

2. Flipping an Image

You can easily flip images horizontally or vertically:

flipped_image = tf.image.flip_left_right(image)
plt.imshow(flipped_image.numpy())
plt.axis('off')
plt.show()

3. Resizing Images

To scale images to a new size, use:

resized_image = tf.image.resize(image, [128, 128])
plt.imshow(resized_image.numpy().astype('uint8'))
plt.axis('off')
plt.show()

Conclusion

TensorFlow provides a powerful set of tools to perform image filtrations and transformations. Whether you're preparing data for machine learning tasks or enhancing images for visualization, these functionalities can help in processing images efficiently. Perhaps the most significant benefit is the seamless integration of these operations into a larger deep-learning workflow, all within the TensorFlow ecosystem. As you become more comfortable with these tools, you’ll be able to craft more complex and tailored image processing pipelines.

Next Article: TensorFlow Image: Creating Image Pipelines for Training

Previous Article: TensorFlow Image: Working with Image Masks

Series: Tensorflow Tutorials

Tensorflow

You May Also Like

  • TensorFlow `scalar_mul`: Multiplying a Tensor by a Scalar
  • TensorFlow `realdiv`: Performing Real Division Element-Wise
  • Tensorflow - How to Handle "InvalidArgumentError: Input is Not a Matrix"
  • TensorFlow `TensorShape`: Managing Tensor Dimensions and Shapes
  • TensorFlow Train: Fine-Tuning Models with Pretrained Weights
  • TensorFlow Test: How to Test TensorFlow Layers
  • TensorFlow Test: Best Practices for Testing Neural Networks
  • TensorFlow Summary: Debugging Models with TensorBoard
  • Debugging with TensorFlow Profiler’s Trace Viewer
  • TensorFlow dtypes: Choosing the Best Data Type for Your Model
  • TensorFlow: Fixing "ValueError: Tensor Initialization Failed"
  • Debugging TensorFlow’s "AttributeError: 'Tensor' Object Has No Attribute 'tolist'"
  • TensorFlow: Fixing "RuntimeError: TensorFlow Context Already Closed"
  • Handling TensorFlow’s "TypeError: Cannot Convert Tensor to Scalar"
  • TensorFlow: Resolving "ValueError: Cannot Broadcast Tensor Shapes"
  • Fixing TensorFlow’s "RuntimeError: Graph Not Found"
  • TensorFlow: Handling "AttributeError: 'Tensor' Object Has No Attribute 'to_numpy'"
  • Debugging TensorFlow’s "KeyError: TensorFlow Variable Not Found"
  • TensorFlow: Fixing "TypeError: TensorFlow Function is Not Iterable"