Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

How do I add reversible noise to the MNIST dataset using PyTorch?

$
0
0

I would like to add reversible noise to the MNIST dataset for some experimentation.

Here's what I am trying atm:

import torchvision.transforms as transformsfrom torchvision.datasets import MNISTfrom torch.utils.data import DataLoaderfrom PIL import Imageimport torchvisiondef display_img(pixels, label = None):    plt.imshow(pixels, cmap="gray")    if label:            plt.title("Label: %d" % label)    plt.axis("off")    plt.show()class NoisyMNIST(torchvision.datasets.MNIST):    def __init__(self, root, train=True, transform=None, target_transform=None, download=False):        super(NoisyMNIST, self).__init__(root, train=train, transform=transform, target_transform=target_transform, download=download)    def __getitem__(self, index):        img, target = self.data[index], self.targets[index]        img = Image.fromarray(img.numpy(), mode="L")        if self.transform is not None:            img = self.transform(img)        # add the noise        noise_level = 0.3        noise = self.generate_safe_random_tensor(img) * noise_level        noisy_img = img + noise        return noisy_img, noise, img, target    def generate_safe_random_tensor(self, img):"""generates random noise for an image but limits the pixel values between -1 and 1"""         min_values = torch.clamp(-1 - img, max=0)        max_values = torch.clamp(1 - img, min=0)        return torch.rand(img.shape) * (max_values - min_values) + min_values# Define transformations to apply to the datatransform = transforms.Compose([    transforms.ToTensor(),  # Convert images to tensors    transforms.Normalize((0.1307,), (0.3081,)),])train_dataset = NoisyMNIST(root='./data', train=True, download=True, transform=transform)test_dataset = NoisyMNIST(root='./data', train=False, download=True, transform=transform)np_noise = train_dataset[img_id][1]np_data = train_dataset[img_id][0]display_img(np_data_sub_noise, 4)

Ideally, this would give me the regular MNIST dataset along with a noisy MNIST images and a collection of the noise that was added. Given this, I had assumed I could subtract the noise from the noisy image and go back to the original image, but my image operations are not reversible.

Any pointers or code snippets would be greatly appreciated. Below are the images I currently get wit my code:

Original image:

enter image description here

With added noise:

enter image description here

And with the noise subtracted for the image with noise:

enter image description here


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>