Created
October 3, 2024 16:07
-
-
Save brayevalerien/47b06d02fe362bfdf6d6dfe30b5ee931 to your computer and use it in GitHub Desktop.
Small python script that adds some noise to all images in a dataset.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import argparse | |
import numpy as np | |
from PIL import Image | |
from tqdm import tqdm | |
def add_gaussian_noise(image: Image, factor: float): | |
""" | |
Add a given amount of white guassian noise to an image. | |
Args: | |
image (Image): original image. | |
factor (float): amount of noise to mix, between 0 and 1. | |
Returns: | |
PIL.Image: The noisy image. | |
""" | |
image_array = np.array(image) | |
mean = 0 | |
sigma = factor * 255 | |
noise = np.random.normal(mean, sigma, image_array.shape) | |
noisy_image = image_array + noise | |
noisy_image = np.clip(noisy_image, 0, 255).astype(np.uint8) | |
return Image.fromarray(noisy_image) | |
def main(): | |
parser = argparse.ArgumentParser(description='Adds Gaussian noise to images in a dataset.') | |
parser.add_argument('--dataset', type=str, required=True, help='Path to the dataset directory.') | |
parser.add_argument('--factor', type=float, required=True, help='Amount of noise to mix, between 0 and 1.') | |
args = parser.parse_args() | |
if not (0 <= args.factor <= 1): | |
raise ValueError(f"The noise factor should be between 0 and 1 (got {args.factor}).") | |
for filename in tqdm(os.listdir(args.dataset), "Adding noise", unit="img(s)"): | |
if filename.lower().endswith(('.png', '.jpg', '.jpeg')): | |
img_path = os.path.join(args.dataset, filename) | |
image = Image.open(img_path).convert('RGB') | |
noisy_image = add_gaussian_noise(image, args.factor) | |
noisy_image.save(img_path) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment