You're in luck! The kornia.augmentation.RandomMotionBlur augmentation is designed to pick the angle randomly if you provide it as a range.
The angle parameter can accept:
A single float: This will use a fixed angle.
A tuple (min_angle: float, max_angle: float): This will randomly sample an angle uniformly from the range [min_angle, max_angle] for each image in the batch (unless same_on_batch=True). Angles are typically specified in degrees.
Here's how you can do it:
python
import torch
import kornia.augmentation as K
import kornia.io as KI # For loading/saving if needed
import torchvision.transforms.functional as TF # For PIL to tensor
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# 1. Load a sample image (or create a dummy tensor)
try:
# Example: Load an image using PIL and convert to tensor
# Make sure you have an image file 'sample_image.jpg' or change the path
img_pil = Image.open("sample_image.jpg").convert("RGB")
img_tensor = TF.to_tensor(img_pil).unsqueeze(0) # Add batch dimension (B, C, H, W)
except FileNotFoundError:
print("sample_image.jpg not found. Using a random tensor instead.")
img_tensor = torch.rand(1, 3, 256, 256) # (B, C, H, W)
# 2. Define the RandomMotionBlur augmentation with a random angle range
# Let's pick an angle randomly between 0 and 360 degrees
min_angle = 0.0
max_angle = 360.0
# You also need to define kernel_size and direction
# kernel_size can be an int or a tuple (min_k, max_k) for random kernel size
# direction is a float or tuple (min_d, max_d) for random direction strength/phase
motion_blur_aug = K.RandomMotionBlur(
kernel_size=(7, 15), # Random kernel size between 7 and 15 (odd numbers preferred)
angle=(min_angle, max_angle), # Random angle between 0 and 360 degrees
direction=(-0.75, 0.75), # Random direction factor
p=1.0 # Apply always for this demo
)
# 3. Apply the augmentation
# If you have multiple images in a batch, each might get a different random angle
# (unless same_on_batch=True)
blurred_tensor = motion_blur_aug(img_tensor)
# 4. Visualize or save (optional)
def show_tensor_image(image_tensor, title=''):
if image_tensor.is_cuda:
image_tensor = image_tensor.cpu()
# Remove batch dimension if it exists and has size 1
if image_tensor.dim() == 4 and image_tensor.size(0) == 1:
image_tensor = image_tensor.squeeze(0)
plt.imshow(image_tensor.permute(1, 2, 0).numpy()) # C, H, W -> H, W, C
plt.title(title)
plt.axis('off')
plt.show()
print(f"Original image shape: {img_tensor.shape}")
print(f"Blurred image shape: {blurred_tensor.shape}")
# To see the parameters chosen for this specific application (if return_transform=True)
# motion_blur_aug_with_transform = K.RandomMotionBlur(
# kernel_size=(7, 15), angle=(min_angle, max_angle), direction=(-0.75, 0.75), p=1.0, return_transform=True
# )
# blurred_tensor_val, transform_params = motion_blur_aug_with_transform(img_tensor)
# print(f"Applied transform parameters: {transform_params}")
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
show_tensor_image(img_tensor, "Original Image")
plt.subplot(1, 2, 2)
show_tensor_image(blurred_tensor, f"Motion Blurred (Angle in [{min_angle}, {max_angle}])")
plt.show()
# If you want to apply multiple times to see different random angles:
print("\nApplying multiple times to show different random angles:")
for i in range(3):
blurred_again = motion_blur_aug(img_tensor)
# If you had return_transform=True, you could print the specific angle chosen
# _, params = motion_blur_aug_with_transform(img_tensor)
# print(f"Run {i+1} - Angle: {params['angle_factor']}") # Check Kornia docs for exact key
plt.figure()
show_tensor_image(blurred_again, f"Blurred Run {i+1}")
plt.show()
Key takeaway:
To make the angle random, simply pass a tuple (min_value, max_value) to the angle parameter of RandomMotionBlur. Kornia will then sample a value from this range for you. The same principle applies to kernel_size and direction if you want those to be random as well.