【PyTorch】生成一张随机噪声图片

在这里插入图片描述

环境

PyTorch安装教程:Windows | Linux | Mac

代码

from torchvision.transforms import ToPILImage
import torch


def random_noise(nc, width, height):
    '''Generator a random noise image from tensor.

    If nc is 1, the Grayscale image will be created.
    If nc is 3, the RGB image will be generated.

    Args:
        nc (int): (1 or 3) number of channels.
        width (int): width of output image.
        height (int): height of output image.
    Returns:
        PIL Image.
    '''
    img = torch.rand(nc, width, height)
    img = ToPILImage()(img)
    return img


if __name__ == '__main__':
    random_noise(3, 256, 256).save('random-noise.jpg')

结果

彩色图灰度图

参考

https://pytorch.org/docs/stable/generated/torch.rand.html#torch-rand
https://pytorch.org/vision/stable/transforms.html#torchvision.transforms.ToPILImage

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是使用PyTorch生成图片脉冲噪声并将其保存到原文件夹下的示例代码: ```python import os import torch import torchvision.transforms as transforms from PIL import Image # 定义脉冲噪声函数 def pulse_noise(image_size, prob): noise = torch.rand(image_size) mask = noise < prob noise[mask] = 1 noise[~mask] = 0 return noise # 设置文件路径和名称 file_path = "path/to/file.png" file_name = os.path.basename(file_path) # 读取原始图片文件 img = Image.open(file_path) # 转换图片为张量 transform = transforms.ToTensor() img_tensor = transform(img) # 生成脉冲噪声并添加到图片张量上 image_size = img_tensor.shape[-2:] prob = 0.1 noise = pulse_noise(image_size, prob) noisy_img_tensor = img_tensor.clone() for i in range(img_tensor.shape[0]): noisy_img_tensor[i] = img_tensor[i] + noise # 将有噪声图片张量转换为PIL图片并保存 noisy_img = transforms.ToPILImage()(noisy_img_tensor) noisy_file_path = os.path.join(os.path.dirname(file_path), "noisy_" + file_name) noisy_img.save(noisy_file_path) ``` 在这个示例中,我们首先使用`os.path`模块获取原始图片文件的路径和名称,并使用Pillow库中的`Image.open`函数加载原始图片文件。然后,我们使用`torchvision.transforms`模块中的`ToTensor`函数将图片转换为张量,并使用之前定义的`pulse_noise`函数生成脉冲噪声。接着,我们将脉冲噪声添加到图片张量上,生成噪声图片张量。 最后,我们将有噪声图片张量转换为PIL图片,并使用`save`函数将其保存到与原始文件相同的目录下,并在文件名前加上前缀"noisy_"。 你可以根据需要修改脉冲出现概率或保存文件的前缀。注意,这个示例仅适用于PNG格式的图片文件,如果你要处理其他格式的图片文件,需要使用相应的库进行加载和保存。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Xavier Jiezou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值