Reputation: 1376
I want to randomly invert some of the pixels of an image, that's what I mean by "Partial Inversion". This is definitely feasible using two for loops but I am looking for a faster operation since this operation is to be applied to a lot of images in the dataset. I didn't find any operation in the PIL documentation. I am attaching a sample image for the reference, assume it has all channels (RGB). Any help would be appreciated.
Upvotes: 0
Views: 337
Reputation: 36684
Will you consider solutions other than PIL
? It's very easy to manipulate pixels with numpy
. To invert, just subtract the array values from 255.
import tensorflow as tf
import torch
import matplotlib.pyplot as plt
(x, _), (_, _) = tf.keras.datasets.mnist.load_data()
x = x[0]
x = torch.cat([x[:14, :], 255 - x[14:, :]])
plt.imshow(x.numpy(), cmap='Greys')
You can call it in your transforms like this:
torchvision.transforms.Lambda(lambda x: torch.cat([x[:14, :], 255 - x[14:, :]]))
Upvotes: 1